I try to move the green hover color on the buttons, with the four arrow keys on the keyboard. The thing is that it does not move normally. What I want is the following:
- pressing right, the green color goes to the right.
- pressing left, the green color goes to the left.
- Press up or down, the green color also goes to the middle row (Four-Five-Six) without removing the
from the HTML.
I want the green color to go in all directions depending on the button I press. eg if it is at 1 and press down, go to 4. If it is at 1 and press right to go to 2. If it is at 2 and press left, go to 1 etc
The keycodes are: Left:37, Right:39, Up:38, Down:40
How can it be done? Thanks a lot!!!
var button = $('button');
var buttonSelected;
$(window).keydown(function(e) {
if (e.which === 40) {
if (buttonSelected) {
buttonSelected.removeClass('selected');
next = buttonSelected.next();
if (next.length > 0) {
buttonSelected = next.addClass('selected');
} else {
buttonSelected = button.eq(0).addClass('selected');
}
} else {
buttonSelected = button.eq(0).addClass('selected');
}
} else if (e.which === 38) {
if (buttonSelected) {
buttonSelected.removeClass('selected');
next = buttonSelected.prev();
if (next.length > 0) {
buttonSelected = next.addClass('selected');
} else {
buttonSelected = button.last().addClass('selected');
}
} else {
buttonSelected = button.last().addClass('selected');
}
}
});
button.selected {
background: green
}
.all button {
border: 1px solid blue;
color: #222;
padding: 10px 25px;
cursor: pointer;
}
.all button:hover {
background-color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="all">
<button>One</button>
<button>Two</button>
<button>Three</button>
</div>
<div class="all">
<button>Four</button>
<button>Five</button>
<button>Six</button>
</div>
<div class="all">
<button>Seven</button>
<button>Eight</button>
<button>Nine</button>
</div>