Search code examples
javascriptjquerymouseenter

Mouseenter/mouseleave multiple divs


I have three divs in a line going down a page with classes e.g. .class1, .class2, .class3.

when a users mouse enters either of the divs i want to show other divs (divA & divB), question is can i have multiple divs in the function?

this is what I have so far, for one div which works great:

$(document).ready(function(){
$("body").on("mouseenter", ".class1", function ()
{
$(this).children(".divA").slideDown();
$(this).children(".divB").slideDown();
});

$("body").on("mouseleave", ".class1", function ()
{
$(this).children(".divA").slideUp();
$(this).children(".divB").slideUp();
});
});

I want the effect to happen though if a use enters either .class1, .class2 or .class3

Without a similar function three times

I've tried .class1 && .class2 etc but no joy, also .class1 || .class2 etc but also no joy

Is this possible?


Solution

  • In jQuery you can separate selectors with , so in your case something like ".class1, .class2" and so forth.

    jQuery will then look for elements that match one or multiple of those selectors.

    Update:

    You can shorten the code a bit by binding both the events to the same callback, and use slideToggle() instead:

    $(function() {
       $("body").on("mouseenter mouseleave", ".class1, .class2, .class3", function ()
       {
           $(this).children(".divA, .divB").slideToggle();
       });
    });
    

    Haven't tried it, but this should be equivalent to your code in terms of functionality. Just a bit shorter.