jQuery check if element is visible on screen

Check if element is visible in viewport:

<script>
$.fn.is_on_screen = 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();
 
    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
 
if( $('.target').length > 0 ) { // if target element exists in DOM
	if( $('.target').is_on_screen() ) { // if target element is visible on screen after DOM loaded
        $('.log').html('<div class="alert alert-success">target element is visible on screen</div>'); // log info		
	} else {
        $('.log').html('<div class="alert">target element is not visible on screen</div>'); // log info
	}
}
$(window).scroll(function(){ // bind window scroll event
	if( $('.target').length > 0 ) { // if target element exists in DOM
		if( $('.target').is_on_screen() ) { // if target element is visible on screen after DOM loaded
			$('.log').html('<div class="alert alert-success">target element is visible on screen</div>'); // log info
		} else {
			$('.log').html('<div class="alert">target element is not visible on screen</div>'); // log info
		}
	}
});
</script>
<div class="log">log</div>
 
scroll to target element<br> scroll to target element<br> scroll to target element<br> scroll to target element<br>
scroll to target element<br> scroll to target element<br> scroll to target element<br> scroll to target element<br>
 
<div class="target label label-info">target element</div>

10 comments on “jQuery check if element is visible on screen

  1. Pingback: Fixed Check if element is visible after scrolling #dev #it #asnwer | Good Answer

  2. Pingback: Расширяем страницы а-ля ВКонтакте (WordPress) | Персональный блог Евгения Жукова

  3. Pingback: Solution: Check if element is visible after scrolling #dev #it #computers | Technical information for you

  4. Pingback: How to: Check if element is visible after scrolling | SevenNet

  5. I was trying to target all the image tag that were inside a view port and loading only them .

    What I was doing is something like this

    Hence I wanted to check
    $('li).each(){
    if(img is vissible in viewport)
    {
    var source = this.attr(data-src);
    this.attr('src', 'source');
    }

    }

    Can you give me some suggestion if this is the right way to load the images in my mobile app ?

    And if yes then how can i use you function to do this
    Thanks & Regards

  6. hi, how do you handle the case when you have two or more specified div tags that want to be detected?

Leave a Reply

Your email address will not be published. Required fields are marked *