Jack_Hu Jack_Hu - 1 year ago 175
jQuery Question

How can I share a variable amongst a jQuery event map?

Given the following jQuery

.on()
event map:

$('header').on({
mouseenter: function(e) {},
mouseleave: function(e) {},
}, 'li');


How can I share a
var $this = $(this)
variable between both the
mouseenter
and
mouseleave
events to keep it DRY?

EDIT:

To be clearer, if I want to apply the logic to each event in the event map, let's say:

mouseenter: function(e) {
// Grabs the list element.
var $this = $(this);

// Gets the sub-menu of the active menu item, if there is one.
var $subMenu = $this.find('.main-menu__sub-menu').first();

if ($subMenu.length) {
// Do something...
}
},
mouseleave: function(e) {
// Perform the same checks, and get the same variables as above...
},
click: function(e) {
// Again, perform the same checks and grab the same variables as above...
}


I obviously don't want to repeat my logic, but I require getting the
li
element that's firing the event, which will be the same for all events within the event map... Hopefully that makes more sense?

Answer Source

With your expanded description, you could go for something like this:

function getSubmenu(li) {
    // Grabs the list element.
    var $li = $(li);

    // Gets the sub-menu of the active menu item, if there is one.
    var $subMenu = $li.find('.main-menu__sub-menu').first();
    return $subMenu;
}

$('header').on({
    mouseleave: function(e) {
        var $subMenu = getSubmenu(this)
        // do some stuff...
    },
    click: function(e) {
        var $subMenu = getSubmenu(this)
        // do some other stuff...
    }
 }, 'li');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download