Avoid going through divs repeatedly in Javascript

Here is the code snippet I am working with:

function loopCalendar() { // function to loop through calendar elements
    var labels = loopDivs('calendarDiv', 'btn_'), // loop through calendar buttons
        arrows = loopDivs('calendarDiv', 'icon_'), // loop through calendar arrows
        content = loopDivs('calendarDiv', 'content_'); // loop through calendar content

    for (var i = 0; i < labels.length; i++) {
        var l = labels[i],
            a = arrows[i],
            c = content[i];

        (function(l, a, c) {
            // add event listener on click and touch events
            On(document.getElementById(l), ['click', 'touch'], function(e){
                // display the content of the clicked div
                showContent(c, a);
                // loop through calendar availabilities
                loopAvailabilities(c);
            });
        })(l, a, c);
    }
}

The function loopDivs() retrieves all the ids from a given div with a specified id.

In essence, this script iterates over a calendar and retrieves the id of each month, the id of each arrow representing an open/close icon for the respective month, and the id of the content containing booking availabilities for the month. After completing the iteration, it displays the content of that month and then proceeds to loop through the days of that month using loopAvailabilities(). In loopAvailabilities(), there is another similar script that adds an AJAX GET request to each day to fetch their availabilities when clicked.

While everything functions correctly initially, an issue arises when I close and reopen a month causing the AJAX REQUEST associated with a particular day to make multiple calls. Subsequently, if I repeat the process of opening and closing the month, the AJAX requests multiply accordingly.

What measures can be taken to prevent the repetitive calls of the AJAX request?

If you require additional parts of the script, please inform me as it contains extended code with similar functionalities along with AJAX calls.

Answer №1

Make sure to detach the click and touch event before you attach it again. Each time the loopCalendar method is called, an extra event handler is being added.

On(document.getElementById(l), ['click', 'touch'], function(e){ }) This is where the issue arises. You must undo the previous attached handler or ensure that it is only executed once for each element.

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

Is it feasible to create that specific character using Google Charts?

Quick question here. Can a Char be generated in Google Charts? Also, do you have any advice on how to do this? Chart1 The blank space under the chart is crucial. ...

How can I retain the value of a String even after clicking the Submit button on a .jsp page?

I am encountering an issue where, after clicking the submit button, I lose the content that was previously stored in my textToConsole variable. Post submission, only "hello" remains in the variable. How can I prevent the loss of the text: "world!"? <% ...

Selection pseudo selectors for tooltips are a great way to provide additional

Can someone explain how tooltips change on Medium.com when you double click a word or sentence to reveal options like share and edit? https://i.stack.imgur.com/0EVmH.png ...

What is the correct way to use "DELETE" and "BACKSPACE" in a condition statement?

Attempting to prevent the deletion of input values when the length is 2 or lower, but my if statement doesn't seem quite right. $(document).ready(function() { $('#mobile').val("09"); // Set initial value to "09" $('#mobile&ap ...

There seems to be an issue with the ajax functionality as I am not receiving any

I'm struggling with inserting a name into my database. I have a form that asks for the name and a submit button. However, when I click the submit button, no alert is shown. I am new to using ajax. This code is from index.php. <html> <he ...

Exploring and Troubleshooting HTML and JavaScript with Visual Studio Code Debugger

Visual Studio Code Version 1.10.2 Windows 10 I am currently experimenting with VS Code and would like to debug some basic HTML and JavaScript code. The instructional video found at http://code.visualstudio.com/docs/introvideos/debugging mentions that ...

Is there a way to restore a previous version of package-lock.json?

Currently, I am facing the challenge of adjusting a JS/node project that includes a package.json but lacks a committed package-lock.json file. Additionally, the original package-lock.json from the author is not available as newer versions have been develop ...

Having trouble persisting data with indexedDB

Hi there, I've encountered an issue with indexedDB. Whenever I attempt to store an array of links, the process fails without any visible errors or exceptions. I have two code snippets. The first one works perfectly: export const IndexedDB = { initDB ...

Is it feasible to showcase collections from MongoDB and every individual element from all collections on a single EJS page?

I am currently working on developing a forum for my website using NodeJs, Express, MongoDB, and EJS for HTML rendering. However, I encountered an error message saying: "cannot set headers after they are sent to the client." I am a bit confused about this i ...

Error encountered while using XLSX.write in angular.js: n.t.match function is not recognized

I've encountered an issue while trying to generate an .xlsx file using the XLSX library. The error message I received is as follows: TypeError: n.t.match is not a function at Ps (xlsx.full.min.js:14) at Jd (xlsx.full.min.js:18) at Sv (xlsx.full.min ...

Enhance the efficiency of React code by optimizing the loading of data from multiple sources concurrently instead of one after another

In my project, there are 2 tabs displaying visualizations generated from separate data sources. Each tab requires multiple queries to be executed in the background to fetch the data, resulting in a delay when loading each tab individually. The current impl ...

Preventing Prepend Scroll: Tips and Tricks

Adding extra content to the top of the body can be frustrating, especially if it pushes everything down as you're trying to read. Is there a way to smoothly prepend this additional content without shifting the page layout, so that it seamlessly appear ...

Changing Https to Http in Cpanel for Website Redirection

Currently, I am working on redirecting my https traffic to http while waiting for my SSL renewal. Google Chrome continues to display the certificate date error indicating it is invalid. Despite attempting to update my .htaccess file, I have been unsucces ...

Code to track the changes made to a specific cell in Google Sheets

I am currently collaborating on a file with multiple individuals and I would like to create a script that can identify the person who last modified a specific cell, along with the timestamp of when the modification occurred. All I need is the email address ...

What is the best way to access a sub-object within a JSON object when the object's name is unknown?

I have a JSON object called data with the following content: {"query":{"pages":{"856":{"pageid":856,"ns":0,"title":"Announcements","revisions":[{"*":"* News item number one\n* News item number two"}]}}},"query-continue":{"revisions":{"rvstartid":1244 ...

CKEditor's height automatically increases as the user types

I am using a ckEditor and looking for a way to make its height automatically grow as I type. https://i.stack.imgur.com/m7eyi.png <textarea name="description" id="description"> </textarea> <script> CKEDITOR.replace( 'description ...

Timeout for AngularJS Bootstrap UI Modal

I am having some trouble with opening a bootstrap modal using the $timeout function. The issue I am facing is that the modal keeps opening multiple times as the timeout fires repeatedly. Any assistance or suggestions on how to resolve this problem would be ...

Adjusting the dimensions of :before with JavaScript: A Step-by-Step Guide

There's this CSS3 tag named body:before that I'm working with, and I'm looking to adjust the height and width of body:before using JavaScript. Any suggestions on how to achieve this? ...

The functionality of JQuery's ajax post request is not functioning properly as intended

Link to the page: localhost/mysite/create-user This is the block of code: <form class="form-horizontal" name = "signUp1F" id = "signUp1F"> <input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = ...

Retrieving data for a route resolver involves sending HTTP requests, where the outcome of the second request is contingent upon the response from the first request

In my routing module, I have a resolver implemented like this: { path: 'path1', component: FirstComponent, resolve: { allOrders: DataResolver } } Within the resolve function of DataResolver, the following logic exists: re ...