First question on SO...please forgive me if it's poorly done.
This appears to be a normally discussed problem (a search yields dozens if not hundreds of posts "my JS only works on page refresh" all solved by using jquery-turbolinks
and adding it to application.js
).
I've taken all those steps. However I'm experiencing something that almost no one else references...
The problem:
Here's what we've got:
This adds the localScroll
animation to the div I'm using:
<script type="text/javascript">
$(document).on('page:load', ready)
$(document).ready(function() {
$('#nav').localScroll({duration:800});
});
</script>
The JS libraries I'm using (links broken since I'm a newb and can only include up to two links in a post...):
Both are downloaded and added to app/assets/javascripts
Both are required in application.js
(the last two before //= require_tree .
).
I've installed and added jquery-turbolinks
to my gemfile
, run Bundler, required it in application.js
(before turbolinks
but after jquery
), and stopped/started the rails server.
I didn't add all the details around the div and name/href combinations I'm using since the animation does does work once. I'm assuming my problem is very closely related to what everyone else experiences, but I just can't find a solution.
Any help would be highly appreciated.
Thank you!
UPDATE
application.js
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require_tree .
The localScroll.js and scrollTo.js is in the javascripts folder so require_tree .
does grab them (I inspected the page after it loaded to verify).
This pops the alert every time any page in the application is loaded after the page with the function has been called.
<script type="text/javascript">
$(document).ready(function()
{
alert("JQuery is working!");
$('#nav').localScroll({duration:800});
});
</script>
Then it pops the alert twice on any new page if I load the page with the function again. Then three times if I load it again...I'm assuming that something under the hood is interfering with with this JS which is why the .localScroll
call itself isn't working...
UPDATE 2 Alternate solution
I ended up abandoning trying to work with localScroll and scrollTo and instead just used this agnostic internal link interceptor:
<script type="text/javascript">
$(document).ready(function()
{
$("a[href^=#]").click(function(e) {
e.preventDefault();
var dest = $(this).attr('href');
console.log(dest);
$('html,body').animate(
{ scrollTop: $(dest).offset().top }, 'slow'
);
history.pushState(null, null, dest);
});
});
</script>
You are calling ready on page load, but seem to be missing the ready function.
Try the following snippet:
var ready;
ready = function() {
$('#nav').localScroll({duration:800});
};
$(document).ready(ready);
$(document).on('page:load', ready);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With