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('');
})
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With