12

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.

Harshal
  • 961
  • 1
  • 11
  • 26
  • What do you mean when you say "no luck"? – Lars Kotthoff Feb 04 '15 at 14:37
  • As you stated this is D3.js-related, have a look at the following SO q&a where a possible solution is mentioned: http://stackoverflow.com/questions/15261447/how-do-i-capture-keystroke-events-in-d3-force-layout – SaschaM78 Feb 04 '15 at 14:39
  • No luck means , control doesn't come in handler. SaschaM78 thanks for ur help, I dont want to listen key events on whole body , I want key events on svg only as I have other components too in body – Harshal Feb 04 '15 at 14:41
  • 2
    svg 1.1 [does not handle keyboard events](http://www.w3.org/TR/SVG/interact.html#SVGEvents) (cf.section 16.2). svg 2 [will support them](http://www.w3.org/TR/SVG2/svgdom.html#RelationshipWithDOM3Events). – collapsar Feb 04 '15 at 14:43

2 Answers2

11

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

$(window).on('keypress', function (evt){ ... })
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
5

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.

DarthVanger
  • 1,063
  • 10
  • 10