1

I want to fire a key event when the mouse is over a certain part of the document and the key is pressed. I tried the following:

$(document).ready(function(){
    $("#main_content").keydown(function(e) {
        if(e.which == 40) {
            alert("button Down");
            return false;
        }
    });
});

I expected that wouldnt work but I cant think of another way to do it.

JSFIDDLE: http://jsfiddle.net/c57nkb9y/

Niko Lang
  • 549
  • 1
  • 5
  • 23
  • possible duplicate of [Capture key press (or keydown) event on DIV element](http://stackoverflow.com/questions/3149362/capture-key-press-or-keydown-event-on-div-element) – putvande Jun 24 '15 at 11:33
  • Yes thats what I thought but it works on $(document). There must be a way to do this. – Niko Lang Jun 24 '15 at 11:34
  • So you want to trigger a key event when you hover over the element? Or do you want to trigger it, when you are over it AND press the key? – putvande Jun 24 '15 at 11:35
  • I want to trigger it, when I am over it AND press the key. – Niko Lang Jun 24 '15 at 11:39
  • Than have a look at the duplicate post. That tells you how you can do it. Normally none `input` fields can't receive key events, so you have to add a `tabindex="x"` attribute to it. – putvande Jun 24 '15 at 11:42

3 Answers3

3

First solution

Create a variable to store mouse state, then update it when mouse enters and leaves:

let mouseIsOver = false
const content = document.getElementById('main_content')

content.addEventListener('mouseenter', () => {
  mouseIsOver = true
})

content.addEventListener('mouseleave', () => {
  mouseIsOver = false
})

document.body.addEventListener('keydown', event => {
  // When key pressed, check mouseIsOver
  if (mouseIsOver && event.which === 40) {
    alert('Button Down!')
  }
})

Second solution

Attach and Detach KeyPress listener when mouse enters and leaves:

const content = document.getElementById('main_content')

function keyPressHandler() {
  if (event.which === 40) {
    alert('Button Down!')
  }
}

content.addEventListener('mouseenter', () => {
  document.body.addEventListener('keypress', keyPressHandler)
})

content.addEventListener('mouseleave', () => {
  document.body.removeEventListener('keypress', keyPressHandler)
})
kube
  • 13,176
  • 9
  • 34
  • 38
0

As you can read here, attaching keyboard event listeners to unfocusable elements (like your #main_content div) is useless. Instead, I suggest you attach them to the window object, or the body element.

kube's answer should work fine, but you really don't need to listen to keydown events all the time when you're out of the main div. I propose this :

$(document).ready(function () {
    $("#main_content").mouseover(armKeyEvent);
    $("#main_content").mouseout(shutdownKeyEvent);

    function armKeyEvent() {
        $(window).keydown(function(e) {
            if(e.which == 40) {
                alert("button Down");
                return false;
            }
        });
    }

    function shutdownKeyEvent() {
        $(window).unbind('keydown');
    }
});

See this fiddle.

ttzn
  • 2,543
  • 22
  • 26
  • I hesitated to post the same approach. However, if you want to go this way you'll have to name your handler functions to prevent all handlers being unbound from `window` when shutdownKeyEvent is called. http://stackoverflow.com/questions/3972886/how-to-unbind-a-specific-event-handler – kube Jun 24 '15 at 19:12
-1

You can add your keypress event after mouseenter, and remove it on mouseleave:

$(document).ready(function () {
    $('#main_content').mouseenter(function () {
        console.log(this)
        $(document).keypress(function (e) {
            var code = e.keyCode || e.which;
            if (code == 40) {
                alert("button Down");
                return false;
            }
        });
    }).mouseleave(function () {
        $(document).on("keypress", function () {});
    });
});

UPDATED JSFIDDLE

Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35