javascript - Hover effects in for loops -
here html:
<div class=column1of4> <a rel="appendix" href="images/watermarks/watermark_pic1.jpg" title="bottle in mirror"> <img src="images/250-width/pic1.jpg" alt="" width="250px" height="250px" id="bottleinthemirrorpic"> </a> <a rel="appendix" href="images/watermarks/watermark_pic1.jpg" title="bottle in mirror"> <div id="bottleinthemirror" class="spanlink"> <p>bottle in mirror</p> </div> </a> </div>
and here javascript:
var texts = ['#bottleinthemirror']; var picture = ['#bottleinthemirrorpic']; ( var = 0; < 1; ++i ) { $.each(texts, function(i) { $(this).hide(); $([this, picture[i]]).hover(function() { $(this).show(); }, function() { $(this).hide(); }); });
basically, when hover on #bottleinthemirrorpic
, want #bottleinthemirror
show , want #bottleinthemirror
go away when hover off of both of them.
i want loop because going add more elements texts , picture, i'm wondering why javascript doesn't work? doesn't seem hide #bottleinthemirror
.
this code works want able loop through elements inside texts , picture why not using code:
$('#bottleinthemirror').hide(); $('#bottleinthemirrorpic, #bottleinthemirror').hover(function() { // in $('#bottleinthemirror').show(); }, function() { // out $('#bottleinthemirror').hide(); });
nested loops unnecessary, arrays one-dimensional. can try like:
var texts = ['#bottleinthemirror'], pictures = ['#bottleinthemirrorpic'], i, j, curtext, curpicture, generatehandlers; generatehandlers = function (text, picture) { $(text).hide(); $(text + "," + picture).hover(function () { //in $(text).show(); },function () { //out $(text).hide(); }); }; (i = 0, j = texts.length; < j; i++) { curtext = texts[i]; curpicture = pictures[i]; generatehandlers(curtext, curpicture); }
demo: http://jsfiddle.net/hq8xt/
the immediate problem binding events in loop event triggered later, when loop has finished. time, iterator (in case, i
) has reached last value (in case, j
). need create new scope capture values in arrays, i've done calling generatedhandlers
function , passing array values.
one thing i'd suggest combine texts
, pictures
arrays object, like:
var textpics = { '#bottleinthemirror': '#bottleinthemirrorpic' };
and loop on like:
var curtext, curpicture; (curtext in textpics) { curpicture = textpics[curtext]; generatehandlers(curtext, curpicture); }
Comments
Post a Comment