NewBoy
NewBoy

Reputation: 1144

using multiple events with the same function

I'm making attempts to clean up my code. Just wondering if there's a way to write this code better? I've added a snippet of my code below:

$('.popUp-block').on("click",function() {
    $('.protect-field-container').removeClass('is-displayed');
    $(this).closest('.protect-field-container').addClass('is-displayed');
});

$('.popUp-block').hover(function() {
    $('.protect-field-container').removeClass('is-displayed');
    $(this).closest('.protect-field-container').addClass('is-displayed');
});

$('.popUp-block').focusout(function() {
    $('.protect-field-container').removeClass('is-displayed');
});

$('.popUp-block').on("mouseout", function() {
    $('.protect-field-container').removeClass('is-displayed');
});

Upvotes: 2

Views: 265

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

In simple way, you can do it with .on():

$('.popUp-block').on("click mouseover",function() {
  $('.protect-field-container').removeClass('is-displayed');
  $(this).closest('.protect-field-container').addClass('is-displayed');
});

$('.popUp-block').on("mouseout focusout", function() {
  $('.protect-field-container').removeClass('is-displayed');
});

From the docs:

One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".

Upvotes: 3

Related Questions