How To Determine When An Html5 Element Has Been Viewed?
Solution 1:
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);
functioninView() {
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>
Solution 2:
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):
Solution 3:
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.
Solution 4:
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.
Post a Comment for "How To Determine When An Html5 Element Has Been Viewed?"