jQuery - Change class when entering div area (but not with mouse)
I came across great sites which had a cool feature, which I'll try to explain here.
I tried to study the .js sources, but as I'm a newbie I couldn't decipher the minified versions. :(
Let's say I have the following markup:
<ul id="posts">
<li id="photo"> Lorem ipsum </li>
<ii id="quote"> Lorem ipsum dolor </li>
</ul>
<div id="logo">My Logo&开发者_如何转开发lt;/div>
What I want to do is: when user enters the li#photo area, jQuery would change the #navigator background color to, say, blue. If the user keeps scrolling down he would enter the li#quote, and when he enters the area, jQuery would change #navigator bg color to red.
When I say "enter the area", I mean by scrolling and not by mouse hovering.
There's a Tumblr theme that kind of does what I'm trying to explain:
http://www.figueric.com/ (scroll down and see the navigator on the right)
The only thing I can come up is to use the .addclass feature, but I don't know where to start, specially when it comes to recognizing that the user is viewing the li#photo area, for example.
Can you guys give me some light here?
jQuery has a scroll()
event you can use when scrolling. You just need to get the position of the child elements and see if they are in the current view.
Here's an example that you can test: http://jsfiddle.net/BKnzr/1/
CSS
html,body {
padding:0;
margin:0;
clip: auto;
overflow: hidden;
}
#navigator {
text-align: center;
background: green;
color: white;
position: absolute;
top: 150px;
right: 50px;
overflow: hidden;
width: 60px;
height: 250px;
}
#posts {
position:absolute;
top: 0;
bottom: 0;
width: 100%;
overflow: auto;
}
#photo,#quote {
margin-top: 800px;
height: 300px;
}
HTML
<div id="navigator">Scroll down to change background</div>
<ul id="posts">
<li id="photo">photo section</li>
<li id="quote">quote section</li>
</ul>
jQuery
// cache the elements
var $nav = $('#navigator');
var $photo = $('#photo');
var $quote = $('#quote');
var $posts = $('#posts');
// get the view area of #posts
var top = $posts.offset().top;
var bottom = top + $posts.height();
// run code when #posts is scrolled
$posts.scroll(function() {
if($quote.offset().top < bottom) {
$nav.css('backgroundColor', 'red');
} else if ($photo.offset().top < bottom) {
$nav.css('backgroundColor', 'blue');
} else {
$nav.css('backgroundColor', 'green');
}
});
I created a demo on jsbin: http://jsbin.com/ewuti4/edit
On the document's or window's .scroll() event, check the .scrollTop() property, plus the .height(), and see if it greater than whatever element's .offset().top property. Then change your nav's styling or add/remove a class as appropriate.
$(window).scroll(function(){
if ($(window).scrollTop() + $(window).height() >= $('#quote').offset().top)
{
$('#nav').css({
'backgroundColor': 'blue',
'border': '5px solid black',
'top': $(window).scrollTop(),
'left': 0
});
}
精彩评论