0

I'm trying to sync hovering in two diferente tables... but for some reason when only the first part of the function works, adding the second part breaks the first part and gives me no errors.

I did not put it into the jsfiddle because its not a visual thing... its pure code that's breaking somewhere.

$(function(){
    //first part
        var trsCont = $('#conteudo table tr');
        for (i = 0; i < trsCont.length; i++) {
            trsCont.eq(i).hover(
                function () {
                    $('#coluna_fixa table tr').eq(i-1).toggleClass("hovered");
                    }
                );
            }
        //second part   
        var trsCol = $('#coluna_fixa table tr');
        for (i = 0; i < trsCol.length; i++) {
            trsCol.eq(i).hover(
                function () {
                    $('#conteudo table tr').eq(i+1).toggleClass("hovered");
                }
            );
        }
});

I know I am doing something wrong... can someone just point it out?

Thanks for reading this far.

3
  • If you take the first part out, does the second part work? Commented Feb 15, 2013 at 18:23
  • 2
    You really shouldnt define event handlers inside of loops Commented Feb 15, 2013 at 18:28
  • 1
    ... especially loops involving global iterator variables :-) Commented Feb 15, 2013 at 18:28

1 Answer 1

3

You really shouldnt define event handlers inside of loops. Instead you should make your hover functions more generic, like so:

//first part
       $('#table1 tr').hover(
           function () {
               var index = $(this).index();
               $("#table2 tr:eq(" + (index - 1) + ")").toggleClass("hovered");
           }
       );
        //second part   
        $('#table2 tr').hover(
           function () {
               var index = $(this).index();
               $("#table1 tr:eq(" + (index + 1) + ")").toggleClass("hovered");
           }
       );

Check out this JSFiddle for an example: http://jsfiddle.net/cAEWR/2/

Sign up to request clarification or add additional context in comments.

5 Comments

The problem is the logic needed. I need to trigger the hover event on the Table 2 Tr(X-1) when Table 1 Tx(X) is hovered.
@MBarni Ah, I did not notice that from the original code. Let me modify to JS Fiddle
Vice-versa must happen too.
@MBarni Updated. Should work for you now. JSFiddle is updated as well
Thank you very much! Very fast, constructive, wise coding and teaching.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.