How to run an event once?

4

How do I get an event fired one time?

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

This is just a simple example.

    
asked by anonymous 01.03.2016 / 18:00

5 answers

2

Here's 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>
    
01.03.2016 / 18:11
6

I recommend using the .one () method, since it was developed just for situations like the one you described. It fires the event for a 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><buttonclass="oi">Click me!</button>
</div>

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

    
01.03.2016 / 18:12
4

A simple solution:

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

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

    
01.03.2016 / 18:09
1

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

var primeiravez_mouseenter = true;

$('.oi').mouseenter(function(){
    if(primeiravez_mouseenter)
    {
       alert('OLÁ');
       primeiravez_mouseenter = false;
    }      
});
    
01.03.2016 / 18:09
0

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

<script>
   var verifica = true;

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

<div>
  <span class="oi">
    OI
  </span>
</div>
    
01.03.2016 / 18:08