Monday, 15 August 2011

javascript - Jquery inview element should work on load and on scroll -



javascript - Jquery inview element should work on load and on scroll -

i'm trying create inview function working adding class element , remove when not inview. not sure i'm missing... help please?

http://jsfiddle.net/zefjh/

$.fn.isonscreen = function () { var win = $(window); var viewport = { top: win.scrolltop(), left: win.scrollleft() }; viewport.right = viewport.left + win.width(); viewport.bottom = viewport.top + win.height(); var bounds = this.offset(); bounds.right = bounds.left + this.outerwidth(); bounds.bottom = bounds.top + this.outerheight(); homecoming (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom)); }; $('.box').click(function () { alert($('.box').isonscreen()); }); if ($('.box').isonscreen() == true) { $('.box').addclass('inview'); } $(window).scroll(function () { if ($('.box').isonscreen() == true) { $('.box').addclass('inview'); } else { $('.box').removeclass('inview'); } });

you utilize $.each check every .box, whether it's on screen or not, on scroll.

$.each($(".box"), function(){ if ($(this).isonscreen()) { $(this).addclass('inview'); } else{ $(this).removeclass('inview'); } });

also: click function should check if clicked element on screen using this

$('.box').click(function(){ alert($(this).isonscreen()); });

and finally: can leave == true part in if statements.

full example: http://jsfiddle.net/zefjh/2/

javascript jquery scroll

No comments:

Post a Comment