Search code examples
javascriptjquerybrowserifyvelocitycommonjs

Uncaught TypeError: $(...).velocity is not a function


I have the following code:

var $ = require('jquery');
var velocity = require('velocity-animate');

module.exports = function () {

    function togglePanel () {

        $('.trip-assist-search-panel__container').velocity({
            height: '0px'
        },{
            duration: 400
        });

    }

    return {
        togglePanel: togglePanel
    };

}();

When togglePanel() gets triggered, the following error gets thrown:

Uncaught TypeError: $(...).velocity is not a function

Which is usually solved by making sure you're loading JQuery before a library that requires it. But, I am..

var $ = require('jquery'); // first
var velocity = require('velocity-animate'); // second

So.. what gives?


Solution

  • From the documentation:

    Module Loader: Browserify
    If you're using Velocity with jQuery, you must require jQuery before Velocity, and you must assign jQuery globally on the window object:

    window.jQuery = window.$ = require("path/to/jquery-x.x.x.js");
    require("path/to/velocity.js");
    // Optional: If you're using the UI pack, require it after Velocity. (You don't need to assign it to a variable.)
    require("path/to/velocity.ui.js");
    /* Your app code here. */
    $("body").velocity({ opacity: 0.5 });
    

    You've only assigned jQuery to a local $ variable.