Call IntersectionObserver callback again after it has observed an element? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Call IntersectionObserver callback again after it has observed an element? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am observing messages and keep track of these observations using message timestamps. There’s an important condition for these observations: the tracking timestamp shouldn’t update if there’s no client activity on the page (cursor not moving, or he’s not typing anything). Quite often client gets a new message, but has no activity. That means that Observer is skipping that element once it’s fully observed. But when user actually provides some activity this element is not re-observed, that means that observer callback is never called again unless the ratio changes. How do I tell IS to recalculate all the observations to trigger my callback?

The problem with manually ‘re-observing’ elements is that the callback is never called if the element is already within intersection bounds.

Some pseudo-code for example:

IS.callback = function(entries, observer){
    for (var entry in entries)
    {
        if (activity && entries.hasOwnProperty(entry))
        {
            if (lastTimestamp < entries[entry].data.timestamp)
                lastTimestamp = entries[entry].data.timestamp;
        }
    }
};

Answer

The solution was pretty simple: remove any observers and observe elements once again. Then call startObserve(); on any activity change. Using jQuery here for simplicity.

function startObserve()
{
    IS.targets =
        $('#messages .message')
        .each(function(index, target){
            IS.observer.unobserve(target);
            IS.observer.observe(target);
        });
}
We are here to answer your question about Call IntersectionObserver callback again after it has observed an element? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji