0

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.

theAussieGuy
  • 157
  • 1
  • 2
  • 11

3 Answers3

3

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
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you. I think I have fixed the first problem and I deduce that I need to use the bind() function on the second problem? I'm just unsure where to put it. I assume it needs to be placed with the parent function but I haven't been able to get that working. I've edited my question to suit. – theAussieGuy Sep 29 '22 at 21:57
1

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.

Farimah
  • 27
  • 9
Fllopis
  • 79
  • 6
1

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

Farimah
  • 27
  • 9
  • Look at this line `function(){ $(this).addClass('ImageHover') },` - there's a comma at the end. OP is passing two *separate* parameters to the `hover` event, not calling removeClass immediately after addClass – freedomn-m Sep 29 '22 at 12:18