Search code examples
javascriptjquerythissetintervaltoggleclass

toggleClass with setInterval for current class (this)


I have a couple of boxes that have a shadow. I want the shadow to pulse on hover. The code below works but obviously makes all shadows to pulsate when I hover any one of them. I've tried to use this in the setInterval function in order to apply the pulse effect on a single box only – but that breaks the code all together. What should I do?

$( ".pulse_label_shadow" ).hover(function() {
    setInterval(function() {
       $( '.pulse_label_shadow' ).toggleClass("pulse_label_shadow_hover");
    }, 450);
  }
);

Or perhaps better and/or easier, how can I add the setInterval while using:

$( ".pulse_label_shadow" ).hover(function() {
    $( this ).toggleClass("pulse_label_shadow_hover");
}, function() {
    $( this ).removeClass( "pulse_label_shadow_hover" );
   }
);

The css looks like this, if that makes any difference:

.pulse_label_shadow{
    -webkit-box-shadow: 0px 0px 35px 1px rgba(255,255,255,0.5);
    -moz-box-shadow: 0px 0px 35px 1px rgba(255,255,255,0.5);
    box-shadow: 0px 0px 35px 1px rgba(255,255,255,0.5);
    transition: all 0.8s ease;
}
.pulse_label_shadow_hover{
    -webkit-box-shadow: 0px 0px 95px 1px rgba(0,255,255,0.5);
    -moz-box-shadow: 0px 0px 95px 1px rgba(0,255,255,0.5);
    box-shadow: 0px 0px 95px 1px rgba(0,255,255,0.5);
}

And the HTML (for one of the boxes):

<div name="NameOfDiv">
    <a class="p1 scale1_toggle scale1_toggle_hide taphover ios_auto_playback floating show_text_on_enter1" rel="nofollow" aria-haspopup="false">
        <div class="indicator_up"><img src="images/indicators/up.png"/></div>
        <div class="pulse_label pulse_label_shadow border_up">
        <span class="ending_arrows">Title</span>
        </div>
    </a>
</div>

Edit: Thanks for a lot of great answers with different approaches. I'll select an answer once I've tested them out a bit more.


Solution

  • $( ".pulse_label_shadow" ).hover(function() {
        $( this ).addClass("pulse_label_shadow_hover");
    }, function() {
        $( this ).removeClass( "pulse_label_shadow_hover" );
       }
    );
    

    So this should add and remove classes as described, I think your problem is the 'pulse', where you will need to run the transition repeatedly. For this we should use an animation with 'animation-iteration-count:infinite'.

    @keyframes pulse {
        0% {  
            box-shadow: 0px 0px 35px 1px rgba(255,255,255,0.5); 
        }
        100% {  
            box-shadow: 0px 0px 95px 1px rgba(255, 0, 0 ,0.5); 
        }
    }
    
    
    .pulse_label_shadow_hover{ 
        animation: pulse 5s infinite; 
    }
    

    An example without jQuery to do the hover http://codepen.io/mrbizle/pen/QjEMeO