I have been reading tutorials from several different places like http://css-tricks.com/scrollfollow-sidebar/ or http://jqueryfordesigners.com/fixed-floating-elements/ and have been playing around with them but cant seem to figure out how I would be able to add more then just that one sliding box on the page. Any thoughts?
A:
My assumption (from the first example link) is that instead of just having #sidebar
stay in view, you want to have another element scroll with the window as well (i.e. logged in user's details).
The easiest way would be to add this information to your existing scrolling element:
<ul id="sidebar">
<li id="user-details">Name: John Doe<br/>Email: [email protected]</li>
<!-- remaining links here -->
</ul>
However, if you want to scroll two elements with the window:
<ul id="sidebar">
<!-- sidebar links -->
</ul>
<ul id="user-details">
<!-- user details -->
</ul>
It would just be a matter of animating both of their margin-top's inside the $(window).scroll()
event handler:
Edit
The following code scrolls #sidebar
until it reaches 2000px of scroll at which point it stops and scrolls #user-details
until it reaches 4000px of scroll:
// constants for the scrolling
var offsetSidebar = $("#sidebar").offset();
var offsetUserDetails = $("#user-details").offset();
// on scroll of window
$(window).scroll(function() {
scrollElement($("#sidebar"), offsetSidebar, 2000);
scrollElement($("#user-details"), offsetUserDetails, 4000);
});
// handle the scrolling
function scrollElement(elem, offset, boundary){
var currOffset = elem.offset();
if(currOffset.top < boundary && $(window).scrollTop() < boundary){
if ($(window).scrollTop() > offset.top) {
elem.stop().animate({marginTop: $(window).scrollTop() - offset.top});
} else {
elem.stop().animate({marginTop: 0});
}
}
}
You can see it in action here.
Pat
2010-08-19 14:36:27
I am sorry I guess I did not explain this well enough what I want is to have one box A follow you until it gets to a certain point. Now box a has stopped and box B will start following you until that gets to a certain point. Now box b has stopped and box c will start following you and so on and so on
Jacinto
2010-08-19 22:29:48
That's still easy enough. You just have to setup boundary conditions for all your boxes to test against `$(window).scrollTop()`. So for example, box A will follow until `$(window).scrollTop() > 2000`, box will follow until `$(window).scrollTop() > 4000` etc. I've updated my example so you can see what I mean.
Pat
2010-08-20 00:40:28
Can I make the boundary a class or id?
Jacinto
2010-08-20 21:14:48
not directly if you want to use it to style the elements. An id or class won't be recognized if it starts with a number. You'd have to prefix it with a letter and then trim the letter off in your javascript.
Pat
2010-08-21 01:39:42
can you show me an example? I think I understand but I wanna make sure.
Jacinto
2010-08-21 05:35:50
http://www.w3schools.com/jsref/jsref_substring.asp
Pat
2010-08-21 11:21:44