Ilja
Ilja

Reputation: 46499

Function is being called without trigger event

I have a function that I want to use in order to expand menus in various places. I expect it to be triggered on a click of menu associated button, but at the moment it is being called on page load (I assume from within document ready), and class 'expanded' is added without clicking on a buton. I am confused to why this happens, as it should be called .on('click' ..

jQuery(document).ready(function ($) {
    'use strict';

    $('#btn-expand-mobile-nav').on('click', showMenu('#side-navigation'));

});

function showMenu(menu) {
    var x = $(menu),
        y = 'expanded';
    if (x.hasClass(y))
        x.removeClass(y);
    else
        x.addClass(y);
}

Upvotes: 1

Views: 690

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93581

You are calling the function immediately. Instead defer the execution using an anonymous function:

$('#btn-expand-mobile-nav').on('click', function(){
     showMenu('#side-navigation')
});

If there were no parameters you could have done this:

$('#btn-expand-mobile-nav').on('click', showMenu);

Simplistic explanation for @skobaljic:

By using the function name alone, you are pointing at the variable showMenu and saying call this later as a function.

By using function(){} you are saying, here is a temp variable, containing a function, that you can call later.

e.g. it is the same as:

var temp = function(){
     showMenu('#side-navigation')
}
$('#btn-expand-mobile-nav').on('click', temp);  // No parenthesis on temp

As @Dave Newton rightly points out, this can be simplified using toggleClass:

$('#btn-expand-mobile-nav').on('click', function(){
     $('#side-navigation').toggleClass("expanded");
});

Upvotes: 4

Related Questions