By Default, if I have anchors in my website, then the URL on the address bar is changed, when I click on a link (ie. www.mysite.com/#anchor)
Is it possible to change the URL in the address bar instantly when I scroll to an anchor? Or have a long document with multiple anchors and the url changes on address bar, when I hit a new anchor?
You can bind to the jQuery scroll event (http://api.jquery.com/scroll/) and on each call of the callback called, check how far on the document the user has scrolled by checking this value: . scrollTop (http://api.jquery.com/scrollTop/) and set the anchor by manipulating te location.
The easiest way to to make the browser to scroll the page to a given anchor is to add *{scroll-behavior: smooth;} in your style. css file and in your HTML navigation use #NameOfTheSection .
Try using this jquery plugin: Scrollorama. It has tons of cool features and you can use window.location.hash
to update your browsers hash.
Alternatively, you can add a "scroll" event to check when an anchor is reached.
Here is a working fiddle to illustrate the event: http://jsfiddle.net/gugahoi/2ZjWP/8/ Example:
$(function () { var currentHash = "#initial_hash" $(document).scroll(function () { $('.anchor_tags').each(function () { var top = window.pageYOffset; var distance = top - $(this).offset().top; var hash = $(this).attr('href'); // 30 is an arbitrary padding choice, // if you want a precise check then use distance===0 if (distance < 30 && distance > -30 && currentHash != hash) { window.location.hash = (hash); currentHash = hash; } }); }); });
you can use HTML 5 pushstate to change the URL in the address bar
window.history.pushstate
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