Creating Custom Scroll Directives — Vue.js (2024)

Base Example

There are many times that we might want to add a bit of behavior, especially animation, to a scroll event on a site. There are many ways to do so, but the path with the least amount of code and dependencies is perhaps to use a custom directive to create a hook for anything that fires off a particular scroll event.

Vue.directive('scroll', {
inserted: function (el, binding) {
let f = function (evt) {
if (binding.value(evt, el)) {
window.removeEventListener('scroll', f)
}
}
window.addEventListener('scroll', f)
}
})

// main app
new Vue({
el: '#app',
methods: {
handleScroll: function (evt, el) {
if (window.scrollY > 50) {
el.setAttribute(
'style',
'opacity: 1; transform: translate3d(0, -10px, 0)'
)
}
return window.scrollY > 100
}
}
})

<div id="app">
<h1 class="centered">Scroll me</h1>
<div
v-scroll="handleScroll"
class="box"
>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A atque amet harum aut ab veritatis earum porro praesentium ut corporis. Quasi provident dolorem officia iure fugiat, eius mollitia sequi quisquam.</p>
</div>
</div>

Remember! The directive must be registered before the Vue instance.

We’d also need a style property that will transition the intermediary values here, in this case:

See the Pen Custom Scroll Directive- CSS Transition by Sarah Drasner (@sdras) on CodePen.

Or, with GreenSock(GSAP) or any other JavaScript animation library, the code becomes even more simple:

Vue.directive('scroll', {
inserted: function (el, binding) {
let f = function (evt) {
if (binding.value(evt, el)) {
window.removeEventListener('scroll', f)
}
}
window.addEventListener('scroll', f)
}
})

// main app
new Vue({
el: '#app',
methods: {
handleScroll: function (evt, el) {
if (window.scrollY > 50) {
TweenMax.to(el, 1.5, {
y: -10,
opacity: 1,
ease: Sine.easeOut
})
}
return window.scrollY > 100
}
}
})

Though we would remove the previous CSS transition from this implementation because it’s now handled with JavaScript.

The Benefit of Using Custom Directives

Vue is rich with options for directives, most of which cover very common use-cases, which can create a very productive developer experience. But even if you have an edge case not covered by the framework, it’s got you covered in this case as well, because you can quite easily create a custom directive to fit your needs.

Attaching and removing scroll events to elements is a really good use case for this technique because just like other directives we use, they are necessarily tied to the element and otherwise, we’d have to find the reference for it in the DOM. This pattern avoids the need for traversal, and keeps the event logic paired with the node that it’s in reference to.

In the course of creating a cohesive site, you may find that you’re reusing the same type of animation logic in several areas. It seems simple, we would then create a very specific custom directive, right? Well, typically if you’re reusing it, you will need to change it just slightly for each use.

To help keep our code concise and legible, we would want to pass in some predefined arguments such as the beginning point and ending of the animation as we scroll down the page.

This example is better viewed in the full screen version.

See the Pen Scrolling Example- Using Custom Directives in Vue by Sarah Drasner (@sdras) on CodePen.

In the demo above, each of the sections has two different types of animation triggered from the scroll: a morphing animation, and a drawing animation that animates the individual paths in the SVG. We reuse those two animations, so we can create a custom directive for each. The arguments we’ll pass in will help keep everything simple and reusable.

To show how we do this, we’ll take a look at the morphing shape example, where we’ll need to state the start and finish, as well as pass in a path value that we’ll create a morph to. These arguments are each defined as binding.value.foo:

Vue.directive('clipscroll', {
inserted: function (el, binding) {
let f = function (evt) {
var hasRun = false
if (!hasRun && window.scrollY > binding.value.start) {
hasRun = true
TweenMax.to(el, 2, {
morphSVG: binding.value.toPath,
ease: Sine.easeIn
})
}
if (window.scrollY > binding.value.end) {
window.removeEventListener('scroll', f)
}
}
window.addEventListener('scroll', f)
}
})

We can then use this animation in our template, in this case we’re attaching the directive to the clipPath element, and pass all of our arguments to the directives in an object.

<clipPath id="clip-path">
<path
v-clipscroll="{ start: '50', end: '100', toPath: 'M0.39 0.34H15.99V22.44H0.39z' }"
id="poly-shapemorph"
d="M12.46 20.76L7.34 22.04 3.67 18.25 5.12 13.18 10.24 11.9 13.91 15.69 12.46 20.76z"
/>
</clipPath>

Alternative Patterns

Custom directives are extremely useful, but you may find some situations where you need something very specific that already exists in scrolling libraries that you don’t wish to rebuild from scratch yourself.

Scrollmagic has a very rich ecosystem of offerings to work with, as well as good documentation and demos to explore. This includes, but is not limited to things like parallax, cascading pinning, section wipes, and responsive duration.

##company## — ##description##

' }); Caught a mistake or want to contribute to the documentation? Edit this on GitHub! Deployed on Netlify .

Creating Custom Scroll Directives — Vue.js (2024)
Top Articles
FastGene RNA Basic Kit
Florida Lottery Powerball Double Play
Great Clips Mount Airy Nc
Skylar Vox Bra Size
Sandrail Options and Accessories
Belle Meade Barbershop | Uncle Classic Barbershop | Nashville Barbers
Craigslist Portales
Us 25 Yard Sale Map
Mylaheychart Login
Songkick Detroit
Gameplay Clarkston
Mivf Mdcalc
Nieuwe en jong gebruikte campers
Tiraj Bòlèt Florida Soir
Craigslist Estate Sales Tucson
Urban Dictionary Fov
Washington Poe en Tilly Bradshaw 1 - Brandoffer, M.W. Craven | 9789024594917 | Boeken | bol
Bjork & Zhulkie Funeral Home Obituaries
Flights To Frankfort Kentucky
Belle Delphine Boobs
Grasons Estate Sales Tucson
Justified Official Series Trailer
Moviesda3.Com
Jenn Pellegrino Photos
What Channel Is Court Tv On Verizon Fios
Xsensual Portland
Rapv Springfield Ma
Kentuky Fried Chicken Near Me
Обзор Joxi: Что это такое? Отзывы, аналоги, сайт и инструкции | APS
In hunt for cartel hitmen, Texas Ranger's biggest obstacle may be the border itself (2024)
Wisconsin Volleyball Team Leaked Uncovered
Slv Fed Routing Number
Truis Bank Near Me
Gabrielle Enright Weight Loss
Rocketpult Infinite Fuel
Ny Post Front Page Cover Today
Solemn Behavior Antonym
D3 Boards
Studio 22 Nashville Review
Kerry Cassidy Portal
Sukihana Backshots
Tfn Powerschool
Garland County Mugshots Today
Autozone Battery Hold Down
Searsport Maine Tide Chart
Headlining Hip Hopper Crossword Clue
Plumfund Reviews
Rovert Wrestling
Diablo Spawns Blox Fruits
Lorcin 380 10 Round Clip
Bellin Employee Portal
Dr Seuss Star Bellied Sneetches Pdf
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 5714

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.