The intersection observer fails to activate upon the initial page load and when navigating back to a

When utilizing useIntersectionObserver from VueUse to trigger a fade-in animation upon an element entering the viewport, I encountered a specific issue. Upon navigating to another page or clicking on an item in the carousel and then returning to the previous route with the saved position, the intersection observer fails to trigger automatically. This results in elements remaining hidden unless the page is manually scrolled up and down or refreshed. Additionally, there are instances where if I navigate away after scrolling to the carousel and returning, the observer may not trigger as expected. So the challenge extends beyond just returning to a route but also affects situations involving scrolling and navigation.

To handle the visibility of elements before the observer activation, I apply the invisible class which includes properties like visibility: hidden and opacity: 0. The root cause appears to be the intersection observer's inability to detect elements when the visibility: hidden property is active. Consequently, this prevents the initiation of the fade-in animation upon returning to the page.

To see a demonstration, you can visit: . In the demo, I navigate to the /details route and then return followed by a page reload.

Regarding the Observer.vue code snippet:

<template>
    <div ref="observerRef">
        <slot :isVisible="isVisible" />
    </div>
</template>

<script setup>
import { useIntersectionObserver } from '@vueuse/core';

const props = defineProps({
    rootMargin: {
        type: String,
        default: '0px',
    },
});

const observerRef = ref(null);
const isVisible = ref(false);

const { stop } = useIntersectionObserver(
    observerRef,
    ([{ isIntersecting }]) => {
        if (isIntersecting) {
            isVisible.value = isIntersecting;
            stop();
        }
    },
    {
        rootMargin: props.rootMargin,
    }
);
</script>

The component where the intersection observer is utilized:

<ItemObserver v-slot="{ isVisible }">
    <div :class="isVisible ? 'fade-in' : 'invisible'">
        <CarouselContent>
            <CarouselItem v-for="item in 8" :key="item">
                <NuxtLink
                    to="/">
                    Link
                </NuxtLink>
            </CarouselItem>
        </CarouselContent>
    </div>
</ItemObserver>

CSS styles used:

@keyframes fadeIn {
    from {
        visibility: hidden;
        opacity: 0;
    }
    to {
        visibility: visible;
        opacity: 1;
    }
}

.fade-in {
    visibility: hidden;
    opacity: 0;
    animation: fadeIn 0.3s cubic-bezier(0.5, 0, 0.5, 1) forwards;
}
.invisible {
    visibility: hidden;
    opacity: 0;
}

If anyone has suggestions for resolving this issue, please share your thoughts!

Answer №1

The issue I encountered stemmed from JavaScript running before the DOM was fully loaded. To address this, I restructured my code so that the intersection observer logic is now called within the onMounted function with a slight delay to ensure proper execution:

onMounted(() => {
    setTimeout(() => {
        if (!observerRef.value) return;

        const { stop } = useIntersectionObserver(
            observerRef,
            ([{ isIntersecting }]) => {
                if (isIntersecting) {
                    isVisible.value = isIntersecting;
                    stop();
                }
            },
            {
                rootMargin: props.rootMargin,
            }
        );
    }, 0);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

it results in an error when attempting to deconstruct an object

Using a style object in a component <Temp styles={{fontWeight: 'bold', fontSize: '1.6'}} ...otherprops /> Encountering an error while deconstructing the style object Cannot read property 'fontSize' of undefined. The d ...

The occurrence of multiple URLs being passed to driver.get can lead to inaccurate test

As I embark on creating a system with an expanding assortment of single-page applications, I am exploring strategies to efficiently organize their UI tests. My current approach involves writing a test module for each page in order to validate it thoroughly ...

Angular.js filter issue: "Error: textProvider is not recognized provider"

I implemented a custom filter for my AngularJS project that is similar to the one in this fiddle http://jsfiddle.net/tUyyx/. myapp.filter('truncate',function(text,length){ var end = "..." text = text.replace(/\w\S*/g, function( ...

Utilizing the request body value within the .withMessage() function of the Express validator chain

I am looking to showcase my express validator errors with the specific value entered by the user. For instance, if a user types in an invalid username like "$@#" (using a regex that I will provide), I want to return my error message as follows : { "er ...

What is the best way to save an AJAX response to a text file using JS and jQuery?

It appears that this question is asked on a regular basis and the typical answer is "You shouldn't use AJAX for that. Just redirect to the file." However, my situation is unique because I am trying to access a file that doesn't physically exist ...

Exploring the functionality of async functions that utilize the await feature within the Karma and Jasmine JavaScript

Attempting to test an async function using Karma and Jasmine in an AngularJS v1.5.0 project. This async function, labeled as (a), contains 2 await statements: async function a(){ let var1 = await b() console.log(var1) let var2 = await c() } fu ...

Is it possible to display an unordered list upon clicking a button without relying on CSS and still achieve identical visual outcomes?

Within the responsive CSS of my web application, I am attempting to display the ul element inside the "mobile header" only upon clicking the "Connect Wallet" button. I want it to appear and disappear again as soon as anything else is clicked. Is there a w ...

Using javascript, hide or show a div without using jquery or the display:none property

I am looking for a way to show/hide a div up and down, but I have some requirements: I cannot use jQuery: toggle(), slideToggle(), fade, animate, etc. all use display: none, and I need the div to still occupy space in the DOM (I will be processing things ...

Encountering the issue "undefined title" when using the EJS template engine in Express framework

While studying NodeJS and utilizing EJS as a templating engine, I encountered an issue when clicking on the register button on my Registration page. The error message states that title is not defined. Here is the snippet of my code: users.js var express ...

The npm request was unsuccessful due to a self-signed certificate within the certificate chain causing the failure

I am attempting to launch a React Native project using Expo from this site npm install expo -g expo init AwesomeProject npm start However, when running npm start, I encounter the following error: npm ERR! code SELF_SIGNED_CERT_IN_CHAIN npm ERR! er ...

Is employing the HTML 'confirm' method considered a best practice?

How can I alert a user before they discard changes in a form while switching to another page? Is using if (!confirm("Are you sure")) return false;... considered a good practice for this type of message? Or should I consider using a modal panel instead? (W ...

Attempting to integrate a complex Ruby operation (using each loop and iterator) into a JavaScript platform (such as Google Charts API) by creatively combining them in a non-conventional manner during the development phase

It's time for my application to transition into production mode, and I have come to the realization that some of the code in development mode needs a major overhaul. Particularly, the views where I embedded data iteratively into Google Charts API Java ...

The response from the MySQL insert is not being received by the Ajax request

Currently, I am facing an issue with retrieving the return message after successfully inserting data into a MySQL database via AJAX. I have ensured that the data is being inserted correctly and I am using the latest versions of jQuery and PHP. The code sn ...

Looking to display the precise information from an opened Accordion in a modal window for updating purposes with Django

My main goal is to update data using a modal toggle button within a bootstrap accordion. Each question is retrieved from views.py and displayed within an accordion element. The ideal scenario is for each accordion to have a modal toggle button that, when c ...

How can I change the behavior of the Enter key in text fields to automatically submit the form, rather than requiring the user to

Utilizing material UI for my component library, I have a compact dialog with a "recover password" button placed within the form. However, upon adding this button, I noticed that pressing the "enter" key in the text fields triggers the onClick event of the ...

Refining the options in security question dropdown menus

Firstly: The title should mention filtering security options in dropdown lists, but it seems I'm restricted from using the term questions or question in the title. I came across this code example, but it appears to be outdated. Does anyone know why a ...

Is there JSON data available to determine the overall attendance rate in percentage?

I have a set of attendance data for a specific student. Each subject is marked with a 1 if the student was present, and a 0 if absent on a particular date. I need assistance in calculating the total attendance based on this information... { " ...

Reorder div elements using jQuery with two specific criteria

On my website, I have implemented a method for sorting divs (.ligne) with different sorting options: by name, date, status, and type. The jQuery code I've written works well, but I want to refine it further to make it lighter. When clicking on each h ...

Refreshing the page reveals the complete local storage object

I've successfully created a todo list using Vanilla Javascript along with local storage. The todo list includes the following key-value pairs: key: todolist value: [[\"id:0\",\"title:buy groceries\",\"done:false\"], [&b ...

I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other f ...