Search code examples
javascriptjquerydelay

I need a delay when I change some text


I need a hint! I want to change some text with a delay in it. With .delay it isn't working because it isn't a queue. Then I tried it with .setTimeout. That worked, but only for one textbox. When I add another one, it doesn't work properly. Can anyone help me?

Here the code:

$('#text-box1').hover(function() {
     $('#text-box1').text("The text changed!");
}, function() {
     $('#text-box1').text("The previous Text");
});

Solution

  • You need to know if there is some timeout working and stop it first. Here is your solution:

    $(function(){
        var to;
        var $tb1 = $('#text-box1');
    
        $tb1.on('mouseenter', function(){
            if( to !== undefined ) return;
            var $this = $(this);
            to = setTimeout(function(){
                $this.text('The text changed!');
                to = undefined;
            }, 500);
    
        }).on('mouseleave', function(){
            if( to !== undefined ) return;
            var $this = $(this);
            to = setTimeout(function(){
                $this.text('The previous Text');
                to = undefined;
            }, 500);
        });
    });
    

    Check jsFiddle