How to run an event once?

Asked

Viewed 1,538 times

4

How to make an event to be triggered once?

<div>
  <span class="oi">
    OI
  </span>
</div>
$('.oi').mouseenter(function(){
    alert('OLÁ');
});

This is just a simple example.

5 answers

7

I recommend you use the method .one(), since it was developed precisely for situations like the one you described. It fires the event for given element only once. After that the event is untied from the element.

$('.oi').one('click', function(){
    alert('OLÁ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div>
    <button class="oi">Click me!</button>
</div>

In the above example only the first click on <button> will cause the alert() is displayed on the screen. This is because the event will be automatically removed by jQuery from the element after the first time.

4

A simple solution:

$('.oi').on('mouseenter', function(){
    alert('OLÁ');
    $('.oi').off('mouseenter');
});

As the method on adds events to an element, the off removes these events.

2


Follows a solution:

$(function() {

  $('div').on('mouseenter', function() {

      $('h1').html('Mouse Dentro');

    })
    .on('mouseleave', function() {

      $('h1').html('Mouse Fora');
      // Remove os eventos de mouseenter e mouseleave
      // Se você não for realmente fazer nada na saida do mouse
      // Basta utilizar o off dentro da funcão de mouseenter
      $('div').off('mouseenter').off('mouseleave');

    });

});
div { background: #eee;position: fixed;top: 0;left: 0;bottom: 0;right: 0;color: #333;font-size: 28px;text-align: center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h1>Mouse Fora</h1>
</div>

  • That’s exactly what I was looking for thanks

1

You can use a boolean variable to know if it is the first time the event is being fired and then set it to false.

var primeiravez_mouseenter = true;

$('.oi').mouseenter(function(){
    if(primeiravez_mouseenter)
    {
       alert('OLÁ');
       primeiravez_mouseenter = false;
    }      
});

0

Good afternoon, you can create a global variable to verify this, for example:

<script>
   var verifica = true;

   $('.oi').mouseenter(function(){
      if(verifica){
         alert('OLÁ');
         verifica = false;
      }
   });
</script>

<div>
  <span class="oi">
    OI
  </span>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.