0

I want to listen on ctrl + c key event on a div dom. I know I can add keypress event on the dom by setting its contentEditable to true (see below code). But it will make the div editable. What I want is to listen on ctrl + c event not make the div editable. Is there a way for me to do that?

$('.mydiv').attr('contentEditable', true);
$('.mydiv').focus();
$('.mydiv').bind('keypress', handler);
treyBake
  • 6,440
  • 6
  • 26
  • 57
Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523
  • Will the `
    ` have `:focus` when you're pressing `ctrl + c` ?
    – Alex Jul 12 '18 at 10:03
  • An element, what is not editable, can't have this events. You could listen to the whole document only, and see what is selected if `ctrl+c` is pressed. – eisbehr Jul 12 '18 at 10:04
  • [Link Might help](https://stackoverflow.com/questions/2903991/how-to-detect-ctrlv-ctrlc-using-javascript) – Siddharth Jain Jul 12 '18 at 10:14
  • read this : https://stackoverflow.com/questions/3149362/capture-key-press-or-keydown-event-on-div-element – MajiD Jul 12 '18 at 10:48

2 Answers2

1

You can try this. Run this in your debugger on this current page:

document.querySelector('.post-taglist').oncopy = _ => alert('CCCCCCC')

enter image description here

it should make entire div (marked on screenshot with yellow color) listen to copy event (CTRL + C). Now you can click anywhere on the div (for example, where red circle is marked on the screenshot), than CTRL + C and you should get alert 'CCCCCCC'

Andriy
  • 14,781
  • 4
  • 46
  • 50
0

If you add tabindex="0" to your <div> it will be able to get :focus without using contentEditable. You can then list for the ctrl + c like so:

var ctrlDown = false,
    ctrlKey = 17,
    cKey = 67;

$(document).keydown(function(e){
    if($('div').is(":focus")){
    if (e.keyCode == ctrlKey) ctrlDown = true;
    if (ctrlDown && e.keyCode == cKey){
        alert('dave');
        ctrlDown = false;
    }
  }
})

Check out this fiddle to see it working.

Alex
  • 8,875
  • 2
  • 27
  • 44