Search code examples
jqueryhovertoggleclassoocss

jQuery - Simultaneous hover actions on multiple CSS classes


$(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 extends button, and button-rounded-hover extends button-hover. I don't want to define button-rounded-hover almost exactly like button-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 second div.
  • 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.