Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Advanced Vue.js - Directives, Plugins, and Render Functions Chapter 17

The first thing we need to define is the jump animation in CSS:


@keyframes generateJump {
20%{transform: translateY(0);}
40%{transform: translateY(-30px);}
50%{transform: translateY(0);}
60%{transform: translateY(-15px);}
80%{transform: translateY(0);}
}
.kangaroo {
animation: generateJump 1.5s ease 0s 2 normal;
}

What this does is create a class named kangaroo that, when applied to an element, makes


it jump twice by translating it along the y axis.


Next, write a function that adds this class to a specified element in the JavaScript:


const jump = el => {
el.classList.add('kangaroo')
el.addEventListener('animationend', () => {
el.classList.remove('kangaroo')
})
}

The jump function adds the kangaroo class and then removes it when the animation is


finished.


We want to perform this action on a random element picked from the ones registered:


const doOnRandomElement = (action, collection) => {
if (collection.length === 0) {
return
}
const el =
collection[Math.floor(Math.random()*collection.length)]
action(el)
}

The doOnRandomElement function takes an action and a collection and applies the action


to a drawn element. We then need to schedule it at random intervals:


const atRandomIntervals = action => {
setTimeout(() => {
action()
atRandomIntervals(action)
}, Math.round(Math.random() * 6000))
}
Free download pdf