Aessandro
Aessandro

Reputation: 5761

jQuery callback function pass event

I have a click event as follow which works fine:

$('#showmenu').off('click').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();
    show_menu();
    return false;
});

where show_menu is:

function show_menu(e) {
    if (!collapseForm.is(':visible')) {
        collapseForm.show();
        showMenu.removeClass(chevronDown).addClass(checvronUp);
        searchAgain.hide();
    } else {
        collapseForm.hide();
        showMenu.removeClass(checvronUp).addClass(checvronDown);
        searchAgain.show();
    }
}

I would like to be able to do something like that:

$('#showmenu').off('click').on('click', show_menu(e));

Is it possible to pass "e" to the callback function by doing the following?

function show_menu(e) {
    e.preventDefault();
    e.stopPropagation();
    if (!collapseForm.is(':visible')) {
        collapseForm.show();
        showMenu.removeClass(chevronDown).addClass(checvronUp);
        searchAgain.hide();
    } else {
        collapseForm.hide();
        showMenu.removeClass(checvronUp).addClass(chevronDown);
        searchAgain.show();
    }
    return false;
}

enter image description here

Upvotes: 0

Views: 447

Answers (1)

Quentin
Quentin

Reputation: 943517

The event object is passed to the function when the function is called (by the event firing).

You have to pass the function to the on method.

$('#showmenu').off('click').on('click', show_menu);

Upvotes: 3

Related Questions