javascript - How to condense this into a single function? -
i new js/jquery, cant figure out how keep code d.r.y, if possible @ don't know. using jquery on hover effect image. box1 being div , img_hover_effect being overlay on hover.
js:
$('.box1').hover(function () { $('.img_hover_effect').fadein(500); }, function () { $('.img_hover_effect').fadeout(400); }); $('.box2').hover(function () { $('.img_hover_effect_2').fadein(500); }, function () { $('.img_hover_effect_2').fadeout(400); }); $('.box3').hover(function () { $('.img_hover_effect_3').fadein(500); }, function () { $('.img_hover_effect_3').fadeout(400); });
you can use loop that.
an anonymous function inside loop used prevent breakage jquery events, try:
for(var = 1; <= 3; i++){ (function(num){ $('.box' + num).hover(function() { $('.img_hover_effect' + (num == 1 ? "" : num)).fadein(500) }, function(){ $('.img_hover_effect' + (num == 1 ? "" : num)).fadeout(400) }) })(i) }
Comments
Post a Comment