jquery - Trying to condense javascript into for loop -
i've got following code trying condense for loop 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 for loop code have condense above code:
for (var = 1; <= 5; i++) { $("motion1-sub1-" + i).hover( function () { $("motion1-sub1-" + + "div").show(); }, function () { $("motion1-sub1-" + + "div").hide(); } ); }
no need for-loop, bind elements have id pattern, , use this reference them within hover functions:
$("[id^='motion1-sub1-']").hover( function(){ $("div", this).show(); }, function(){ $("div", this).hide(); } ); i don't know type of element we're binding to, should provide tag part of selector. instance, if div we're hovering, modify selector include that:
$("div[id^='motion1-sub1-']") or shorter, more dry version:
$("[id^='motion1-sub1-']").on("mouseenter mouseleave", function(e){ $("div", this).toggle( e.type === "mouseenter" ); });
Comments
Post a Comment