Search code examples
jquerymouseenter

How to create a jquery mouseover for multiple divs by id?


Hi I am trying to group a series of mouseover events to one but I am really new to javascript and getting really confused. I have 5 buttons like the one bellow and I want to create one function to include them all. I use the class of the divs for another function not included here. I believe that I have to use the ids for the mouseover.

$('#trigger1').mouseover(function(){ 
    $('#roll1r').fadeOut('slow');
});

http://jsfiddle.net/alexnode/fCw6y/2/

I use the conditional to define which element I want to hide but I am not sure how to define the variables and pass them to the fade out function. I have tried all sort of syntax to pass it as a string but I don't understand what is the problem.

$('#trigger1, #trigger2, #trigger3').mouseover(function () {
      var roll = null;
      var that = $(this);


        if (that==="#trigger1"){roll = "$('#roll1r')";}
        else if(that==="#trigger2"){roll ="$('#roll2r')";}
        else if(that==="#trigger3"){roll = "$('#roll3r')";}
        console.log(roll);
        roll.fadeOut({
            duration:300,
           // fail: that.hide()
        });
    });

     <div class="buttoncontainer" >

          <div id="buttonbg1">
          <img id="roll1" class="translatebuttons" src="images/buttonover.png" alt="Translation games">
<img id="roll1r" class="translatebuttons" src="images/button.png" alt="Translation games">
            <div class="translatebuttons" id="tr1"></div>
            <div id="trigger1" class="translatebuttons"></div>
            </div>

          <div id="buttonbg2">
            <img id="roll2" class="translatebuttons" src="images/buttonover.png" alt="Translation games"> <img id="roll2r" class="translatebuttons" src="images/button.png" alt="Translation games">
            <div class="translatebuttons" id="tr2"></div>
            <div id="trigger2" class="translatebuttons"></div>
          </div>


          <div id="buttonbg3">
            <img id="roll3" class="translatebuttons"  src="images/buttonover.png" alt="Translation games"> <img id="roll3r" src="images/button.png" alt="Translation games">
            <div class="translatebuttons" id="tr3"></div>
            <div id="trigger3" class="translatebuttons"></div>
            </div>

      </div>

Solution

  • You are looking for something like this? One way you can simplify you code with just one handler:

       $('[id^=trigger]').hover(function () { 
           var roll = $(this.id.replace(/trigger/, '#roll') + 'r');
           roll.fadeToggle({
            duration: 300
          });
       });
    

    Fiddle

    • Use startswith selector to select all triggers
    • Use hover for a shortcut to mouseenter/mouseleave
    • use simple regex repalce to calculate the id of respective roll
    • Use fadeToggle to toggle the fading state of roll.