Unexpected behavior encountered in Rails app with unobtrusive JavaScript

I'm facing an issue with my link_to setup. Here's what I have:

<%= link_to "Load More", comments_feed_path(@post.id), :id => 'my-link', :remote => true %>

In my application.js file, I have the following code:

$( document ).ready(function() {

    $('#my-link').bind('click', function() {
        alert('Hooray!');

       //event.preventDefault(); // Prevent link from following its href
      });
});

However, nothing happens when I click on the link. It only works if I use inline JavaScript, like this:

<%= link_to "Load More", comments_feed_path(@story.id), :id => 'my-link', :onclick => "test()", :remote => true%>

In my application.js, I define the test function as follows:

function test(){
    alert('test');
}

Can anyone suggest what might be missing in my initial setup?

Answer №1

Encountering the typical turbolinks problem here. Turbolinks, a gem automatically added to rails projects, prevents certain parts of the webpage from reloading with each request. The main part it avoids reloading is the header section, which includes all the JavaScript declarations. Thus, your $(document).ready function will only run once on the initial page load.

To resolve this issue, simply switch $(document).ready to:

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

For more information, check out the documentation at: https://github.com/turbolinks/turbolinks

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

Tips for using the $each() function within a jquery append to retrieve object-based conditions for parameters

I encountered an issue while trying to include a condition in my endpoint, and I have recently started using jQuery for this purpose. Here is the code snippet from my Laravel view: <tbody id="tbody"> @foreach ($modul as $m) <tr> ...

Tips for showcasing a designated set of numbers in Vue Js while iterating?

Is there a way to specifically target numbers during a loop? For example, I only want to retrieve numbers 5 and above or within a certain range that I specify. <select name="" id="input" class="form-control" v-model="selectcompetitionyear"> < ...

Optimize your mobile experience by creating a notification menu that is scrollable and fixed in position

Recently, I purchased Moltran, but encountered a major issue: The notification menu disappears on mobile devices, which is not ideal for me. After some research, I discovered that removing the hidden-xs class from the li notification element can solve this ...

Notification window when the page is being loaded

My goal is to have a module or alert box display when my website is opened, and then disappear after 5 minutes. To see an example of what I'm looking for, take a look at this website: On that website, there is a facebook.com box that automatically d ...

Converting an array of numbers into an object using JSON

When I use jQuery to encode an array, this is the JSON I receive: {"1":{"name":"11233","po":"121212","po_item_number":"000001","po_item_material_code":"material","po_item_description":"assemble","sales_order":"11000000","sales_order_item":"10","tracable": ...

Providing Node-server with Vue.js Server Side Rendering

I've been attempting to deploy the Hackernews 2.0 demo on my Digital Ocean droplet but have hit a roadblock. npm run start starts the server on port :8080. npm run build is used for production builds. The specific build tasks can be found below: ...

Having trouble submitting data to a NextJS API route?

I am currently working on a simple form within a NextJS page, where the data is being stored in state: const [bookingInfo, setBookingInfo] = useState({ name: "", email: "", phone: "", }); const handleChange = (e ...

Query the MySQL database using ActiveRecord to retrieve a categorized collection of records

I have a 'Statement' model associated with a 'Member'. In an array of members, I need to construct a query to retrieve the most recent statement for each member in a single query. I initially attempted using 'group' and &apos ...

Struggles with loading order in Knockout.JS

I've encountered an issue with loading my scripts properly for a page utilizing a knockout.js form. Upon page load, my viewmodel js file isn't immediately loaded, resulting in errors that cause the validation messages to flash and hidden divs to ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...

Increase the gap between the legend and the chart when utilizing charts.js

I'm currently working on a project using charts.js and running into a slight issue. The legend for my bar chart is overlapping with the values displayed. I've been attempting to troubleshoot this problem without much success so far, so I would g ...

Using JSON in Node.js

After recently diving into Node, I've been working on parsing JSON data from an API. While I have managed to access most of the JSON content, there are certain elements that seem to elude me. var request = require("request"); var url = 'https: ...

Error message in Angular js: Unable to load file using XMLHttpRequest

Encountering an error while debugging an Angular JS application in the WebStorm IDE. The error message states: "XMLHttpRequest cannot load file:///C:/Users/../list.html. Cross origin requests are only supported for HTTP." Provided Javascript code : var a ...

Troubleshooting Guide: Issues with Bootstrap 3 Modal Window Implementation

This question is so simple that it's embarrassing. I attempted to copy the code from http://getbootstrap.com/javascript/#modals directly into a basic page setup, but it's not functioning. It seems like I'm making a very silly mistake. Here i ...

Jenkins integration with a MEAN stack application: A step-by-step guide

I'm working on a Mean stack application and looking to integrate Jenkins CI into my workflow. I am uncertain about the steps needed to accomplish this task. Currently, I use bower for installing frontend packages and npm for other functionalities. ...

What is the best way to eliminate the appended content within the tbody?

The code snippet below is functioning correctly. I am trying to retrieve the ID or Class of the appended data from the checkbox. However, when I use the following code $('.chk').click(function(){ console.log(cc);}), it does not work as expected. ...

Vue: Changing the value in the select dropdown causes input fields to reset their content

After setting up a form with input values, I noticed that when using a select element with a v-model to change the dropdown value, the input fields from the previous selections are cleared. This has been a persistent issue for me and is now starting to imp ...

How can I prevent a repetitive div from appearing in a JQuery show/hide function?

Whenever I trigger my AJAX function, the loading image keeps repeating every time I click on the next page. I want to prevent this repetitive loading image and only display it once when I go to the next page. To address this issue, I created a <div cla ...

When implementing protractor spyOn() with jQuery's ajax() function, an error is triggered stating 'ajax() method is non-existent'

I am currently testing the functionality of using AJAX to submit a form. Below is the Protractor code for the test: describe('login.php', function() { it("should use ajax on submit", function() { browser.get('/login.php'); spyOn($ ...