Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen keyboard events on svg

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.

like image 688
Harshal Avatar asked Feb 04 '15 14:02

Harshal


People also ask

How do you handle keyboard events?

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.

How do I trigger an event on my keyboard?

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.


2 Answers

Because SVG is not an input-type, listen for the event on the window instead:

$(window).on('keypress', function (evt){ ... })
like image 197
Diodeus - James MacFarlane Avatar answered Oct 14 '22 01:10

Diodeus - James MacFarlane


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.

like image 27
DarthVanger Avatar answered Oct 14 '22 01:10

DarthVanger