rod
rod

Reputation: 309

Trying to condense javascript into for loop

I've got the following code that I am trying to condense to a for loop but am having no luck:

$("#motion1-sub1-1").hover( function () {
$("#motion1-sub1-1 div").show();
  }, 
  function () { $("#motion1-sub1-1 div").hide();
  }
);
$("#motion1-sub1-2").hover( function () {
$("#motion1-sub1-2 div").show();
  }, 
  function () { $("#motion1-sub1-2 div").hide();
  }
);
$("#motion1-sub1-3").hover( function () {
$("#motion1-sub1-3 div").show();
  }, 
  function () { $("#motion1-sub1-3 div").hide();
  }
);
$("#motion1-sub1-4").hover( function () {
$("#motion1-sub1-4 div").show();
  }, 
  function () { $("#motion1-sub1-4 div").hide();
  }
);
$("#motion1-sub1-5").hover( function () {
$("#motion1-sub1-5 div").show();
  }, 
  function () { $("#motion1-sub1-5 div").hide();
  }
);

Here's the for loop code that have to condense the above code:

for (var i = 1; i <= 5; i++) {
 $("motion1-sub1-" +  i).hover( function () { $("motion1-sub1-" +  i + "div").show();
  }, 
  function () { $("motion1-sub1-" +  i + "div").hide();
  }
);
}

Upvotes: 1

Views: 72

Answers (3)

Sampson
Sampson

Reputation: 268344

No need for a for-loop, just bind to those elements that have a certain id pattern, and use this to reference them from within the hover functions:

$("[id^='motion1-sub1-']").hover(
    function(){
        $("div", this).show();
    },
    function(){
        $("div", this).hide();
    }
);

I don't know what type of element we're binding to, but you should provide that tag as part of the selector. For instance, if this is a div we're hovering, modify the selector to include that:

$("div[id^='motion1-sub1-']")

Or an even shorter, more DRY version:

$("[id^='motion1-sub1-']").on("mouseenter mouseleave", function(e){
    $("div", this).toggle( e.type === "mouseenter" );
});

Upvotes: 3

Andy Jones
Andy Jones

Reputation: 6275

You're missing a space on motion1-sub1-x div selector right before the div

 $("motion1-sub1-" +  i + " div")

Upvotes: 0

Steve
Steve

Reputation: 3046

How about giving all your divs a class of motion-sub and then doing

$(".motion-sub").hover(function() {
    $(this).show() }, function() { $(this).hide(); }
});

Upvotes: 3

Related Questions