jQuery trigger function when element is in viewport


jQuery trigger function when element is in viewport : Sometimes we need to call function when element appears in viewport. There are many ways to check the element postion, we are going to explain the easiest way to check the position of an element using jQuery and then call the function. You can also use our online editor to edit and run the demo online.


jQuery trigger function when element is in viewport | Example

You use the following method to check that element is in viewport or not –

jQuery trigger function when element is in viewport?

<!DOCTYPE html>
<html>
<head>
<title>jQuery Demo example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js">
 </script>
<script type="text/javascript">
function isIntoView(elem)
{
    var documentViewTop = $(window).scrollTop();
    var documentViewBottom = documentViewTop + $(window).height();

    var elementTop = $(elem).offset().top;
    var elementBottom = elementTop + $(elem).height();

    return ((elementBottom <= documentViewBottom) && (elementTop >= documentViewTop));
}
  $(window).scroll(function(){
   if (isIntoView($('#myDiv'))){
       alert("Div in view port");
    }
})
</script>
 </head>	
<body>
<div id="myDiv" style="margin-top:500px;width:200px;height:200px;background:yellow;">
<h2>Demo Div</h2>
</div> 
</body>
</html>                                                                                                                                                                                                                                                                                                                                                                                                                                              

Try it »


Advertisements

Add Comment

📖 Read More