Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails 4 javascript not executed

I have a custom js file in app/assets/javascripts. This is the js file:

//app/assets/javascripts/contacts.js
//$(document).ready(function() { //I've already tried with this method

$(window).load(function() {
    alert("foo bar")
});

I require the file contacts.js file in the application.js file.

If I inspect the html page I see the js file loaded correctly, but the message is not shown. If I reload the page (by pressing f5), the message is correctly show.

When the page is loaded the javascript is loaded (I can see it in source html code in the browser) but not executed.

Can you help me?

SOLUTION: Rails 4: how to use $(document).ready() with turbo-links

like image 425
user1066183 Avatar asked Apr 02 '14 12:04

user1066183


People also ask

What is the difference between rails and Ajax?

Because of Unobtrusive JavaScript, the Rails "Ajax helpers" are actually in two parts: the JavaScript half and the Ruby half. rails.js provides the JavaScript half, and the regular Ruby view helpers add appropriate tags to your DOM.

What is UJS in Ruby on rails 6?

Rails 6 shipped with a tool called UJS that allows developers to override the method of <a> tags to perform non-GET requests after a hyperlink click and to add confirmation dialogs before executing an action. This was the default before Rails 7, but it is now recommended to use Turbo instead. Clicking links always results in an HTTP GET request.

How do I install yarn in Ruby on rails?

To install Yarn, follow the installation instructions at the Yarn website. Running this command should print out the Yarn version: If it says something like 1.22.0, Yarn has been installed correctly. When you create a new Rails application, you will need to choose between import maps and a JavaScript bundling solution.

Can I integrate JavaScript into my Rails application?

This guide covers the options for integrating JavaScript functionality into your Rails application, including the options you have for using external JavaScript packages and how to use Turbo with Rails. How to use Rails without the need for a Node.js, Yarn, or a JavaScript bundler.


1 Answers

$(document).ready(function() { } # Not working with turbo-links

From

Turbolinks overrides the normal page loading process, the event that this relies on will not be fired. If you have code that looks like this, you must change your code to do this instead:

$(document).on('ready page:load', function () {
  // you code here
});

Another question

like image 148
Philidor Avatar answered Oct 03 '22 04:10

Philidor