1

I'm using this script to toggle a class between a group of DIVs.

The keyboard nav works great, but if you mouse over a DIV, and then switch back to using your keyboard, you will notice the script does not remember the last DIV you moused over. It will continue to remember the last DIV you navigated to by keyboard.

Here is a JSFiddle demonstrating the problem: http://jsfiddle.net/bupGk/


What I am looking for is the correct equation that will calculate the index value for any given DIV on hover, with the class of column.

jQuery

var i = -1;
var all = $('.column');     

$('.column').hover(function(){ 
    $('.column').removeClass('scroll'), 
    $(this).addClass('scroll'), 
    i = $(this).eq() /*problem area*/
});

function traverse(ele) {
    all.removeClass("scroll");
    all.eq(ele).addClass("scroll");
}

$(document).keydown(function(e){

    if (e.which == 37) {
        e.preventDefault();
        traverse( i = !i ? all.length - 1 : --i );
    }

    if (e.which == 39) {
        e.preventDefault();
        traverse( i = ++i % all.length );
    }

});

2 Answers 2

1

Try this:

i = $(this).index()-1 

Index() without params gives the index relative to its sibling elements. fiddle: http://jsfiddle.net/bgg92/

eq() returns a jQuery object, not an integer.

eq() http://api.jquery.com/eq/

index() http://api.jquery.com/index/

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

1 Comment

Thank you! I had to change the code to i = $(this).index()-2 for my application, but it works perfectly.
0

Rather than i = $(this).eq(), use i = $(this).index().

Here's an example using your fiddle that will log i to the console: http://jsfiddle.net/bupGk/1/

Comments

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.