Velocity.js Vertical Slide without jQuery


April 30, 2015

Yesterday I worked in Velocity.js for animation on my jQuery slide pattern and today I thought I go through that same pattern without using jQuery as a dependency. With requirements becoming more IE9+ I'm getting closer to leaving IE8 behind It's a lot easier to use vanilla JavaScript in projects with the exception of using classList. I'm using a classList shim to ease the pain of removing, adding, and toggling classes in IE9. Ideally the shim is loaded conditionally.

I'm using querySelector to get dom elements instead of jQuery's $ and storing up some variable commands:

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

Adding the click event listener is straight forward and well supported in IE9+:

el.addEventListener('click', function(event) { 

  var active = el.classList.contains('active'); // store active state 
  el.classList.toggle('active'); // toggle click target active
 
  Velocity(con, active ? up : down, { // test and init command 
    duration: duration, // duration set in function call params 
    easing: easing // easing set in function call params 
  }); 

  event.preventDefault();

});

One thing to note:

$element.velocity({});

has changed to:

Velocity(element, command {});

This new syntax does not work if you happen to have jQuery loaded. So I'm either all in with jQuery or not. I'm thinking I'll rewrite my patterns using both syntaxes so I can just grab the one I need and include it in my projects depending on if I'm supporting IE8 or not.

The entire function and function call looks like:

// velocity.js
// classList.js

var App = {};

// show/hide vertical slide pattern with Velocity.js IE9+
App.verticalSlide = function(element, container, easing, duration) {

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

  el.addEventListener('click', function(event) {
    var active = el.classList.contains('active'); // store active state
    el.classList.toggle('active'); // toggle click target active

    Velocity(con, active ? up : down, { // test and init command
      duration: duration, // duration set in function call params
      easing: easing // easing set in function call params
    });

    event.preventDefault();

  });
};

window.onload = function() {
  App.verticalSlide('.drawer-button', '.drawer', 'easeOutCirc', 600);
};

Here's the working example on CodePen:

See the Pen Vertical slide pattern with Velocity.js (without jQuery) by Jason Weaver (@indyplanets) on CodePen.

Latest Thoughts

Thanks for stopping by!