Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetInterval for hover event

I have input field here, when I hover on input field asterisk adds, when I lose hover input text is clean. How with setInterval(maybe) I can add additional asterisk in input field every second when it's hovered?

$('body').append("<input type='text' />");

  $('input').hover(function() {
     $(this).val('*' + $(this).val());
  })
$('input').mouseleave(function() {
  $(this).val('');
})
like image 295
Bybnovskiy Avatar asked Jan 18 '26 15:01

Bybnovskiy


2 Answers

Use an interval and store it in $.data to clear it on mouseeleave

var input = $('<input />', {
  type : 'text',
  on   : {
    mouseenter : function() {
      var self = this;
      
      $(this).val('*').data('interval', setInterval(function() {
        self.value += '*';
      },1000));
    },
    mouseleave : function() {
      clearInterval( $(this).data('interval') );
      this.value = "";
    }
  }
});

$('body').append(input);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

FIDDLE

like image 200
adeneo Avatar answered Jan 20 '26 03:01

adeneo


You have to also use clearInterval to prevent the function to be executed when the mouse leaves the input.

You should store the ID that setInterval returns. When mouse leaves (or mouse hovers again), you can clear the previous interval id.

  $('body').append("<input type='text' />");
  var id = null;
  $('input').hover(function() {
    var element = this;
    clearInterval(id)
    id = setInterval(function () {
     $(element).val('*' + $(element).val()); 
    }, 1000)

  })
  $('input').mouseleave(function() {
    clearInterval(id)
    console.log(id);
    $(this).val('');
  })

https://plnkr.co/edit/wKiw8B8oihQBZU5gTcdk?p=preview

like image 33
Aᴍɪʀ Avatar answered Jan 20 '26 04:01

Aᴍɪʀ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!