How to determine when an HTML5 element has been viewed?

早过忘川 提交于 2019-11-28 11:48:46

As already mentioned, there is no "event" but someone already wrote a method to "detect if a DOM Element is Truly Visible" (the title). It doesn't require JQuery. You might want to check for the value on several events like the document load, scroll or window resize.

In plain JavaScript you can use the event "scroll" along with getBoundingClientRect().bottom <= window.innerHeight to determine if an html element has come into view.

document.addEventListener("scroll", inView);

function inView() {
    if (document.getElementById("viewElement").getBoundingClientRect().bottom <= window.innerHeight) {
        console.log("in view");
        // uncomment below if you only want it to notify once
        // document.removeEventListener("scroll", inView);
    }
}

The console prints "in view" when the element comes into view.

<div id="viewElement">Hello there!</div>
jfriend00

There are no built-in events that tell you when an entire DOM element has become viewable/visible on the page due to scrolling or window resizing.

The only way to do this is to keep track of resize and scroll events (which can each cause more or less of your page to be visible) and then use the scroll position and window height and DOM element positions to calculate if your entire DOM element is visible.

Some relevant pieces of code you can either consider using or look into how they work (these tend to be jQuery-based because they are harder to share if not based on a common DOM library):

Lazy Load Plugin for jQuery

Element "in view" Event jQuery Plugin

Check if Element is Visible After Scrolling - plain JS

I had to do something similar to this when I built http://f1circle.com.
When the bottom banner becomes visible, I have to show a spotlight to the user asking him to login.

The code that achieves it using angularjs can be viewed at https://github.com/rajegannathan/angularUtilities/blob/master/directives/eagerload.js

Though it is an angularjs directive, the main logic is in plain javascript. Basically I check if the the last feed's bottom edge is visible and then trigger the spotlight.

I can explain more if required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!