Reputation: 45
I want onkeypress event to only work when mouseover event is active.
For example: onkeypress shouldn't work if my mouse pointer isn't hovering over an specific element.
document.getElementById("image").onmouseover=function(){
document.onkeypress=function(event){
event = event || window.event;
var key = event.key || event.which || event.keyCode;
if(key===84){ //this is for 'T'
doThing();
}
}
}
I want something like this. But the code is not working. Sorry, if the question is not clear. I'm new at javascript so please forgive my mistakes.
Upvotes: 0
Views: 1641
Reputation: 6766
Create a flag to indicate when you are over the image or not. There are many ways. In this example, I am using HTML5 data-attribute to hold the flag.
Then when you press the key, check whether the flag is on to do your next step.
// set a flag when you are over the image
image.onmouseenter = function(){
console.log('set flag');
this.dataset.flag = 'true';
}
// unset the flag when you leave the image
image.onmouseleave = function(){
console.log('unset flag');
this.dataset.flag = 'false';
}
document.onkeypress = function (event) {
event = event || window.event;
var key = event.key || event.which || event.keyCode;
console.log('keypressed', key);
if (key === 'T' && image.dataset.flag && image.dataset.flag === 'true') {
console.log('do something');
}
}
<img id="image" src="https://images.pexels.com/photos/31418/pexels-photo.png?h=350&auto=compress&cs=tinysrgb" alt="" width="200">
Upvotes: 3
Reputation: 235
How about something like this? Perhaps you can extend this to help solve the problem.
var isHovered = false;
function keyDown(event) {
if (!isHovered) return;
var key = event.keyCode;
if(key === 84) {
console.log('we are hovered and pressing T!')
}
}
function hoveredBox() {
isHovered = true;
}
document.addEventListener('keypress', keyDown);
document.getElementById('elem').addEventListener('mouseenter', hoveredBox);
document.getElementById('elem').addEventListener('mouseleave', function() {
isHovered = false;
})
#elem {
height:100px;
width:100px;
background-color:red
}
<div id="elem"></div>
Upvotes: 1