Pergunta

I apologize for the title, it's kinda hard to explain though. I have these two divs:

<div id="a">
   <div class="categoryBlock"></div>
   <div class="categoryBlock"></div>
   <div class="categoryBlock"></div>
   <div class="categoryBlock"></div>
   <div class="categoryBlock"></div>
</div>

<div id="b">
   <div class="smallDef"></div>
   <div class="smallDef"></div>
   <div class="smallDef"></div>
   <div class="smallDef"></div>
   <div class="smallDef"></div>
</div>

If the user hovers over the second div in the first container, the second div in the second container should show. Same for the third, fourth, fifth, ...

I have this code:

var CatBlock = $("#content_main-portal-page .categoryBlock"); 
CatBlock.each(function() {
        $(this).hover(function() {
            var indexHoverItem = $("#a").find(".categoryBlock").index($(this));
            $("#smallDef").eq(indexHoverItem).stop(true,true).fadeIn(160);
        }, function() {
            var indexHoverItem = $("#a").find(".categoryBlock").index($(this));
            console.log(indexHoverItem);
            $("#smallDef").eq(indexHoverItem).stop(true,true).delay(160).fadeOut(160);
        });
    });

Currently, only the first hover works (on the first element), as if there were no each. Could anybody help me?

Foi útil?

Solução

I'm not sure if you overcomplicated your function or you wanted something else

$('#a div').hover(function () {
    $("#b div").eq($(this).index()).stop(true, true).fadeIn(160);
}, function () {
    $("#b div").stop(true, true).delay(160).fadeOut(160);
});

Outras dicas

I would suggest:

$('#a > div').on('mouseenter mouseleave', function (e) {
    var m = e.type === 'mouseenter' ? 'fadeIn' : 'fadeOut';
    $('#b > div').hide().eq($(this).index()).stop()[m]();
});

You could try adding IDs that indicate the pairing.

$("#a").each(function(i,e) {
    $(this).attr('tag','b'+i).attr('id','a'+1);
});
$("#b").each(function(i,e) {
    $(this).attr('tag','a'+i).attr('id','b'+1);
});
$("#a > div,#b > div").bind('hover',function(){
   $(this).fadeIn();
   $('#'+$(this).attr('tag')).fadeIn();
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top