Check block visibility
We have code like:
<body>
<div class="blocks">some text here</div>
<div class="end"></div>
</body>
Text can fit in current browser visible part or not.
How to detect, does the block is in visible part of browser window?
I mean, if resoution is 1024x768 and .block
height bigger than 768, then .end
is invisible.
- we should detect this on window.ready and also on browser 开发者_如何学Gowindow change.
- if block is visible, then run some function.
Any help is appreciated.
Something like this:
$.fn.viewport = (function() {
var vp = function(el, opts){
this.el = $(el);
this.opts = opts;
this.bind(); // bind resize and scroll
this.change(); // init change
};
vp.prototype = {
bind: function(){
$(window).bind('resize scroll',
$.proxy(this.change, this));
},
change: function(e){
var p = this.el.position(),
o = this.el.offset(),
d = { w: this.el.width() +o.left, h: this.el.height()+o.top },
win = $(window),
winD = {w:win.width() + win.scrollLeft(), h:win.height()+win.scrollTop()};
if(d.w <= winD.w && d.h <= winD.h){
console.log('inview');
} else {
console.log('out of view');
this.opts.outOfView.call(this);
}
}
};
return function(opts){
return $(this).each(function(){
$(this).data('vp', new vp(this, opts));
});
};
})();
And use like this:
$('#el').viewport({
outOfView: function(){
alert('out of view');
}
});
First grab the window dimensions.
var windowSize = {width: $(window).width(), height: $(window).height() + $(window).scrollTop()};
Next grab the div position in relation to the document:
var position = $('.block').offset()
Then make your if's:
if(position.top > windowSize.height){ /* here we go */ }
You might want to also grab div dimensions in case there is a possibility it will be out of bounds on the top or left side.
You could make it into a function that returns a boolean value and then call it on the window.resize and document.ready events.
EDIT: Added scrollTop to account for scrolling.
As a quick answer you'll have to do some computation on load (psuedocode assumes jQuery).
- Find the window height $(window).outerHeight(true)
- Find the offset of the ".end" element $(".end").offset()
- Find the scroll distance of the window $(window).scrollTop()
Calculate! It should roughly be:
if ((step1 + step3) > step2) { //do stuff here }
Note that that does not check if you are scrolled past the ".end" element. I didn't verify this one, so hopefully I'm not missing something big.
- Get the offsetTop and offsetLeft attributes of the element
- Get the width of the element in question
- Get the width of screen
- Do the relevant maths and see if the element is in the viewport or now.
in jQuery you can do something like
$("#element").attr("offsetTop")
EDIT: Simple and Effective: http://jsfiddle.net/hPjbh/
精彩评论