codenoob
codenoob

Reputation: 27

Simplifying two jQuery functions into one

Is there one function that would do the job of both of these (and anything that continued the format)?

   $("#1A").hover(function(){
         $(".route1A").stop().fadeToggle(500);
      });

  $("#1B").hover(function(){
      $(".route1B").stop().fadeToggle(500);
      });

The result would look something like below, where __ is code for 'these are the same':

$("#__").hover(function(){
  $(".route__").stop().fadeToggle(500);

Upvotes: 0

Views: 34

Answers (3)

mhodges
mhodges

Reputation: 11116

You can combine the selector for .hover() to include #1A, #1B, etc. and then just grab the id off of the element that triggered the hover event to create your class selector, like so:

$("#1A, #1B").hover(function(){
   $(".route" + this.id).stop().fadeToggle(500);
});

Upvotes: 4

Fueled By Coffee
Fueled By Coffee

Reputation: 2559

You can use a multi-selector. This will bind the event handler to all selectors included.

$("#1A, #1B").hover(function(){
    $(".route" + this.id).stop().fadeToggle(500);
});

Upvotes: 0

Thomas Cohn
Thomas Cohn

Reputation: 497

Perhaps something like this?

var names = ["1A", "1B"]; //Extend as needed
for(var i=0; i<letters.length; ++i) {
    $("#" + names[i]).hover(function() {
        $(".route" + names[i]).stop().fadeToggle(500);
    });
}

Upvotes: 0

Related Questions