what we made in this code ? Line by line js code?
How to Check if element is visible in viewport using javascript library in javascript and add scroll event to detect when element is in screen:
Video and new version of this writing is here : https://gokhancelebi.net/how-to-detect-when-element-is-visible-on-screen-with-javascript/
// detect when element gets visible on scroll
window.addEventListener("scroll", detect_visibility);
// detect when screen opens for first time
detect_visibility();
function detect_visibility() {
var element = document.getElementById("element");
var top_of_element = element.offsetTop;
var bottom_of_element = element.offsetTop + element.offsetHeight + element.style.marginTop;
var bottom_of_screen = window.scrollY + window.innerHeight;
var top_of_screen = window.scrollY;
if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
// Element is visible write your codes here
// You can add animation or other codes here
alert("element is visible")
} else {
// the element is not visible, do something else
alert("element is not visible")
}
}
detect_visibility ()
With this function i wrote you above you can detect if element inside secreen viewport. It calculates based on offset and element height. You can use this to implement lazyload or animations.
If you want to check if div is visible on screen use “getElemgetElementsByClassName()” or “getElementById” for div class or id
You can add animaton classes in the // Element is visible section of detect_visibility function
var top_of_element = element.offsetTop;
In this line of code we get offset of element that we want to know if it is visibile.
var bottom_of_element = element.offsetTop + element.offsetHeight + element.style.marginTop;
In this line of code we get bottom offset of element
var bottom_of_screen = window.scrollY + window.innerHeight;
var top_of_screen = window.scrollY;
In the first line we get window screen’s bottom offset
In the second line we get windows screen’s top offset
if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
// Element is visible write your codes here
// You can add animation or other codes here
alert("element is visible")
} else {
// the element is not visible, do something else
alert("element is not visible")
}