1

I wanted to change the url to that of the section id that is currently scrolled to. However my below code just breaks the scroll (it doesn't scroll at all).

$(document).scroll(function() {
  $('section').each(function(){
    if ($(this).offset().top) {
      window.location.hash = $(this).attr('id');
    }
  });
});

<section id="a"></section>
<br><br><br><br><br><br><br>
<section id="b"></section>
<br><br><br><br><br><br><br>
<section id="c"></section>
<br><br><br><br><br><br><br>
<section id="d"></section>

Any help would be much appreciated.

Many thanks.

2
  • $(this).attr('id') it will return you the id like a, b, c, d but when you assign it to hash it suppose to start with #, so just concate it like '#' + $(this).attr('id') and then assign the value. Commented Feb 12, 2015 at 21:58
  • @PashaB, location.hash automatically adds the #. Commented Feb 12, 2015 at 22:05

1 Answer 1

2

This line returns true for all sections except the first one:

if ($(this).offset().top)

Instead, you can compare each section's offset against the window's scroll position:

if($(this).offset().top < $(window).scrollTop())

This line reloads the page, always scrolled to the last section (based on your current if):

window.location.hash = $(this).attr('id');

That's why it appears that scrolling is broken.

If you want to change the URL without reloading the page, use history.pushState().

Complete code:

$(document).scroll(function() {
  $('section').each(function() {
    if($(this).offset().top < $(window).scrollTop()) {
      history.pushState({}, '', '#'+$(this).attr('id'));
    }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

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.