javascriptmouseeventkeyboard-eventscustom-events

Triggering Keyboard events with data using JavaScript


This seems to be a duplicate question. But I have searched many places, I could not be able to find proper example of sending event data using plain javascript(not using jQuery).

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent doesn't have any example.

I need something like this. https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Adding_custom_data_.E2.80.93_CustomEvent

Example:

// listening for keypress event,    
ele.addEventListener("keydown", function(e){
    console.log(e.keyCode); //expecting 50
});


// triggering like this
var e = new KeyboardEvent("keydown", {keyCode: 50});
ele.dispatchEvent(e);

Solution

  • With the help of an awesome post http://www.2ality.com/2013/06/triggering-events.html from Dr. Axel Rauschmayer

    You can trigger using below 3 Constructors,

    // use any one of these constructor as per your usecase
    
    var e = new Event("keydown"); //without any data
    var e = new CustomEvent("keydown", {detail: {prop1: "value"}}); //if any data required use detail: only detail/bubbles/cancelable properties can be passed here
    var e = new KeyboardEvent("keydown");
    
    // add properties
    
    e.keyCode = 50; // works for *Event* and *CustomEvent* constructors
    e.key = 50; // in *KeyboardEvent* constructor *keyCode* is **readonly** property so use *key* property. Refer properties detail using https://developer.mozilla.org/en-US/docs/Web/Reference/Events/keydown
    e.anyNewProp = "value"; // if any new prop is required
    
    // finally dispatchEvent using dispatchEvent method of dom element
    
    ele.dispatchEvent(e);
    
    // listening for keypress event,    
    ele.addEventListener("keydown", function(e){
        console.log(e.keyCode); //results 50
        console.log(e.key); //results 50
        console.log(e.anyNewProp); //results "value"
    });