I currently am working on a single page app and am using jQuery waypoints to around the page. When manually scrolling though, I'd like to use pushState to change the url in the address bar when the div comes in to view. How could I go about doing that? Thanks!
Asked
Active
Viewed 532 times
0
-
What do you mean *"using jQuery waypoints to around the page"?*..?! – T J Sep 27 '14 at 09:26
2 Answers
0
You want to change the url depending on the page scroll? The only part of the url which can be changed is the 'hash', for example http://example.com/index.html#div5
To do this, you need to detect page scroll and then to set this hash string.
$(window).scroll(function () {
//this shows how many pixels we have scrolled
var scroll = window.scrollTop;
//now we loop through the divs
$('.div').each(function(){
var top = $(this).offset().top,
width = $(this).width();
//if we are seing the current div, set the url and...
if(scroll >= top && scroll <= top + width) {
location.hash = $(this).attr('id');
return false;// ... and stop looping through the divs
}
});
});
I suppose your html is like this:
<div class="div" id="this is the url for the first div">
</div>
<div class="div" id="this is the url for the second div">
</div>
<div class="div" id="this is the url for the third div">
</div>

Al.G.
- 4,327
- 6
- 31
- 56
-1
Just listen for document scrolling
$(window).on('scroll'/*, your handler */);
and calculate div's position against view port, good solution is here:
https://stackoverflow.com/a/125106/990942
Basically, you need to
var myBlocks = $('.div-you-track') // gather all your blocks
function resolve() {
var resolved;
myBlocks.each(function(block) {
if (inViewort(block)) { // for inViewport look link above
resolved = block;
}
});
if (resolved) {
// push your state
// you can use data-* attributes to determine link, for example
// resolved.data('url')
}
}
$(window).on('scroll', resolve); // listen to body
Here is HTML sample
<div class="div-you-track"></div>
<div class="div-you-track"></div>
<div class="div-you-track"></div>
...

Community
- 1
- 1

Lesha Ogonkov
- 1,218
- 8
- 20
-
1What you mean? You should listen to scroll and push required state when you see that div into viewport. It's all in my post. It's not clear what you want. Some code? I didn't know what you already done. – Lesha Ogonkov Sep 27 '14 at 09:28
-
1in most of the cases, anyone can say do this, then this, then this.. how to do it in a specific programming language is actually the issue... *"Just listen for document scrolling"* - how? please provide some sample code... "*and calculate div's position against view port*" - how? please provide some sample code... – T J Sep 27 '14 at 09:34
-
OK, i've added code for listening document scroll. Calculating view position is on the link i've already provided. – Lesha Ogonkov Sep 27 '14 at 09:45