user2749195
user2749195

Reputation: 43

JQuery - Detect if element is fully in viewport

I'm trying to use this plugin to execute an animation when if an element is fully visible in the viewport; kind of like a lightbox effect. It somewhat responsive ... but moreso not. Not sure if I'm using the right approach. Any ideas?

$(window).bind("resize mousewheel scroll scrollStop", function() {
if($(".tailor .content").is(":within-viewport")) {
    $(".tailor").animate({opacity:'1.0'}, 900, 'easeInOutQuart');
}
else {
    $(".tailor").animate({opacity:'0.8'}, 900, 'easeInOutQuart');
}
});

Upvotes: 0

Views: 4540

Answers (2)

Jason Ellis
Jason Ellis

Reputation: 576

This is what I use to detect when an element is fully visible then do whatever I want with it:

// Create jQuery Method
jQuery.fn.isFullyVisible = 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 elemtHeight = this.height();// Get the full height of current element
elemtHeight = Math.round(elemtHeight);// Round it to a whole number

var bounds = this.offset();// Coordinates of current element
bounds.top = bounds.top + elemtHeight;
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();

return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

}

//Usage:
$(window).on('scroll', function() {
  if( $('.tailor .content').isFullyVisible() ){
    // do something
  }
});

Upvotes: 4

Art
Art

Reputation: 592

No reason to use a plug-in for that :-) This should work easily;

var el = $('.tailor .content');
var $window = $(window);
var isInFrame = false;

$window.on('scroll', function() {
    if((el.offset().top < ($window.scrollTop + $window.height())) && ((el.offset().top + el.heigt()) > $window.scrollTop))
    {
        if(!isInFrame) 
        {
            isInFrame = true;
            el.animate({opacity:'1.0'}, 900, 'easeInOutQuart');
        }
    }
    else
    {

        if(isInFrame) 
        {
            isInFrame = false;
            el.animate({opacity:'0.8'}, 900, 'easeInOutQuart');
        }
    }
});

You'll need to keep track if your element is already in frame; or else it'll keep resetting the animation every time you scroll.

Upvotes: 0

Related Questions