I have a svg and I can draw multiple shapes on this svg. Now my requirement is I want to listen keyboard events like ctrl+C, ctrl+V, ctrl+D, Esc, Delete so that I can copy, paste , duplicate selected shape. But I have no idea about listening keyboard events on SVG . I tried following code but no luck !!
mySVG.on("keydown", function () {
//code to handle keydown
});
Any help ? Thanks in advance.
There are three different keyboard events in JavaScript: keydown : Keydown happens when the key is pressed down, and auto repeats if the key is pressed down for long. keypress : This event is fired when an alphabetic, numeric, or punctuation key is pressed down. keyup : Keyup happens when the key is released.
keydown: This event is triggered when a key is pressed down. keypress: This event is triggered when a key is pressed. This event fails to recognise keys such as tab, shift, ctrl, backspace etc. keyup: This event is triggered when a key is released.
Because SVG is not an input-type, listen for the event on the window instead:
$(window).on('keypress', function (evt){ ... })
Add tabindex="0"
attribute to the <svg>
and it will work:
const svgElement = document.querySelector('svg');
svgElement.addEventListener('keydown', event => {
console.log('svg keydown: ', event.key);
});
<svg tabindex="0" width="300" height="200">
<rect width="100%" height="100%" fill="#555" />
<text x="50%" y="50%" font-size="20" text-anchor="middle" fill="white">
Click me and start typing
</text>
</svg>
The tabindex attribute allows you to control whether an element is focusable, and ...
See MDN docs for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With