rgex
rgex

Reputation: 119

addEventListener per element only

I want to make my canvas to exclusively respond to keydown/mouse EventListeners only.

Another user had this problem: addEventListener for keydown on Canvas

But the problem still persists: I have a canvas and an input box. I have the spacebar to trigger an event but when I want to type in an input element box, it will trigger as well.

How do I make keydown/mouse events exclusive for the canvas so it won't affect other elements such as my input?

 //js file
 gameCanvas = document.getElementById('gameCanvas');
 document.addEventListener("keydown", function(e){
    if(e.keyCode == 32) // triggers something in canvas
 }, false); 

 //html dom
 <canvas id="gameCanvas" tabindex='1'></canvas>

 //input that accidentally triggers the above event meant for canvas
 <input type="text" id="conversation"></input>

Upvotes: 2

Views: 1752

Answers (2)

Vincent1989
Vincent1989

Reputation: 1657

You can create separate keydown/click event for each of your input/canvas.

To get canvas to response to keydown you need to add tabindex="1".

Like so <canvas id="gameCanvas" tabindex="1"></canvas>

Both input and canvas will response to keyboard event when the right elements are selected and triggered when keys are pressed. If you prefer click event just replace keydown with click instead.

//js file
 gameCanvas = document.getElementById('gameCanvas');
 conversation = document.getElementById('conversation');

 gameCanvas.addEventListener("keydown", function(e){
    console.log(gameCanvas);
 }, false); 

 conversation.addEventListener("keydown", function(e){
    console.log(conversation);
 }, false);
#gameCanvas {
    background: blue;
    width: 100px;
    height: 100px;   
}
<p>gamecanvas</p>
<canvas id="gameCanvas" tabindex="1"></canvas><br />
<p>conversation</p>
 <input  id="conversation" type="text" tabindex="2"></input>

Upvotes: 3

Blindman67
Blindman67

Reputation: 54069

Canvas can not be focused

Keyboard events can be listened to by element if the element has focus. This can be a little problematic as the canvas will not take the focus and thus can not listen to keyboard events.

Your best bet is to use the document keyboard events and redirect the call depending on the current document focus or the target of the event.

function canvasKeyHandler(event) {
    // handle the key event 

}
document.addEventListener("keydown",(event) => {
    if(event.target.id !== "conversation"){ // redirect to canvas
        canvasKeyHandler(event);
    }else{
        // handle the key event for the input
    }
})

You can also check which element has the focus with document.activeElement which returns the active (focused) element.

Upvotes: -1

Related Questions