Tuesday, August 29, 2023
HomeProgrammingExamine Component Visibility After Scrolling with jQuery or JS

Examine Component Visibility After Scrolling with jQuery or JS


Introduction

On the planet of internet improvement, it is usually obligatory to find out whether or not an HTML ingredient is seen after scrolling. This may be essential for quite a lot of causes, akin to triggering animations, loading content material dynamically, or monitoring person habits.

On this Byte, we’ll discover learn how to verify the visibility of a component after scrolling in each plain JavaScript and jQuery.

Component Visibility within the DOM

Earlier than diving into the code, it is necessary to grasp what we imply by a component’s visibility within the DOM. Once we speak about a component being seen, we imply that it’s throughout the viewport, i.e., the portion of the webpage at present seen within the browser window. A component can exist within the DOM however nonetheless be invisible if it is outdoors the viewport, both above or beneath the realm at present being considered.

Notice: A component will also be invisible if it is hidden utilizing CSS properties like show: none or visibility: hidden. Nevertheless, for the aim of this text, we’re solely involved with visibility by way of the viewport.

Why Examine Component Visibility After Scrolling?

You would possibly surprise why it’s a necessity to verify a component’s visibility after scrolling. There are a number of causes for this. Think about you would possibly wish to load content material dynamically because the person scrolls, a typical approach in infinite scroll implementations. Otherwise you possibly you wish to set off an animation or occasion when a sure ingredient comes into view. You may discover that checking ingredient visibility will also be helpful for monitoring person habits and interplay together with your web site.

Checking Component Visibility in Plain JavaScript

Now let’s get all the way down to the code. This is how one can verify a component’s visibility utilizing plain JavaScript:

operate isElementVisible(el)  rect.left > vWidth 

// Utilization
const myElement = doc.querySelector('#myElement');
console.log(isElementVisible(myElement));  // Outputs: true or false

On this code, we first get the bounding rectangle of the ingredient utilizing the getBoundingClientRect() technique. This offers us an object with the properties high, proper, backside, and left, which characterize the coordinates of the ingredient’s edges relative to the viewport.

We then examine these coordinates with the viewport’s dimensions, which we get utilizing window.innerWidth, window.innerHeight, or their fallbacks. If the ingredient’s coordinates are outdoors the viewport’s dimensions, we all know the ingredient isn’t seen and return false. In any other case, we return true.

This operate can be utilized with any ingredient within the DOM, and it’ll let you know whether or not that ingredient is at present seen within the viewport.

Checking Component Visibility with jQuery

jQuery, as you most likely know, is a quick, small, and highly regarded JavaScript library. It makes issues like HTML doc traversal and manipulation, occasion dealing with, and animation a lot simpler with an easy-to-use API that works throughout most browsers.

To verify if a component is seen after scrolling, jQuery offers a way known as :seen selector. Nevertheless, this technique alone can not detect if the ingredient is definitely within the viewport after scrolling.

To do what we would like, we will create a customized operate.

$.fn.isInViewport = operate() {
    var elementTop = $(this).offset().high;
    var elementBottom = elementTop + $(this).outerHeight();
    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).peak();
    return elementBottom > viewportTop && elementTop < viewportBottom;
};

To make use of this operate, merely name it on any jQuery object like this:

$(window).on('resize scroll', operate() {
    if ($('#myElement').isInViewport()) {
        console.log('#myElement is seen');
    } else {
        console.log('#myElement isn't seen');
    }
});

Scroll Occasion Listener in JavaScript

JavaScript offers the scroll occasion for detecting when a component’s scroll place has modified. The scroll occasion is fired when the doc view or a component has been scrolled.

Right here is how we will arrange a scroll occasion listener on the window object:

window.addEventListener('scroll', operate() {
    console.log('Scrolled!');
});

Notice: The scroll occasion is fired for any scrollable ingredient and the window object. Nevertheless, it’s not fired for parts that would not have a scrollbar.

That is useful since we will then verify if our goal ingredient is within the viewport, however solely after a scroll occasion.

Scroll Occasion Listener in jQuery

In jQuery, we will arrange a scroll occasion listener utilizing the .scroll() technique. It attaches an occasion handler operate to the scroll occasion, or triggers that occasion on a component.

Right here is how we will arrange a scroll occasion listener on the window object utilizing jQuery:

$(window).scroll(operate() {
    console.log('Scrolled!');
});

It will log ‘Scrolled!’ to the console every time the window is scrolled.

Once more, this occasion callback is useful to us in determining if a component is in view because it permits us to solely verify when the person scrolls, versus setting some form of timer to periodically verify.

Conclusion

On this Byte, we discovered learn how to verify if a component is seen after scrolling utilizing each plain JavaScript and jQuery. We additionally explored learn how to arrange scroll occasion listeners in each JavaScript and jQuery. Whereas jQuery offers a extra concise and easy-to-use syntax, it is all the time good to grasp learn how to obtain the identical lead to pure JavaScript.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments