1

Is there a way to combine the following two instructions into more efficient code?

  $('.sandwiches').mouseleave(function () {
    $('.sandwiches').hide();
});
$('.food').mouseleave(function () {
    $('.sandwiches').hide();
});

3 Answers 3

1

By combining the selectors:

$('.sandwiches,.food').mouseleave...
Sign up to request clarification or add additional context in comments.

3 Comments

I have no idea. If you're worried about that, you may want to use the newer method: $('.sandwiches,.food').on('mouseleave',function...); which I believe creates just one.
if it is about efficiency I guess this is important to reduce callback numbers
@Sebas, .mouseleave is identical to .on('mouseleave') in that they both bind the handler to every element in the matched selection. In the case of delegated events (i.e. $('.foo').on('mouseleave', '.bar', fn)) handlers are bound to every element in the initial matched selection (i.e. every .foo element would have a handler, but it's likely that the .bar elements are far more numerous).
0

Merge the selectors:

$('.sandwiches, .food').mouseleave(function () {
    $('.sandwiches').hide();
});

Comments

0

You could attach a defined function to each element:

function hideElement(e) {
    $(this).hide();
}

$('.sandwiches,.food').mouseleave(hideElement);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.