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

What is the most efficient way to handle dependencies and instantiate objects just once in JavaScript?

I am interested in discovering reliable and tested design patterns in Javascript that ensure the loading of dependencies only once, as well as instantiating an object only once within the DOM. Specifically, I have the following scenario: // Block A in th ...

Using Vue.js to share events and data across various components

I am currently working on an application that features a Google map with a places autocomplete controller, similar to the example provided by Google at this link. Whenever an address is searched or selected, or when the map bounds are changed, I trigger a ...

What is the process of importing the csv-writer module?

Can we use the import statement instead of const createCSVWriter = require('csv-writer').createObjectCsvWriter; Is there a way to achieve this using import ...

Checking and contrasting dates within Javascript

Looking to compare two dates with different formats: a) Date1 - 01 Feb 2019 b) Date2 - 2/3/2017 It's important to account for invalid dates and ensure that Date1 is greater than Date2. function CompareAndValidateDates() { var Date1 ="01 Feb 20 ...

Seeking particular section of online content in an asynchronous manner

Is there a method for asynchronously requesting a specific portion of a web resource (like the initial 100 bytes) using JavaScript? I believed this could be accomplished through XmlHttpRequest by adjusting its Range header. However, if the server utilizes ...

Wait until a svelte store value is set to true before fetching data (TypeScript)

I have implemented a pop-up prompt that requests the user's year group. Since I have databases for each year group, I need to trigger a function once the value of userInfo changes to true. My JavaScript skills are limited, and my experience has been ...

The jQuery function may encounter issues when trying to target elements within an appended HTML form

I am encountering a couple of issues. I have 2 separate JQuery functions, one for appending content and the other for displaying the selected file's name. FUNCTION 1 <script> jQuery( document ).ready(function( $ ) { $("input[name ...

Tips for crafting services using $q and $http requests while avoiding redundancy

Is there an elegant way to write AngularJS services without repetitive $q syntax? I currently write services like this: (function() { function ServiceFactory($q, $timeout, $http) { return { getFoo: function() { va ...

Ways to update an angular page using the router without resorting to window.location.reload

I have a specific method for resetting values in a component page. The process involves navigating from the "new-edition" page to the "my-editions" component and then returning to the original location at "new-edition". I am currently using this approach ...

Obtain data from a single module and incorporate it into a different one

In my Angular 2 application, I am dealing with two component files - home.ts and folder-selector.ts. Within the folder-selector.ts file, there is a variable named pathToNode. I am trying to figure out how to access this value from within the home.ts file ...

Encountering an error while attempting to load the jQuery script: TypeError - $.fn.appear.run is not a

I have included an animation script for CSS in my markup, but I am encountering the following error: TypeError: $.fn.appear.run is not a function Does anyone know why this is happening and how I can resolve it? /* * CSS3 Animate it * Copyright (c) 2 ...

The Ajax Process continues to run even after the user has navigated away from the page

Currently, I have a JavaScript function that refreshes a specific section of a Rails-generated view every 2.5 seconds using a JS request to update a basic progress bar. function refreshPage(){ $.ajax({ type:"GET", dataType:"script" }) } s ...

The application is failing to launch following an upgrade to PostCSS version 8 in a React environment

While working on my app, I discovered that I had 80 vulnerabilities. These vulnerabilities were mainly due to peer version mismatches, such as one package requiring React 16.8.0 while I had 17.0.1. However, there was one vulnerability that caught my attent ...

Creating a Canvas Viewport Tailored for Multiplayer Gaming

Lately, I've been playing around with the HTML5 Canvas while working on an io game. However, I've hit a roadblock when it comes to handling the viewport. Setting up the viewport itself isn't too complicated, but accurately displaying other p ...

Issue with Vue JS: e.preventDefault not functioning correctly when using Axios

I am facing an issue in my Laravel project where I have implemented a method in the Vue instance to validate resource availability upon form submission. The validation is done through an AJAX call using axios, and if any resources are unavailable, I receiv ...

Is it advisable to combine ng-change with ng-blur in AngularJS?

Seeking clarification on the correct usage of AngularJS's ng-change and ng-blur from an expert. Specifically, when updating a form value. In the code snippet below, I have a dropdown where I would like to trigger overrideBusinessDec() when the user ...

Deconstructing JavaScript scripts to incorporate HTML5/CSS3 functionality for outdated browsers such as Internet Explorer

I have been researching various resources and guides related to different scripting libraries, but none of them seem to address all the inquiries I have regarding performance and functionality. With so many scripts available, it can be overwhelming to dete ...

Ruby on Rails JSON API - flawless JSON without any errors

When I am displaying an array of ActiveRecord items, each has been processed through the valid? method so errors are already defined. The rendering of the array is done as follows: render json: array_of_objects I have ActiveModelSerializers.confi ...

Is it possible to execute this animation with a single click for repetitive playback?

CODEPEN const btt = document.querySelector('.btt'); btt.addEventListener('click', function(){ this.classList.toggle('anime'); }); Is there a way to achieve the desired effect with just one click? ...

What is the best way to manipulate the canvas "camera" in HTML?

I am currently developing a 3D game that involves navigating through skyboxes. My goal is to have the camera respond to user input, specifically detecting key presses (using WASD controls) to move the camera accordingly. Do you have any suggestions on how ...