Reputation: 559
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/
Upvotes: 1
Views: 1284
Reputation: 13934
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!')
}
})
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)
})
Upvotes: 3
Reputation: 2613
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');
}
});
Upvotes: 0
Reputation: 4100
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 () {});
});
});
Upvotes: -1