How do I simulate hover with Javascript on keydown?

点点圈 提交于 2019-12-05 10:43:24

I would go with a simple assignment of a class on your li-elements and steer it with a keydown handler. The following code is not meant to be complete but give you something you 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 a working example here

I would suggest removing the hover attribute from css. And add only a hovered class which is applied on keypresses and on mouseover

This could look like this in Code

var dropDown = document.getElementsByClassName("dropdownItemContainer")[0]

document.addEventListener("keydown",function (e) {
    if(e.keyCode == 38 || e.keyCode == 40 ) {
        var key = e.keyCode
        var hovered = dropDown.getElementsByClassName("hovered")
        if(hovered.length != 0 ) {
            cur = hovered[0]
            cur.className = ""
            cur = cur[(key==38?"previous":"next")+"ElementSibling"] || dropDown.children[key==38?dropDown.children.length-1:0] 
        } else {
            cur = dropDown.children[key==38?dropDown.children.length-1:0]
        }
        cur.className="hovered"
    }
});


dropDown.addEventListener("mouseover",function (e) {
    for( var i = 0,j; j = dropDown.getElementsByClassName("hovered")[i];i++)
        j.className = "";
    e.srcElement.className = "hovered";
});

Heres an example on JSFiddle

mohammad mohsenipur

Reality you didn't need any js for dropdown but You can use JavaScript Event for simulating it. You can use event like hover, focus, onclick

In JS You Can use This For Set Event

  document.getElementById('id').addEventListener('focus',function(e){
    //place code that want ran at event happened
  }  

In JQuery you can use bind, click ,...

  $('#id')bind('focus',function(e){
    //place code that want ran at event happened
  }

List of Event

http://www.quirksmode.org/dom/events/index.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!