I am trying to learn a bit about optimizing my jQuery code...
Is there a way to improve the code below so that the variable $selected is declared outside of the function, but still accessible, so that the DOM is not traversed every time?
Or is this code about as optimized as it could be?
Or... I suppose I may be misunderstanding how and when jquery DOM traversal happens.
$('#full-width-layout_c1_col-1-1_1').on(
'mouseenter mouseleave click',
'a.project_open, a.song_open',
function(e) {
var $selected = $(this).closest('tr').find('div');
if (e.type == 'mouseenter') {
$selected.addClass("hovered");
}
else if (e.type == 'mouseleave'){
$selected.removeClass("hovered");
}
else if (e.type == 'click'){
$selected.addClass('opened');
}
}
);