N.hwang
N.hwang

Reputation: 245

How create Key event and pass it to document?

I'd like to test key event handler. I searched and found the result that uses 'createEvent', 'dispatchEvent'.

var e = document.createEvent('HTMLEvents');
e.keyCode = 83;
e.initEvent(onkeydown, false, true);
document.dispathEvent(e);       

I did like above but not working. Could you somebody give me a sample or link?

Upvotes: 1

Views: 801

Answers (3)

Madhavan.V
Madhavan.V

Reputation: 845

document.addEventListener('onkeydown', function (e) {
      console.log("onkeydown event raised");
  		console.log(e);
	});
	var e = document.createEvent('HTMLEvents');
	e.keyCode = 83;
	e.initEvent('onkeydown', true, true);
	document.dispatchEvent(e);

You may go through this

Upvotes: 2

Zvezdas1989
Zvezdas1989

Reputation: 1465

This should be what you want to achieve I think.

  document.querySelector('.trigger-event').addEventListener('click', function(e){
    e.preventDefault(); 

    var e = new Event("keydown");
    e.key="a";    // just enter the char you want to send 
    e.keyCode=e.key.charCodeAt(0);
    e.which=e.keyCode;
    e.altKey=false;
    e.ctrlKey=true;
    e.shiftKey=false;
    e.metaKey=false;
    e.bubbles=true;
    this.dispatchEvent(e);

  }, false);
  document.querySelector('.trigger-event').addEventListener('keydown', function(e){
    e.preventDefault();
    alert('Got keydown ' + e.key);
  },false);

  document.addEventListener('keydown', function(e){
    e.preventDefault();
    document.getElementById('keyValue').innerHTML = e.key;
    document.getElementById('charCode').innerHTML = e.keyCode;
  });
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Demo</title>
</head>
<body>


  <h3>Demo</h3>
  <p>
    <button class="btn-flat-blue trigger-event">Trigger Keydown event</button>
  </p>




  <h3> Press a key to see the key code</h3>
  <p>
    key <span id="keyValue"></span> = charCode <span id="charCode"></span> 
  </p>
  
</div>
</body>
</html>

Upvotes: 0

3Dos
3Dos

Reputation: 3487

This is an obsolete way of handling events

Deprecated

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

If you want to handle keyup events on the entire document, here's the way from the MDN Documentation of Keyboard events :

window.addEventListener("keyup", function(event) {
  let str = "KeyboardEvent: key='" + event.key + "' | code='" +
            event.code + "'";
  let el = document.createElement("span");
  el.innerHTML = str + "<br/>";
 
  document.getElementById("output").appendChild(el);
}, true);
<div id="output"></div>

Upvotes: 0

Related Questions