Home > Software engineering >  Is there a way to focus element from querySelectorAll()?
Is there a way to focus element from querySelectorAll()?

Time:10-27

I want to focus my dropdown elements from keyboard (up and down keys).

My code:

var matches = document.querySelectorAll("div.dropdown-content > a");
var i = 0;
var focused = matches[i];

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
            i  ;
            focused.focus();
            break;
        case 38:
            i--;
            focused.focus();
            break;
    }
};

But it's actually not working. Console does not report any errors.

CodePudding user response:

Arrow key up is 38, down is 40, also check i range between 0, nodes.length

const matches = document.querySelectorAll('div.dropdown-content > a');
let i = 0;
let focused;
if (matches.length > 0) {
matches[i].focus();
focused = matches[i];
document.onkeydown = function(e) {
    e.preventDefault();
    switch (e.keyCode) {
        case 40:
            if (i < matches.length - 1) {
                i  ;
            }
            matches[i].focus();
            focused = matches[i];
            break;
        case 38:
            if (i > 0 ) {
                i--;
            }
            matches[i].focus();
            focused = matches[i];
            break;
    }
};
}
a { display: block; }
<div class="dropdown-content">
 <a href="#">Link</a>
 <a href="#">Link</a>
 <a href="#">Link</a>
 <a href="#">Link</a>
 <a href="#">Link</a>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You keep focusing the same element, focused is not updated when i changes.

Also, the keycode for down arrow is 40, not 37.

Finally, you should check that i is always between 0 and matches.length - 1.

var matches = document.querySelectorAll("div.dropdown-content > a");
var i = 0;

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 40:
            if(i < matches.length - 1) i  ;
            matches[i].focus();
            break;
        case 38:
            if(i > 0) i--;
            matches[i].focus();
            break;
    }
};
  • Related