skip to Main Content

I’ve got a simple addClass function to add a class on hover so that I can apply a CSS transition to it. I also want the CSS transition to apply when the mouse leaves the container but It doesn’t work because I have .removeClass. I realize I can do it with CSS but I’m trying to learn JS.

I’ve tried the setTimeout like so:

    $('.wp-container-20').hover(
        function() {
            $(this).addClass('homeServicesImageHover').bind(this)
        },
        function() {
            setTimeout(
                function() {
                    $(this).removeClass('homeServicesImageHover')
                }, 5000)
        }
    )

I can’t get that to work.

3

Answers


  1. You have two problems.

    1. The second value you pass to hover() needs to be a function. You’re calling setTimeout immediately and passing the return value to hover().
    2. this means something different when it is in a function called by setTimeout. See this question
    Login or Signup to reply.
  2. Try to do this with css not jquery.

    Use .yourClass:hover and .yourClass to add CSS correctly. For example the CSS that you should write in .yourClass:hover is the CSS that has the class .imageHover

    Also I use this additional class (in your normal class not in :HOVER) that gives some effects on transition

    .yourNormalClass{
       /* ADDITIONAL CSS TO YOUR NORMAL CLASS */
       -webkit-transition: all 0.3s ease;                  
       -moz-transition: all 0.3s ease;                 
       -o-transition: all 0.3s ease;   
       -ms-transition: all 0.3s ease;          
       transition: all 0.3s ease;
    }
    
    .yourNormalClass:hover{
       /* Add the CSS apply to ImageHover class here */
    }
    

    I hope that my info help you :).

    Kind regards.

    Login or Signup to reply.
  3. you are adding and removing the same class (ImageHover) and it is not logical. You first add this class to the element and then remove it from that same element, so that it has no class at the end!
    For transition after mouse leave, you can use onmouseleave() event, too.
    Good Luck

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search