How do I simulate hover with Javascript on keydown? -
How do I simulate hover with Javascript on keydown? -
first of, i'd utilize native javascript finish task.
let's create custom dropdown, , html code looks kind of this.
<div class="dropdown"> <span class="dropdown-label" style="display:block">select thing</span> <ul class="dropdownitemcontainer"> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> <li>item 5</li> <li>item 6</li> </ul> </div>
in css file have close this:
ul.dropdownitemcontainer li:hover { background-color: #ff0000; }
yeah, there's no dropdownish behavior, it's not point of give-and-take actually. problem couldn't think of decent way enable keyboard command dropdown. desired outcome following: press downwards key, , first alternative highlighted; press again, , sec alternative highlighted , on.
the alternative see @ point (just started studying js) fetch of ul
's children, stick'em array , assign tags background color through js methods in proper way whenever downwards key pressed.
on other hand, still have :hover behavior described in css mouse countrol. there smart way of simulating hovers?
i go simple assignment of class on li-elements , steer keydown handler. next code not meant finish give can work with.
var active = document.queryselector(".hover") || document.queryselector(".dropdownitemcontainer li"); document.addeventlistener("keydown",handler); document.addeventlistener("mouseover",handler); function handler(e){ console.log(e.which); active.classlist.remove("hover"); if (e.which == 40){ active = active.nextelementsibling || active; }else if (e.which == 38){ active = active.previouselementsibling || active; }else{ active = e.target; } active.classlist.add("hover"); }
you can see working illustration here
javascript hover onkeydown
Comments
Post a Comment