Determine When HTML Element Comes Into Viewport While Scrolling

Determine when an HTML element comes into view while scrolling.

The line: document.body.onscroll = ""; is executed if the element comes into the viewport and turns off the onscroll function.  Therefore the code only executes once, as the user scrolls the element into view.

document.body.onscroll = function() {
	if (document.getElementById("viewElement").getBoundingClientRect().bottom <= window.innerHeight) {
		document.body.onscroll = "";
		alert("The tag just came into view");


Place the script above at the bottom of the page in a script tag. 

Place an HTML tag with ID matching the ID in the function.  In the script above the ID is "viewElement" but this can be any ID as long as the ID in the HTML tag and Javascript match.

For example:
<div id="viewElement">When this tag comes into view an alert dialog will pop up.</div>

Produces this result: Scroll down until you see the tag ...

Scroll down ...

Keep scrolling ...

Keep on keeping on with the scrolling ...

You're doing great, just keep scrolling ...







When this tag comes into view an alert dialog will pop up.

(Note. The alert will only pop once.)


Copyright © Website Development | Disclaimer | Privacy Policy | Terms of Use