Question

Select the div below the currently selected element.

Hi!

Okay, let say we have the following HTML code:

<div id="container">
   <div class="an-element selected"></div>
   <div class="another-one"></div>
   <div class="annnddd-onehere"></div>
   <div class="i-think"></div>
   <div class="you-got"></div>
   <div class="the-idea"></div>
</div>

the width of each div is fixed, but not the window size. On a big screen, all 6 elements are displayed on the same row. But on a smaller screen, the first row contain 4 elements and the second row contain 2 elements.

Now let's say the first element have the "selected" class. How can I add the "selected" class the the element below that one (if div does exists) ? (Obviously, the current .selected will be removed)

This is for a keyboard navigation system using the arrows.

Thanks for your time, as always ;)

edit

If the second element is selected, and the user press the down arrow, the sixth element will be affected. If the third element is selected, and the user press the down arrow, nothing is going to happen because there's no div under that one.

I found a little aniamtion showing the "concept" here: http://push-a-button.com/products/emucenter/

Was it helpful?

Solution

This can be done using elementFromPoint method. The idea is to test what element is located under the currently selected:

// testPos is the position under/over the selected element
var under = document.elementFromPoint(testPos.left, testPos.top);

// If the element has class block then we can highlight it
if (under && under.className == 'block') {
    selected[0].className = 'block';
    under.className = 'block selected';
}

Complete demo: http://jsfiddle.net/PMeNJ/1/

OTHER TIPS

try next() and addClass().

$('#container div.selected').next().addClass('selected');

however you if you have multiple selected div then you need to use loop to get each selected and addClass.

$('#container div.selected').each(function(){
   var $nextDiv=$(this).next();
   if(!$nextDiv.hasClass('selected'))
   {
        $nextDiv.addClass('selected');
    }
});

The code will be like:

var diff = window.resolution - (#container div).width()*(#container div).length)

now count if the "diff" is the multiple of how many (#container div).width().

if it is two then it will be the 5th item...add class selected here.

if it is one then it will be the 6th item...add class selected here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top