Rails jQuery not working in asset pipeline

384
November 26, 2016, at 9:49 PM

When I place this jQuery code in the view file, it works fine:

$('.messages-link').click(function (event) {
  $.getScript(this.href);
  history.pushState(null, "", this.href);
});

But when I put it in useful.js, and require useful.js in application.js, it doesn't work, it isn't called.

application.js

//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require bootstrap
//= require underscore
//= require useful

I know that useful.js is successfully being included in the asset pipeline because there is another function in there that is definitely being called from the same view file.

Why does the jQuery function not work?

Answer 1

Have you forgotten to place your code inside a DOM ready function? Perhaps your DOM has not loaded before you try to attach the listener?

$(function() {
  $('.messages-link').click(function (event) {
    $.getScript(this.href);
    history.pushState(null, "", this.href);
  });
});
Answer 2

The reason for this is that if you put it in your view the element .messages-link exists in the DOM.

If you put it in useful then the file gets bundled in application.js and it is loaded in the <HEAD></HEAD> on your html before the view that has .messages-link is loaded.

A possible solution is to change the binding like this:

$('.messages-link').on('click', function (event) {
  $.getScript(this.href);
  history.pushState(null, "", this.href);
});

Which works with dynamically added elements.

Rent Charter Buses Company
READ ALSO
Navigation menu not switching from hover to toggle based on the screen size

Navigation menu not switching from hover to toggle based on the screen size

How can I make my webpage switch buttons from on hover to on toggle when the width of the screen is less than 769pxThe hover or toggle script is selected based on what size the browser starts on and cannot switch when changing the size

208
Setting Keyboard Focus to YouTube Embed

Setting Keyboard Focus to YouTube Embed

I’m trying to find a way to get the keyboard to focus on the YouTube player in my pageThis could, for example, make it easy to use the space bar to play/pause the video

378
jquery move up/down excluding element

jquery move up/down excluding element

I am trying to move thedraggable div up and down, bypassing the

387
Only keep one div expanded

Only keep one div expanded

I'm using simple-expand Jquery plugin (http://sylvain-hamelgithub

275