How to do something when user scroll until a div?
I have a div id="content"
.
Is it p开发者_运维问答ossible to do an action if a user see the id="content"
?
I answered a similar questions at horizontal scroll, detecting scroll position relative to anchors
See working example http://jsfiddle.net/Vy33z/4/
You can also use a plugin if you are not too familiar with jQuery. The Appear plugin is great and easy to use. All you need to do is
$('#mydiv').appear(function() {
alert('Your div is in view');
});
See, as inside the browser viewport? Have you looked at this viewport selector plugin?
You can do it easily with this jQuery plugin: jQuery Waypoints
You could use .scrollTop()
perhaps. Something like:
function scrolledTo(el, shownCallback, hiddenCallback) {
var isVisible = false;
var isScrolledTo = function(){
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(el).offset().top;
var elemBottom = elemTop + $(el).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
$(window).scroll(function(){
if(isScrolledTo()){
if(!isVisible){
isVisible = true;
if(shownCallback)(shownCallback());
}
} else {
if(isVisible){
isVisible = false;
if(hiddenCallback)(hiddenCallback());
}
}
});
}
Contains code from Check if element is visible after scrolling
Here's a fiddle.
you can check to see if the top of the div is within the window view. This code would need enhanced in case you went below the div.
$(document).ready(function(){
var divTop = $('#test5').get(0).offsetTop;
$(window).scroll(function(){
var windowHeight = $(window).height();
var top = $(window).scrollTop();
var windowBottom = (top+windowHeight);
if(windowBottom > divTop){
console.log('div in view');
}
});
});
HTML:
<div id="test1" style="display: block; height: 200px;">1</div>
<div id="test2" style="display: block; height: 200px;">2</div>
<div id="test3" style="display: block; height: 200px;">3</div>
<div id="test4" style="display: block; height: 200px;">4</div>
<div id="test5" style="display: block; height: 200px;">5</div>
精彩评论