amp108
amp108

Reputation: 434

Rails 4 jquery function works once, not on reload

Working in Rails 4.2.5, I have the following code in my application.js file:

$(document).ready(function() {
$("#property_selection #properties").click(function() {
    var url = window.location.href
            .replace(/\/?$|(\?|&)current_prop_id=[^?&]+/g, "")
        + "?current_prop_id="
            + $("#properties option:selected").val();
    window.location.href = url;
    })
});

I.e., when I select a property_id, I want to go to the same URL, plus "?current\_prop\_id=", plus the ID.

This works the first time I login. When I visit a path like http://localhost:3000/foo, however, it doesn't. Hitting refresh on the page makes it work again.

Then I changed the $(document).ready line to $(document).on('page:load', ..., (based on what I'd read here), but that only reversed the problem. Now it works the first time, but not the second.

Dropping this code into a static file works just fine.

I now have both defined in application.js, which feels wrong on many levels, but I don't know what to do to get the function to work in both cases otherwise. Anyone have any suggestions? Thanks.

Upvotes: 1

Views: 103

Answers (2)

mrvncaragay
mrvncaragay

Reputation: 1260

I had the same issue when i had before with jquery function to load my images. The reason for this how Turbolinks load pages. Some nodes you bind with your page doesnt exist anymore.

I used gem 'jquery-turbolinks' to resolve my problems. check the gem here try it out if it solves your problem. good luck mate.

Upvotes: 2

Ronan Lopes
Ronan Lopes

Reputation: 3398

I usually do something like (coffee script syntax):

$ ->
    do_on_load()
    $(window).bind('page:change', do_on_load)

or javascript:

$(document).ready(function() {
  do_on_load();
  $(window).bind('page:change', do_on_load);
}

where do_on_load() is the function with the instructions that should be executed. Anyway, this is caused by turbolinks + jquery and it's really annoying. Change the order they're being loaded in your application.js also influence on that behavior. I suggest reconsider using turbolinks... it will give you some headaches. Good luck!

Upvotes: 1

Related Questions