Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change url when manually scrolled to an anchor?

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?

like image 934
r1987 Avatar asked Feb 02 '13 09:02

r1987


People also ask

How do I change my scrolling URL?

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.

How do I scroll an HTML page to an anchor?

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 .


2 Answers

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;             }         });     }); }); 
like image 66
Gustavo Hoirisch Avatar answered Sep 21 '22 16:09

Gustavo Hoirisch


you can use HTML 5 pushstate to change the URL in the address bar

window.history.pushstate


  1. https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history
  2. How can I use window.history.pushState 'safely'
like image 21
user2031802 Avatar answered Sep 19 '22 16:09

user2031802