11

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.

4

2 Answers 2

11

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

$(window).on('keypress', function (evt){ ... })
3

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.

1
  • This works, thanks Darth.
    – Mattis
    Nov 8, 2021 at 22:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.