Miloš Đakonović
Miloš Đakonović

Reputation: 3871

How to continuously execute Javascript function when part of HTML is currently visible?

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:

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() ?

Upvotes: 1

Views: 1235

Answers (1)

slebetman
slebetman

Reputation: 113906

OK, I know this is a bad method of answering. The standard is to close this question and point to the duplicate question, but this question has two parts and two separate answers. So, I'm putting the links to the answers here:

Part 1: Detect when an HTML element is not in scroll view

Check if element is visible after scrolling

Part 2: Detect when tab is not in view

How to tell if browser/tab is active

Both of the above seem to have working answers. Just implement both to get what you want.

Upvotes: 1

Related Questions