I want to continuously execute specific Javascript function only when part of HTML document is visible. That implies stopping the execution of function when that part is not visible again.
Getting out of visible scope means that element is out by:
- scrolling out (either vertical or horizontal)
- changing to some other browser tab
- shutting down tab/window/entire browser.
Example code: I have HTML with a style to make sure that I have div main (entire page) and div target that is on my screen (1920 X 1080) below visible scope:
<html>
<head>
<title>Title</title>
<style type="text/css">
#main{
height: 2300px;
}
.target{
border: 1px solid black;
position: relative;
top:1000px;
width:150px;
height: 150px;
}
</style>
<script scr="js/jquery.js"></script>
</head>
<body>
<div id="main">
<div class="target"></div>
</div>
</body>
</html>
What is the JS/Jquery code that will order:
when div.target is currently visible trigger execution of my_function()
when div.target is scrolled out or tab is changed, stop execution of my_function() ?