NewBoy NewBoy - 6 months ago 16
Javascript Question

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');
});

Answer

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".

Comments