0

I have a div on my homepage. I have a .js file which i have to run on it only when the user views it on his screen i.e the div is placed down and the .js file should only be run when the user views the div while scrolling down or up the homepage.

How should i do that?

Sumant Bagade
  • 69
  • 1
  • 8

3 Answers3

3

Use a window.addEventListener. And attach an event to the listener, and a function to it.

Example, in your case, its scroll, So, it goes something like this-

window.addEventListener('scroll', function(){

// YOUR CODE

});

Hope it helps! :) Happy coding!

bozzmob
  • 12,364
  • 16
  • 50
  • 73
0

You could use the getBoundingClientRect() function for this purpose. It gives you the current rectangle relative to the viewport.

<script>
    window.addEventListener('scroll', function(e){
        var rect = document.getElementById('iddiv').getBoundingClientRect();
        if(rect.top > 0 && window.innerHeight > rect.bottom) {
           //The div is completely in the screen now
        }
    });

</script>
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • It worked. However i want the .js file to run only once when the div is on screen. And when the user comes to back the div , the .js file should again be run but ONLY ONCE. What is happening is that - when we scroll down a little bit, the .js file triggers 2-3 more times to run. ( i have counter.js file which counts to a specific target and gives output on div and i want it to count only once when the div is on screen(not 2-3 times). hope you get what i m asking – Sumant Bagade Dec 29 '15 at 05:45
0

This might not be best solution but you could also use HTML Events with js code attached to it, for example use onmouseover:

<!DOCTYPE html>
<html>
<body>

<div id="demo" onmouseover="myFunction()">Bring mouse here!!!
</div>

<script>
 function myFunction() {
    return document.getElementById("demo").innerHTML = "Good job!";
}
</script>
</body>
</html>

I know you are using external js file here, you can replace script tag with <script src="myScript.js"></script>. You got the idea. Similarily, you can use onmouseout event to change your display back when user is scrolling to different area. Hope it helps, cheers!

Foxy
  • 416
  • 8
  • 18