jQuery - Simultaneous hover actions on multiple CSS classes
-
30-04-2021 - |
Question
$(document).ready(function() {
$('.button').hover(function() {
$(this).toggleClass('button-hover',200);
},function() {
$(this).toggleClass('button-hover',200);
});
});
$(document).ready(function() {
$('.button-rounded').hover(function() {
$(this).toggleClass('button-rounded-hover',200);
},function() {
$(this).toggleClass('button-rounded-hover',200);
});
});
<div class="button">Add class `button-hover` to this `div` on mouse over.</div>
<div class="button button-rounded">Add class `button-hover` and
class `button-rounded-hover` to this `div` on mouse over.</div>
On the second div
, it takes 400 ms to do the whole animation: 200 for the button-hover
toggle, and then another 200 for the button-rounded-hover
toggle. How do I perform these toggles simultaneously?
Notes:
- I'm using OOCSS, so
button-rounded
extendsbutton
, andbutton-rounded-hover
extendsbutton-hover
. I don't want to definebutton-rounded-hover
almost exactly likebutton-hover
because that wouldn't be very DRY (Don't Repeat Yourself) so that's why I'm using two classes and two hover calls on the seconddiv
. - Both actions need to take 200ms. I don't want to make either of them 0 (instantaneous).
Solution
If every element that has .button-rounded
class also have .button
class (that's what I understood by "button-rounded extends button"), you should only add a hover handle to button, and select the class to be toggled based on whether or not your element has button-rounded class. Example:
$(document).ready(function() {
$('.button').hover(function() {
$(this).toggleClass(
($(this).hasClass('button-rounded') ? 'button-rounded-hover ' : '') +
'button-hover',
200
);
});
});
toggleClass also accpets a list of classes separated by spaces, so you can toggle multiple classes simultaneously that way.
Note: since both "over" and "out" functions are equals, you can use a single one and it will apply to both events.
OTHER TIPS
This should do it:
javascript:
$(document).ready(function() {
$('.button').hover(function() {
$(this).toggleClass('button-hover',200);
});
$('.button-rounded').hover(function() {
$(this).toggleClass('button-hover button-rounded-hover',200);
});
});
HTML:
<div class="button">Add class `button-hover` to this `div` on mouse over.</div>
<div class="button-rounded">Add class `button-hover` and class `button-rounded-hover` to this `div` on mouse over.</div>
Note removal of class button
from the second div, which may require redefinition of the two classes' CSS.