The Rails application is loading JavaScript three times

I am encountering an issue with my ajax function where it is being triggered multiple times upon click instead of just once.

$(document).on('click', '.newGameItem', function() {
    console.log('start click event');
    var apiUrl = $(this).attr('data-api-string');
    var callType = $(this).attr('data-api-post-call');
    var apiKey = $(this).attr('data-api-key');
    var dataType = $(this).attr('data-api-data-type');
    var returnValue = $(this).attr('data-return-value');
    var currentGameWrapper = $(this).parent().parent().parent();

    console.log('before api call');
    getNewItem(apiUrl, callType, apiKey, dataType, returnValue, currentGameWrapper);
    console.log('after api call');
});

The click event mentioned above is nested within a turbolinks load event:

$(document).on('turbolinks:load', function() {  ...  }

I added a console.log at the beginning of the turbolinks load event and verified that the JavaScript file is executing 3 times. This behavior occurs when I navigate to another page from this one and then return using the back button, but it also happens when I access the page from different parts of the application.

This particular file is compiled through the asset pipeline and we have data-no-turbolink on the body tag, although it doesn't seem to have any effect.

Does anyone have insights into why this is happening or suggestions on how to address it? Unfortunately, completely removing turbolinks from my application is not currently feasible for me.

Thank you

Answer №1

It is important that the click event is placed outside the 'turbolinks:load' event in order to attach it to $(document) instead of the element itself. If the click event is placed inside, it will be created every time a page loads. Your javascript code should be structured like this:

$(document).on('click', '.newGameItem', function() {
  // ...
});

$(document).on('turbolinks:load', function() {
  // ...
});

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

Using JavaScript to search JSON objects based on key value pairs

Consider a scenario where you have an array of objects in users.json: {"key":"userSubscriptions","value": [{"channel":"Netflix","user":"Bobby","region":"NA"}, [{" ...

Dynamically switch between showing more and showing less content on each div

Whenever the specific show more button is clicked, the content should be displayed without causing the entire component to re-render. I have tried using a useState, but each time the button is clicked, the whole component re-renders, resulting in long load ...

Exploring the functionality of a personalized hook using the useSelector method

I have developed a custom hook and I am in the process of testing it independently. However, I am encountering an issue where I need to wrap the hook inside a Provider to proceed further. The error message I am getting is displayed below: Error: could not ...

Issue with Jquery .on() causing toggleClass function to not trigger

Adding a column dynamically to a table on click with JS/Jquery is achieved as demonstrated below $("#btn").click(function(){ $('#week_title').append('<th>Week '+count+'</th>'); count++; $('.tag&ap ...

Issue with Angular: no action taken when re-calling function and utilizing the

In one of my components, I am using route parameters to switch between different "tabs". Whenever I switch tabs, I call a function specific to that tab which is subscribed to the route parameters. Here is an example of one of those functions: getUserFeed( ...

What is the best way to send AJAX post data to a Node.js server?

I am currently facing an issue with passing a unique ID object back to the server side using Ajax after making an API call. I need help figuring out what might be going wrong in my code. This is the client side code snippet where I loop through a JavaScri ...

Utilize jQuery to automatically assign numbers to <h1-h6> headings

Looking to develop a JavaScript function that can automatically number headings (h1- h6) for multiple projects without relying on CSS. Currently achieving this with CSS: body { counter-reset: h1; } h1 { counter-reset: h2; } h2 { counter-reset: h3; } ... T ...

Move to the following <article>

I am currently working on developing a JavaScript function that will automatically scroll to the next article whenever the down arrow key is pressed. The challenge I am facing is that my HTML elements are all dynamic and are simply article tags without any ...

Next.js and Material UI - issues with dynamic styles not functioning

I recently started using Next JS in combination with Material UI, following the example project setup provided in the documentation on Github: https://github.com/mui-org/material-ui/tree/master/examples/nextjs My main objective is to utilize Material UI&a ...

Executing Code Within Promises and Utilizing return Statements

When using promises, do I need to explicitly return the resolve and reject methods? The code runs smoothly for single condition statements, but what happens if there are multiple conditions - will reject and resolve automatically end or do we need to use ...

Tips for Utilizing Environmental Variables within a Vue Application's index.html File

My website has an index file with all the necessary meta tags, stylesheets, and scripts: <!DOCTYPE html> <html lang="en"> <head> <!-- Required Meta --> <meta charset="UTF-8"> <meta http-equi ...

Automatically include the date as a column heading along with name and ID

I recently came across a guide on how to dynamically add dates as column headers in a table. However, I encountered an issue where I couldn't add new columns for 'Name', 'Age', and 'Section' before the dynamically generat ...

Is there a more efficient method to achieve this task using JavaScript or jQuery?

Here is the code snippet I am currently using: $(document).ready(function() { //Document Ready $(".examples .example1").click(function() { $(".examples .example1 div").fadeToggle("slow"); $(".examples .example1").toggleClass('focused') ...

Is using canvas the best option for creating simple image animations with JavaScript?

I am currently working on a basic animation project using JavaScript. This animation involves switching between 13 different images per second to create movement. I have created two simple methods for implementing this animation. The first method involves ...

Utilize CSS to break apart text (text = white space = text) and align text in a floating manner, allowing

Is there a way to use CSS to create a white space in the middle of text? Currently, I am manually breaking the text, which is not ideal. I am aware that there is a function that allows the text to end and start in another div, but unfortunately, it is not ...

Mastering AJAX requests in Zend Framework

I'm facing a challenge in integrating an AJAX search function with the Zend Framework. My Controller and Action look like this: class IndexController extends Zend_Controller_Action { public function indexSearchAction() { $this-> ...

React state variable resetting to its initial value unexpectedly

I have encountered a puzzling issue with the React useState hook. After setting the state of a value, it gets reset to null unexpectedly. The main problem lies in the click event that should update the startDate value to the current date and time. This cli ...

Efficiently organizing items within a list on Ionic

Currently, I have an ion-list structured as follows: <ion-list *ngFor = "let chat of Chats"> <ion-item (click) = "openChat(chat.id)"> <ion-label> <h2> {{chat.username}} </h2> ...

Encountered an error while trying to install Drivelist: Module 'C:Program Files odejs ode_modules pm ode_modules ode-gypin' not found

My electron project relies on the drivelist dependency. However, when I attempt to run "npm install," I encounter an error indicating that the node-gyp\bin folder is missing. Surprisingly, I do have the node-gyp\bin in my node modules and even in ...

Identify any fresh elements incorporated into the DOM following an AJAX call

I'm attempting to showcase a newly added div element within the DOM using AJAX. Through AJAX/PHP, I dynamically inserted some new buttons: <button type="button" id="viewPP_'.$index.'" onclick="viewPP('.index ...