Reset the counter variable when a certain condition is met

I am facing an issue with my simple "pagination" counter that fetches the next page from an API. The problem arises when I switch between different categories, such as movies or series, because the counter does not reset. Instead of starting again from the first page of the new category, it continues from where it left off.

Despite trying various conditional combinations, none have proven effective so far. I believe solving this should not be too difficult; however, I am struggling to think of the right logic to implement.

let page = 1; 
document.getElementById('load-more').addEventListener('click', () => {
    page++;

    const movies = document.getElementById('movies');
    const series = document.getElementById('series');

    if(movies.classList.contains('active-link')) {

        getMovies(page);

    } else if (series.classList.contains('active-link')) {

        getSeries(page);

    }
})

Resetting the let counter inside the if..else statement does not work as expected, since clicking the load more button resets it back to page 1 each time.

Answer №1

It is advisable to assign separate variables for the current movies page and the current series page in your code. Additionally, consider streamlining your logic by utilizing a single querySelector instead of multiple selections combined with classList.contains:

let currentPageMovies = 1;
let currentPageSeries = 1;
document.getElementById('load-more').addEventListener('click', () => {
  if (document.querySelector('#movies.active-link')) {
    currentPageMovies++;
    loadContent('movies', currentPageMovies);
  } else if (document.querySelector('#series.active-link')) {
    currentPageSeries++;
    loadContent('series', currentPageSeries);
  }
});

Answer №2

Make sure to add an event listener for the click event on both your #movies and #series links.

Within this function, assign the value of 1 to the page variable.

This is a common practice when transitioning between lists, often resulting in a reset of the paging system.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The file always fails the Regex test in Node.js

I am dealing with a log file that contains lines structured like this: [Thu Mar 30 2017 11:24:51 GMT+0100 (WEST)] {"serial":"CA-2M-1107619","type":"iface","body":{"action":"up","device":"tun_man","ip":"127.255.0.10","ip6":"2016:900d:c0de::1001"} My goal ...

Developing front-end libraries using the jspm workflow

What is the best way to convert a library written in TypeScript to ES5? While JSPM documentation focuses on web apps (such as with jspm bundle-sfx), the information I've found on Google seems more suited for a web app workflow rather than a library w ...

What is the best way to retrieve JSON key/value pairs instead of an array?

I am working on retrieving data from a Google Spreadsheet using App Script and have set up a DoGet function. Currently, I am getting an array of data but I need it in JSON key-value pairs format. The table in my Google Sheets is structured as follows: Th ...

Sort the array by unique ID and retrieve the object with the first and last index

I am working with an array that looks like this: [{ "res": [ '123', 'One', '20210318' ] }, { "res": [ '123', 'One', '20210319' ] }, { "res": [ '123&ap ...

Open a JavaScript file to retrieve data from a nearby JSON object

I've been trying to access a local JSON file using a JavaScript file, but for some reason it's not working. Even though I'm sure the URL is correct, the code keeps failing to retrieve data from the JSON object. JavaScript file: var pieData ...

Tips for launching a colorbox within a specific div container

I am looking to implement a color box that opens without a popup and only shows/hides inside a specific div. Is it possible to target a div to open the colorbox content? <a href='#myGallery' class='group'>click here</a> &l ...

Angular 2: Change Boolean value depending on a condition

I find myself facing a challenge with a search-bar feature. My goal is to display all the filtered names when the input value reaches a length of 2 or more characters. After successfully extracting the value.length from the input field, I encountered a ro ...

Retrieve the contents of a script using JavaScript

I have a script on my webpage that looks like this: <script> window.__INITIAL_STATE__ = {"meReducer":{"me":{"id":1234,"groupId":789,"},},//more code removed}; </script> I am looking to trigger a ...

checkbox revision

I'm attempting to update some text indicating whether or not a checkbox is checked. The issue is that when the checkbox is checked, the textbox disappears and the text takes its place. <form name="myForm" id="myForm"> <input type="checkb ...

RequireJS - Enabling the loading of multiple module instances

I am working on a custom RequireJS plugin that needs to create a new object instance every time it is called. For illustration purposes, consider the following: define("loader", { load: function(name, req, onload, config) { var instance = GlobalGet ...

Updating textures dynamically for individual faces in a three.js environment

I have been facing a difficult challenge for some time now, struggling to achieve my goal while unsure if I am on the right path. The Objective My current project involves developing a three.js web application that loads JavaScript models and assigns cu ...

What are the steps for showcasing a personalized HTML tag on a web page

I need to capture user input text and display it correctly. This is what I have attempted: <div> <input type="text" ng-model="post.content" /> </div> <div> <div ng-bind-html="post.content| htmlize"></div> < ...

encountering a glitch during the electron.js build process with nextjs

When attempting to build Electron.js with Next.js, I keep encountering this persistent error. I have updated my packages and reinstalled node modules multiple times, but I am still unable to resolve it. C:\Users\Himanshu\Desktop\claros& ...

Establish the following 13 steps to configure the initial server state and retrieve the client state

Currently, I have 13 applications and I am utilizing Zustand as my state manager. Below is a simple layout example: <MainProvider> <div className="min-h-screen flex flex-col"> <Navbar></Navbar> <main className ...

Utilize string paths for images instead of requires when resolving img src and background-image URLs

I have successfully implemented image loading with webpack using the file loader, but only when I require or import images. I am curious about how create-react-app achieves the functionality where everything in the public folder is accessible, for example, ...

Using a function to send multiple child data in Firebase

I am trying to figure out how to save data to a Firebase multi-child node structure: --Events ----Races -------Participants Below is some dummy data example that represents the type of data I need to store in Firebase: var dummyData = [ { ...

Looking to show a div upon clicking a link with the use of Javascript

Looking for a workaround due to restrictions on using alert or any Js dialog box, I need to create some sort of magic trick: 1. Create a div with a link named "info". 2. Develop an invisible div that will serve as my "PopUp" containing random information. ...

HackerRank Challenge: Strategies for Efficiently Solving Minimum Swaps 2

In this challenge, the goal is to determine the minimum number of swaps needed to arrange an array of disordered consecutive digits in ascending order. My code successfully handles most of the tests, but I'm encountering timeout errors with four speci ...

What is the method for defining distinct parameters for nested functions in AngularJS?

When using AngularJS, what happens when a parent function encapsulates a child function that includes parameters not present in the parent? In this scenario illustrated below with the green arrow representing the parent function without any parameters, an ...

What are the steps to adjust the width of a website from the standard size to a widescreen

Is it possible to create a "floating" screen adjustment on websites? I know you can set the standard size of pixels, but how do sites adjust for different screen sizes like wider laptop screens? Does it automatically detect the reader's screen size an ...