When accessing a page from a link, JavaScript sometimes does not immediately execute on the first attempt

I'm encountering a strange issue in my rails application, where a template fails to execute the Javascript code the first time it is loaded via a link on my home page. This problem only occurs when accessed through the link for the first time. I'm puzzled as to why this is happening. Can anyone provide assistance? Here is the relevant code snippet:

Snippet from Home Page:

#app/views/static_pages/home.html.erb
#...
<%= link_to "Notify an absence", new_cancellation_path %>

Javascript File:

//app/assets/javascripts/cancellations_new.js

var validateDateTime = function(){
// logic that returns true or false
  }
  $(document).ready(function(){
    $("#new_cancellation").submit(function(event){
      event.preventDefault();
      if (validateDateTime()) {
        alert("Alert message");
      }
      else { 
        // additional logic 
      }
    }); 
  }); 

Template where the Javascript should run:

#app/views/cancellations/new.erb

<%= provide(:title, "Notify an absence")%>
<div class="row">
<div class="span3 offset4">
  <h3> Notify an absence </h3>

  <%= form_for @cancellation, :id => "new_cancellation" do |f| %>
    <%= render 'shared/error_messages' %>
    <% # some form elements...%>
    <%= f.submit "Send", class: "btn btn-primary"%>        
  <% end %>
</div>
</div>

Attempted solution by adding //= require cancellations_new to

app/assets/javascripts/application.js
did not resolve the issue.

UPDATE

Further investigation revealed that Turbolinks could be causing the unexpected behavior of the Javascript. When Turbolinks are enabled, <a> elements are fetched via Ajax and used to modify the <body> of the HTML document. Due to this unconventional loading method, content within

$(document).ready(){...}

might not execute unless the page is fully reloaded. In order for your Javascript to work properly, consider changing

$(document).ready(){...}

to

$(document).on("page:change", function() {
  // other logic.
});

For more information on this topic, check out these resources: here
more

Answer №1

It seems like the issue might be with turbolinks. Have you attempted turning it off?

You can disable it by removing it from application.js and from layout.html.erb where you have the stylesheet link tag included.

If the problem resolves after deactivating turbolinks, then I suggest looking into how to implement

$(document).on('page:load', .....)

Thank you for your time!

Answer №2

To implement this, simply insert the following code into your application.html.erb

<body data-no-turbolink="true" >
  # your content
</body>

ALTERNATIVELY

If you prefer, you can also include this gem in your gemfile

gem 'jquery-turbolinks'

EITHER METHOD WILL MEET YOUR EXPECTATIONS.

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

AJAX is designed to only modify one specific Django model instance at a time

My Django project displays a list of "issue" objects, each with a boolean field called "fixed". I am looking to implement a feature where users can press a button that will modify the "fixed" status using Ajax. However, currently, the button only changes o ...

The function applyMiddleware in React Redux is not working correctly

After thoroughly reviewing my code, I couldn't find any flaws, yet I received this error message: Uncaught TypeError: (0 , _reactRedux.applyMiddleware) is not a function import { applyMiddleware, createStore } from 'react-redux' impor ...

A guide on eliminating repetitions from an array of objects by utilizing the spread operator

I am working with an object array that has a unique key called "id": var test = [ {id: 1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""}, {id: 2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""}, {id: ...

Embracing this web design framework with Rails

Hey there, I am currently trying to integrate a free CSS/HTML/JavaScript template into my Rails project. You can download the template from here. The template consists of an index page, a single CSS file, and two JavaScript files. To implement this templa ...

A guide on showcasing nested arrays data in an Angular application

info = [ { list: [ { title: 'apple'} ] }, { list: [ { title: 'banana'} ] } ] My goal here is to extract the list items. Here is how they are structured. desired r ...

The request cannot be completed using GET. The connection has not been established, and the offline queue is not activated

Encountering this unexpected error in the live environment, despite implementing a retry strategy of 500ms and wrapping the setAsync and getAsync functions with a setTimeout of 1s. It's puzzling why this issue persists. Error Message: AbortError at ...

What is the reason that the index is consistently the final index when utilizing it to pass to a function while iterating over an array with map()?

Currently, I am utilizing the map function to iterate over an array object fetched from the server. Each object within the array is used to populate a row in a table for displaying data. I need to perform a specific action for each row by invoking a functi ...

Step-by-step guide on eliminating the modal post-validation

Newbie in reactjs looking for help with modal validation issue. Goal: Press submit button inside modal, validate, then close the modal. Want to reuse modal for another row. Problem: I'm having trouble making the function work for a new row after ...

Transmit a continuous flow of integer values from an Android application and capture them on a Node.js express server

I'm looking to develop a simple solution to send a continuous stream of integers from an Android App to a Node.js server. I'm interested in understanding how to establish this stream in Android and how to receive it on my Node.js server using ex ...

What is the best way to integrate a Vue component into a Knockout application?

My webpage is filled with knockout code, but I'm hoping to integrate a Vue.js component for a specific section. I attempted using controlsDescendantBindings on a surrounding tag for the Vue component, and it seems to be partially functional (I tried ...

`"Attempting to access keys of a non-object value" - Dealing with JSON and React Native`

Having trouble with React Native and JSON structure? No worries, we've all been there at some point! Don't sweat it if you're still new to React and JavaScript - we're here to help! Let's take a look at the JSON structure causing ...

Looking to add some movement to your website? Learn how to make an image track your mouse pointer in a specific section of your webpage

I'm just starting out with web design and javascript, so please be patient. My goal is to have an image follow the mouse pointer only when it's within a specific section of my website. I've managed to make the image track the mouse cursor ...

How to Delete Multiple Rows from an Angular 4 Table

I have successfully figured out how to remove a single row from a table using splice method. Now, I am looking to extend this functionality to remove multiple rows at once. html <tr *ngFor="let member of members; let i = index;"> <td> ...

Combining an Angular factory with another factory

I'm facing some difficulties with injecting one factory into another. The error message I'm getting is: `ReferenceError: testDataService is not defined` I thought it would be a simple issue to resolve, but it's turning out to be quite c ...

Having a flash video load on a new page in the same position as it was on the previous page

On my website, I have a subtle flash video playing in the background that loops every 30 seconds. It's not necessary for navigation, just a nice visual touch. However, every time a new page is loaded, the video restarts from the beginning. I'm l ...

Look into the data with vue.js, but there's not much

1. As a newcomer to vue.js, I encountered some surprising issues while experimenting with examples. The first one arose when I assigned an id to the body tag and included the following JavaScript code: <html> <head> <meta charset="utf-8 ...

Ng-Grid error: Trying to access property 'on' of a null value

Currently, I am in the process of creating an angular.js directive that involves a JQuery dialog box containing a grid component. Directive Template: <div class="datasetsGrid" ng-grid="gridOptions"></div> The Issue Whenever I click on the " ...

Encountering a TypeError with react-rte in Next.js: r.getEditorState is not a valid function

In my Next.js project, I am using a React RTE component. It is displaying correctly, but when I navigate to another component and then return using the browser's back button, I encounter the following error: Unhandled Runtime Error TypeError: r.getEd ...

Angular: Card disabled post-click

I am displaying three cards <div *ngFor="let catalog of catalogs;let i=index" (click)="goToProducts(catalog)"> <div> <div class="name-position text {{catalog.classe}}" style="font-size: 21px;"> ...

How to implement a cyclic item generation feature in React.js

My function is meant to draw multiple items in a cycle, but it is only drawing the first item when I attempt to draw 5. This is my function: export default function CinemaHole() { const items = []; for(let i = 0; i < 5; i++) { item ...