Velocity.js Vertical Slide Pattern


April 29, 2015

I'd like to reuse JavaScript patterns as much as possible from project to project. Currently, I'm refactoring all my jQuery patterns to use velocity.js animation instead of CSS transitions. Here's a look at what I'm working on for slideUp/SlideDown interactions.

First, I want to cache all my elements and set a few variable to work with in the function:

var $el = $(element), // cache click target
 $con = $(container), // cache container target
 up = 'slideUp', // store up command
 down = 'slideDown'; // store down command

Then, in my click function I'll store the active class state for the clicked element, set the active class, and use velocity to do some animation:

$el.on('click', function(e) {

var active = $el.hasClass('active'); // store active state
e.preventDefault();
$el.toggleClass('active'); // set click target to active
$con.velocity(active ? up : down, { // test and init command
duration: duration, // duration set in function call params
easing: easing, // easing set in function call params
}); });

I'm using a ternary operator to test if the class on the clicked element is 'active' and then initializing the command based on that test. I want to reuse this code so I'm using variable parameters for easing and duration.

Here's a look at the entire function and function call:

var App = {};
// show/hide vertical slide pattern with Velocity.js
App.verticalSlide = function(element, container, easing, duration) {
var $el = $(element), // cache click target
$con = $(container), // cache container target
up = 'slideUp', // store up command
down = 'slideDown'; // store down command $el.on('click', function(e) {
var active = $el.hasClass('active'); // store active state
e.preventDefault();
$el.toggleClass('active'); // set click target to active
$con.velocity(active ? up : down, { // test and init command
duration: duration, // duration set in function call params
easing: easing, // easing set in function call params
});
});
};
$(document).ready(function() {
App.verticalSlide('.drawer-button', '.drawer', 'easeOutCirc', 900);
});

I made a CodePen to show how this works.

See the Pen Show/Hide pattern with Velocity.js by Jason Weaver (@indyplanets) on CodePen.

Latest Thoughts

Thanks for stopping by!