1

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the turbolinks tip. I opted to remove it from my config, though, as the gem jquery-turbolinks didn't appear to help. I'm not even sure where the references for them came from, unless a generator automatically created them. Thanks again.
1

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!

1 Comment

Thanks. I did reconsider turbolinks, or rather, considered it for the first time and removed all references to it in my code. I don't remember putting any reference to it in any of my files, so a generator must have done it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.