Tips for smoothly animating and showing content as the user scrolls to a specific element on the page

Here is a sample template:

<template>
    <div id="Test">
        <transition name="fade">
            <div class="row" id="RowOne">
                <p>Lorem ipsum dolor odit qui sit?</p>
            </div>
        </transition>
        <transition name="fade">
            <div class="row" id="RowTwo">
                <p>Lorem ipsum dolor sit amet, consectetur.</p>
            </div>
        </transition>
        <transition name="fade">
            <div class="row" id="RowThree">
                <p>Lorem ipsum dolor sit amet, tenetur!</p>
            </div>
        </transition>
    </div>
</template>

I would like to showcase and animate RowOne, RowTwo and RowThree when they are visible in the viewport through scrolling. Just like how elements on the Laracasts website appear and move as you scroll down. Is it achievable with Vue.js and JavaScript?

Answer №1

If you want to achieve this using a directive, here is how:

Vue.directive('vpshow', {
  inViewport (el) {
    var rect = el.getBoundingClientRect()
    return !(rect.bottom < 0 || rect.right < 0 || 
             rect.left > window.innerWidth ||
             rect.top > window.innerHeight)
  },

  bind(el, binding) {
    el.classList.add('before-enter')
    el.$onScroll = function() {
      if (binding.def.inViewport(el)) {
        el.classList.add('enter')
        el.classList.remove('before-enter')
        binding.def.unbind(el, binding)        
      }
    }
    document.addEventListener('scroll', el.$onScroll)
  },

  inserted(el, binding) {
    el.$onScroll()  
  },

  unbind(el, binding) {    
    document.removeEventListener('scroll', el.$onScroll)
    delete el.$onScroll
  }  
})

To make elements animate when they come into view, add the v-vpshow directive to those elements.

For instance:

<div class="row" id="RowOne" v-vpshow>...</div>

This directive works with two classes:

1) before-enter: hides the element by default and is added automatically upon binding.

2) enter: should contain the transition for when the element becomes visible.

v-vpshow will automatically unbind itself once the element is visible, removing any data or event listeners set during bind.

Here's a live demo:

Vue.directive('vpshow', {
  inViewport (el) {
    var rect = el.getBoundingClientRect()
    return !(rect.bottom < 0 || rect.right < 0 || 
             rect.left > window.innerWidth ||
             rect.top > window.innerHeight)
  },
  
  bind(el, binding) {
    el.classList.add('before-enter')
    el.$onScroll = function() {
      if (binding.def.inViewport(el)) {
        el.classList.add('enter')
        el.classList.remove('before-enter')
        binding.def.unbind(el, binding)        
      }
    }
    document.addEventListener('scroll', el.$onScroll)
  },
  
  inserted(el, binding) {
    el.$onScroll()  
  },
  
  unbind(el, binding) {    
    document.removeEventListener('scroll', el.$onScroll)
    delete el.$onScroll
  }  
})

new Vue({
  el: '#app',  
})
/* v-vpshow classes */
.before-enter {
  opacity: 0;
}

.enter {
  transition: opacity 2s ease;  
}
/* ---------------- */

.row {  
  display: flex;
  min-height: 500px;
  justify-content: center;
  font-size: 20px;
  font-family: tahoma;
}

#RowOne {
  background-color: yellow;  
}

#RowTwo {
  background-color: #5D576B;
}

#RowThree {
  background-color: #F7567C;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>

<div id="app">
    <div id="Test">
        <div class="row" id="RowOne" v-vpshow>
            <p>Lorem ipsum dolor sit amet, consectetur.</p>
        </div>
        <div class="row" id="RowTwo" v-vpshow>
            <p>Lorem ipsum dolor sit amet, consectetur.</p>
        </div>
        <div class="row" id="RowThree" v-vpshow>
            <p>Lorem ipsum dolor sit amet, tenetur!</p>
        </div>
    </div>
</div>

Answer №2

A good approach would be to change the display property from none to a visible value once you notice that the user has scrolled past a specific point.

For more details on how to achieve this, check out this helpful link: Show div on scrollDown after 800px

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

Using JavaScript to block form submission based on AJAX response

I am having trouble understanding why this code is not working as expected to prevent a submit. I have made sure all the HTML elements are properly linked and all alerts display correctly. It doesn't seem like I am losing scope on the event. If anyone ...

Release a stationary element upon scrolling down the page

I have a calculator feature on my website which was coded in php. At the end of this calculator, there is a section that displays the results. While the results div works properly on desktop, I am looking to implement a fix for mobile devices. Specificall ...

What's the best way to link two http requests in AngularJS?

Currently, I am facing the challenge of chaining two http calls together. The first call retrieves a set of records, and then I need to fetch finance data for each individual record. flightRecordService.query().$promise.then(function (flightRecords) { $ ...

Learn the process of marking an option as selected within an Angular component

I have an Angular component that displays a question along with a dropdown menu (<select>) to choose from various answers. My goal is to programmatically set one of the options as selected based on certain parameters present in the application' ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

When a div is covered by an if statement

One of the challenges I am facing is managing a view with multiple projects, some of which are active while others are not. In my function, if a project's deadline has passed, it displays '0' days left on the view, indicating that these are ...

Capture the Vue slot's HTML content and store it in a variable

Is it possible to achieve something similar to this: <div id="app"> <div class="container"> <h1 class="title is-1" v-html="text"></h1> <get-slot-contents> <p>Hi there</p> <p>Hi <span ...

When using AngularJS filter, the comparator will evaluate to true and display the ng-repeat list even when the input

Recently, I stumbled upon this interesting example fiddle showcasing the use of a comparator parameter to filter exact matches: http://jsfiddle.net/api/post/library/pure/ The priority is supposed to be a number between 1-100, but due to inputting it as t ...

VUE JS - My methods are triggering without any explicit invocation from my side

I've encountered a frustrating problem with Vue JS >.<. My methods are being triggered unexpectedly. I have a button that is supposed to execute a specific method, but this method gets executed along with other methods, causing annoyance... Her ...

Achieve this effect by making sure that when a user scrolls on their browser, 50% of the content is entered into view and the remaining 50%

Is there a way to achieve this effect? Specifically, when the user scrolls in the browser, 50% of the content is displayed at the top and the other 50% is shown at the bottom. ...

Guide: Highlighting a selected link in Navigation without redirecting the page can be achieved in AngularJS by utilizing

I have a list of links that I want to be able to highlight when clicked without redirecting to the page. Below is the code snippet: HTML <ul class="nav nav-list"> <li ng-repeat="navLink in navLinks" ng-class="navClass('{{navLink.Title ...

How can I structure the response from HttpClient to make it compatible with *ngFor

I need assistance in solving a minor issue. I am working with data from a REST API, which is returned as an array of objects. After receiving this data in my service, I attempt to transform it and push it to a subject to notify my component about the arriv ...

Wcf Service does not define Angular JS methods

I am utilizing a WCF Service within an AngularJS application. The WCF Service is functional, and I am attempting to display a list of user records from a SQL database. However, upon running the application, I encountered the following errors: angular.js: ...

Guide on importing CDN Vue into a vanilla Typescript file without using Vue CLI?

In the midst of a large project that is mostly developed, I find myself needing to integrate Vue.js for specific small sections of the application. To achieve this, I have opted to import Vue.js using a CDN version and a <script> </script> tag ...

Establishing a primary color for all text in Vuetify

How can I set a base color for all text in a Vue + Vuetify project? I attempted to change the theme's primary color in vuetify.ts: export default new Vuetify({ theme: { themes: { light: { primary: "#E53935", }, }, }, } ...

Java REST service remains out of reach for JavaScript fetch call

Currently, I am in the process of learning about REST API. My goal is to make a call to a POST service implemented in Java from Javascript using fetch. However, I have encountered an issue where the request fails to reach the service whenever the @Produces ...

Creating a HTML and JavaScript carousel without relying on the animate function

I am currently facing some challenges with building a custom slider. While it moves forward smoothly using CSS animation, I'm struggling to implement a backward motion with an animation. It seems like I need to loop through the slides and try a differ ...

Does a document.onmodification event exist, or something similar?

Is there a specific event in JavaScript that triggers whenever an element is added, removed, or modified? Although lacking in detail, it is a straightforward question. ...

What is the most effective method for organizing and handling uploaded files within my editing software?

I am currently developing a social blog that includes a JavaScript-based editor for users to create their own blogs. One of the main challenges I am facing is related to uploading files and its limitations. Currently, I am storing images uploaded by users ...

React - Strategies for handling an empty array in .map() operations

Struggling with rendering an empty list in React and JavaScript, specifically for search results. The goal is to display search results after the user clicks on the search button. However, the list remains empty and does not update even after retrieving ...