Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually trigger an event on window object

I am adding a listener like so:

    window.addEventListener('native.showkeyboard', function (e) {
        ...
        ...
    });

I'm writing a unit test for this so I want to trigger the event. Im doing:

    window.trigger('native.showkeyboard');

But I end up with an error for that line saying:

    undefined is not a function

How can I manually trigger this event?

EDIT

I have also tried:

  $(window).trigger('native.showkeyboard');

but the handler doesnt run with this as it's not registered with jquery...

like image 653
Mark Avatar asked Jun 27 '14 14:06

Mark


People also ask

How do you trigger an event on click?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event.

How can I trigger an Onchange event manually in JavaScript?

document. querySelector('#test'). addEventListener('change', () => console. log("Changed!"))


1 Answers

If you are triggering the event via jQuery then the event ought to have been attached via jQuery -- see @fredericHamidi's comment.

$(window).on('native.showkeyboard', function (e) {
    .........
});

$(window).trigger('native.showkeyboard');

WORKING JSFIDDLE DEMO

Or if you're using plain vanilla JS do it this way:

window.addEventListener('native.showkeyboard', function (e) {
    ........
});

window.dispatchEvent( new Event('native.showkeyboard') );

WORKING JSFIDDLE DEMO

like image 95
PeterKA Avatar answered Oct 21 '22 12:10

PeterKA