Search code examples
jquerydelaymouseovermouseout

wrong code jquery


So I'm have an animated gif on .mouseout and .mouseover and after 3 seconds I want to have a still image there. The method I'm using is to change the background-image of the div, so I have four images:

  1. when the page is loaded (i'm doing this in normal css file)
  2. when mouse is over (should be animated and i'm doing this jQuery)
  3. when mouse is out (should be animated and i'm doing this jQuery)
  4. 3 seconds after the mouseout event (should be normal)

I am stuck on 4 and don't know how to write the code, so here is what I have for 2 and 3:

    $("#ubBackground").hover(function(){
        $(this).stop().css("background-image","url(img/userBoxMouseOver.gif)");},
            function(){
      $('#ubBackground').css('background-image','url(img/userBoxMouseOut.gif)');
                        }
    );

I think I should use .delay() but I don't know exactly how, any help is appreciated.


Solution

  • var timer;
    
    $("#ubBackground").on({
        mouseenter: function(){
            clearTimeout(timer);
            $(this).css("background-image","url(img/userBoxMouseOver.gif)");
        },
        mouseleave: function() {
            var self=this;
            $(this).css('background-image','url(img/userBoxMouseOut.gif)');
            timer = setTimeout(function() {
                $(self).css('background-image','url(img/userBox3secLater.gif)');
            }, 3000);
        }
    });
    

    Set a timer when the mouse leaves that changes the background after three seconds, and clear the timout in mouseenter in case the mouse enters again within the three seconds.