Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript event keypress on hover

Hi I have multiple divs on the page. I want to raise an alert based on a user hovering over one of the divs and pressing control z. I need to in effect alert out what is in the span dependant upon which div the user is hovered over on.

I have tried with getbyId the problem arises with multiple elements. I am unsure if i need to bind every element.

    <div class="mydiv">Keypress here!<span>test</span></div>
    <div class="mydiv">Keypress here!<span>test1</span></div>

var pressed = false;

onload = function(e) {
    var myElement = document.getElementsByTagName('div');

    function keyaction(e, element) {

        //  var originator = e.target || e.srcElement;
        if (e.charCode === 122 && e.ctrlKey) {
            //myElement.innerHTML += String.fromCharCode(e.charCode);
            alert(true);
        }
    }

    for (var i = 0; i < myElement.length; i++) {

        myElement[i].addEventListener("mouseover", function (e)
        {
            document.addEventListener("keypress", function(t){keyaction(t,e);}, false);
        });

        myElement[i].addEventListener("mouseout", function ()
        {
            document.removeEventListener("keypress", keyaction, false);
        });
    }
}
like image 429
matt Avatar asked Oct 30 '22 16:10

matt


1 Answers

I think you are overdoing for what is needed. A simple keydown event bind on mouseover and unbind on mouseout would do the trick.

Here's an example :

 <div id="wrapper">
    <div class="mydiv">Keypress here!<span>test</span></div>
    <div class="mydiv">Keypress here!<span>test1</span></div>
</div>
<br>
    Keys Pressed : 
    <br>
    <div id="key"></div>

$("#wrapper .mydiv").on("mouseover",function()
{
    $(document).bind("keydown",function(e) {
        var originator = e.keyCode || e.which;
         if(e.ctrlKey)
         $("#key").append(originator + ",");
    });

}).on("mouseout",function()
{
    $(document).unbind("keydown");
});

http://jsfiddle.net/s095evxh/2/

P.S : for some reason , Jsfiddle doesn't allow keydown event on mouseover so you might have to click manually on the div to make it work but the solution works flawless on a local system.

like image 73
DinoMyte Avatar answered Nov 12 '22 15:11

DinoMyte