Harshal
Harshal

Reputation: 948

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.

Upvotes: 12

Views: 7864

Answers (2)

DarthVanger
DarthVanger

Reputation: 1183

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.

Upvotes: 7

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

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

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

Upvotes: 10

Related Questions