plmok61 plmok61 - 3 months ago 8
Javascript Question

Tie children of one div to children of another div with jquery

I have two parent divs:

.inputs
and
.infoBoxes
. Each of them have an equal number of children. When the user clicks into the first
.input
in
.inputs
, the first
.infoBox
in
.infoBoxes
should
slideDown()
. Same for second, third, etc. I'd like to do this without re-writing the same code for each pair. So far I have:

var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();

for(var i = 0; i < $inputs.length; i++ ) {
$($inputs[i]).find('.input').focus(function() {
$($infoBoxes[i]).slideDown();
})
$($inputs[i]).find('.input').blur(function() {
$($infoBoxes[i]).slideUp();
})
}


This isn't working but I have tried replacing
i
with the indexes of each div.

$($inputs[0]).find('.input').focus(function() {
$($infoBoxes[0]).slideDown();
})
$($inputs[0]).find('.input').blur(function() {
$($infoBoxes[0]).slideUp();
})
repeat...
repeat...
repeat...


This works but isn't very DRY. I'm looking for a better solution that won't have me repeating a bunch of code.

Answer

First code will not work, because you using same variable for all internal functions. You should wrap it into function, which will create local variable for index. Try following code:

var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children(); 

for(var i = 0; i < $inputs.length; i++ ) {
    (function(ix) {
      $($inputs[ix]).find('.input').focus(function() {
        $($infoBoxes[ix]).slideDown();
      })
      $($inputs[ix]).find('.input').blur(function() {
        $($infoBoxes[ix]).slideUp();
      })
    })(i);
}