'Is there a way to know if the user is on a particular heading, paragraph or a div etc

I was trying to find a way to start an animation only if the user is on it, at first I tried getting screen size, and its works, but its not an optimal solution. Once I was googling I found something where we could get ID (by the ID tag) while scrolling, if somehow I could get the ID while scrolling down, I could use a simple JavaScript function to play the animation. is there any way?



Solution 1:[1]

Okay I found that by my own. What I was trying to do? I wanted to start an animation (skills bar) only when the user is seeing it/on it/have passed previous information. I did this by using section, JavaScript and then trigger the animation when user is on it.

AN EXAMPLE (Im sorry for messy code, I dont know to align code here)

 <section id="name">
        <div class="hello">
<h1>Hello world</h1>
</div>
    </section>
    
        <section id="aboutMe">
        <div class="hello">
<h1>Hello world</h1>
</div>
    </section>
    
        <section id="skills">
        <div class="hello">
             <h1>these are my skills</h1>
</div>
    </section>

JAVASCRIPT:

     var element = document.querySelector("#skills");
    
    function isInViewPort(element) {
    // Get the bounding client rectangle position in the viewport
    var bounding = element.getBoundingClientRect();

    // Checking part. Here the code checks if it's *fully* visible
    // Edit this part if you just want a partial visibility
    if (
        bounding.top >= 0 &&
        bounding.left >= 0 &&
        bounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
        bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight)
    ) {
        return true;
    } else {
        return false;
    }
}

    var element = document.querySelector("#skills");
    
    if (isInViewPort(element)) {
        alert('true')
    }

hope this will help someone in the future

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1