Reputation: 1102
I am having serious issues with my code that's being injected by a Chrome extension that I'm creating. Essentially, I need a keyup event listener to pickup a certain key but I can't seem to get it.
Here's the code that I'm injecting (Note that there is a lot of redundancy because I'm trying tons of things to get it to trigger the event listener, I will clean this up once I find the code that works).
function simulateKey(iElement) {
$( iElement ).focus();
var e = jQuery.Event("keyup");
e.which = 37;
e.keyCode = 37;
e.charCode = 0;
$( iElement ).keyup(function () {
console.log("keyup element");
});
$( iElement ).trigger(e);
var f = jQuery.Event("keyup");
f.which = 70;
e.keyCode = 70;
f.ctrlKey = true;
f.shiftKey = true;
$( iElement ).trigger(f);
$ ( document ).trigger(f);
$ ( window ).trigger(f);
}
When this function is called, the input element becomes focused and "keyup element" is printed to the console. But when this function is called and I have an Event Listener Breakpoint set for keyup events, the code never breaks out.
When I simply press a key on my keyboard while focused inside the input field and I have an Event Listener Breakpoint set for keyup events, there is a break in the source jquery.min.js and "(e)" is highlighted, which is the parameter for this function call: "f=v.handle=function(e)"... Take note that only one breakpoint happens normally, but if I have already called my function, then 2 breakpoints happen because I'm generating that console.log on keyup events.
Any help is extremely appreciated, thanks!
Upvotes: 2
Views: 4397
Reputation: 6606
Use the $.Event()
to create the requested event and than use .trigger()
.
DEMO: JSnippet
CODE:
$(function() {
var $iElement = $('#logit');
$iElement.keyup(function(e) {
console.log(e.which);
$(this).val(e.which);
});
simulateKey($iElement);
});
function simulateKey($iElement) {
var e = $.Event('keyup');
e.which = 65; // Character 'A'
$iElement.trigger(e);
}
Upvotes: 1