How do I fire a JavaScript event trigger? - javascript

I have an input using a onkeypress trigger, and I'm trying to find a way to fire the event trigger with a specific keycode. I've looked around but all I find are jQuery solutions, and I don't want to use jQuery.
For a click trigger you'd just use document.forms[0].elements[1].click() but there doesn't seem to be a keypress() equivalent for onkeypress.

You can create an event and dispatch it to your Object. just like this:
if(document.createEvent) {
var evObj = document.createEvent('KeyEvent');
evObj.initEvent( 'keypress', true, false);
evObj.keyCode = 13; // Set your keyCode
document.getElementById("myid").dispatchEvent(evObj);
}
under IE/FF:
var evObj = document.createEventObject();
evnObj.keyCode = 13;
document.getElementById("myid").fireEvent("onclick",evObj);
event.cancelBubble = true;

Related

Programmatically send keys to input using dispatchEvent

I'm trying to send characters to an input element based on user actions.
I'm trying to use KeyboardEvent with dispatchEvent but whatever I do, it doesn't work
For example:
let keyEvent = new KeyboardEvent();
keyEvent.key = 'a';
keyEvent.keyCode = 'a'.charCodeAt(0);
keyEvent.which = event['keyCode'];
keyEvent.altKey = false;
keyEvent.ctrlKey = true;
keyEvent.shiftKey = false;
keyEvent.metaKey = false;
keyEvent.bubbles = true;
Not sure if this is correct, but I have dispatched it as follows:
document.querySelector('input').dispatchEvent(keyEvent);
document.activeElement.dispatchEvent(keyEvent);
document.dispatchEvent(keyEvent);
DEMO
If I first focus the input before clicking the button nothing really happens. Any suggestions what might go wrong here ?
Actually, due to security reasons, dispatching a KeyboardEvent to an input element does not generate the action you expect.
The KeyboardEvent document makes it quite clear:
Note: manually firing an event does not generate the default action
associated with that event. For example, manually firing a key event
does not cause that letter to appear in a focused text input. In the
case of UI events, this is important for security reasons, as it
prevents scripts from simulating user actions that interact with the
browser itself.
So the dispatchEvent stuff simply won't work.
Alternatively, consider manipulating the input element directly.
In base of your code here is a eventKeyboard, but:
- after dispatch keyevent, wath's next?, who is listener?
- ... i cant underdstand at all
document.querySelector('button').addEventListener('mousedown', (e) => {
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
console.log('send key');
/*let keyEvent = new KeyboardEvent();
keyEvent.key = 'a';
keyEvent.keyCode = 'a'.charCodeAt(0);
keyEvent.which = event['keyCode'];
keyEvent.altKey = false;
keyEvent.ctrlKey = true;
keyEvent.shiftKey = false;
keyEvent.metaKey = false;
keyEvent.bubbles = true;
console.log(keyEvent); */
var keyEvent = new KeyboardEvent("keydown", {
bubbles : true,
cancelable : true,
char : "A",
key : "1",
shiftKey : true,
keyCode : 81
});
document.querySelector('input').dispatchEvent(keyEvent);
document.activeElement.dispatchEvent(keyEvent);
document.dispatchEvent(keyEvent);
console.log(keyEvent);
});

How to trigger touch event on mouse click in GeckoFX using C#

I have been trying to trigger a touch event that is restricting me to perform click, as the function is prepared for Smart Phones.
Here is the function that I need to be called on click event using GeckoFX.
$('#next_button,#bottom_next_button,#next_arrow,.image_inner_a').on('touchstart', function(e) {
if (e.touches && e.touches[0].pageX > 5) {
this.href = this.href.replace(/[&?]z=[^&]*/, '');
valid_user = true;
}
});
What I have so far is written below.
GeckoElement clickedElement = e.Target.CastToGeckoElement();
if (xpathvalue != null) {
GeckoHtmlElement element = (GeckoHtmlElement)browser.Document.GetSingleElement(xpathvalue);
if (element != null)
{
element.Click();
}
}
If there is way to use JavaScript for calling the touch event, it would be accepted too.
You can dispatch a custom type of event.
Look at the event documentation here
https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
Then initialize the event:
nsAStringBase eventType = new nsAString(eventName.ToLower());
DomEventArgs ev = browser.Document.CreateEvent(eventTypeName);
ev.DomEvent.InitEvent(eventType, true, false);
And then try dispatching the event on a proper element
element.DispatchEvent(ev);

jQuery - triggering multiple events one by one

I'm using jquery tagsInput plugin where I need to dynamically modify the query(deleting the query or entering the new query) without actually typing in the search box connected with tagsInput plugin.
My problem here is I want to trigger backspace event at first then enter event next. Here is the code.
function triggering_events() {
$(".tag").each(function() {
var e = jQuery.Event("keydown");
e.keyCode = 8;
e.which = 8;
$("#input-search_tag").trigger(e); //triggering backspace event
});
var input = $("#input-search_tag");
input.val("food");
input.trigger(e); //triggering enter event
}
But only the backspace event is triggering from the above code. How can I make that enter event work?
Could anyone point out the mistake I've done?
Thanks!
you can try use the methods removeTag and addTag for remove and add tag's:
function triggering_events() {
var
idInput = 'input-search',
input = $("#" + idInput);
$("#"+idInput+"_tagsinput .tag").each(function() {
var tag = $.trim($(this).find('span:eq(0)').text());
input.removeTag(tag);
});
input.addTag("food");
}
run
There is an issue here:
$("#input-search_tag").val("food").trigger(e); //triggering enter event
.val() returns you a string value of the jquery Element, it is not a chainable method. strings do not have a trigger method.
You could fix this by splitting it into two calls:
var input = $("#input-search_tag");
input.val("food");
input.trigger(e); // triggering enter event
Or using .end():
$("#input-search_tag").val("food").end().trigger(e); //triggering enter event
Edit: putting it all together, along with reusing one event instead of creating multiples:
function triggering_events() {
var e = jQuery.Event("keydown");
e.which = 8;
$(".tag").each(function() {
$("#input-search_tag").trigger(e); // triggering backspace event
});
e.which = 13;
$("#input-search_tag").val("food").end().trigger(e); // triggering enter event
}

onchange event not fire when the change come from another function

I have an input text that get his value from a Javascript function (a timer with countdown).
I want to raise an event when the input text is 0 ,so I am using the change eventListener.
Unfortunately it doesn't seem to raise the event when the change is coming from javascript function.
How can I force the change event to work, even if the change is coming from Javascript and not from the user?
From the fine manual:
change
The change event occurs when a control loses the input focus and its value has been modified since gaining focus. This event is valid for INPUT, SELECT, and TEXTAREA. element.
When you modify the text input's value through code, the change event will not be fired because there is no focus change. You can trigger the event yourself though with createEvent and dispatchEvent, for example:
el = document.getElementById('x');
ev = document.createEvent('Event');
ev.initEvent('change', true, false);
el.dispatchEvent(ev);
And a live version: http://jsfiddle.net/ambiguous/nH8CH/
In the function that changes the value, manually fire a change event.
var e = document.createEvent('HTMLEvents');
e.initEvent('change', false, false);
some_input_element.dispatchEvent(e);
it's 2018 now and seems that initEvent() is deprecated:
https://developer.mozilla.org/en-US/docs/Web/API/Event/initEvent
i think you can trigger the event in a one-liner now:
element.dispatchEvent(new Event('change'));
A more reusable option :
function simulate_event(eventName, element) {
// You could set this into the prototype as a method.
var event;
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
};
event.eventName = eventName;
if (document.createEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent("on" + event.eventName, event);
}
};
Simply redefine the "value" property of the node, using getAttribute("value") and setAttribute("value", newValue), in the getters and setters, as well as dispatch the "change" event at the end of the setter. For example:
myNode.onchange = e => console.log("Changed!", e.target.value);
Object.defineProperty(myNode, "value", {
get: () => myNode.getAttribute("value"),
set(newValue) {
myNode.setAttribute("value", newValue);
myNode.dispatchEvent(new Event("change")); //or define the event earlier, not sure how much of a performance difference it makes though
}
})
var i = 0;
setTimeout(function changeIt() {
if(i++ < 10) {
myNode.value = i;
setTimeout(changeIt, 1000);
}
}, 1)
<input id="myNode">
Instead of using change, you can use keypress event instead.
This is because the change event is not meant to fire until it is not focused anymore - when you click out of the input tag.

Trigger a keypress/keydown/keyup event in JS/jQuery?

What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?
I don't want to actually put text in the input box, I just want to trigger all the event handlers that would normally get triggered by a user typing info into a input box. This means focus, keydown, keypress, keyup, and blur. I think.
So how would one accomplish this?
You can trigger any of the events with a direct call to them, like this:
$(function() {
$('item').keydown();
$('item').keypress();
$('item').keyup();
$('item').blur();
});
Does that do what you're trying to do?
You should probably also trigger .focus() and potentially .change()
If you want to trigger the key-events with specific keys, you can do so like this:
$(function() {
var e = $.Event('keypress');
e.which = 65; // Character 'A'
$('item').trigger(e);
});
There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.
You could dispatching events like
el.dispatchEvent(new Event('focus'));
el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
To trigger an enter keypress, I had to modify #ebynum response, specifically, using the keyCode property.
e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);
Here's a vanilla js example to trigger any event:
function triggerEvent(el, type){
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
You can achieve this with: EventTarget.dispatchEvent(event) and by passing in a new KeyboardEvent as the event.
For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))
Working example:
// get the element in question
const input = document.getElementsByTagName("input")[0];
// focus on the input element
input.focus();
// add event listeners to the input element
input.addEventListener('keypress', (event) => {
console.log("You have pressed key: ", event.key);
});
input.addEventListener('keydown', (event) => {
console.log(`key: ${event.key} has been pressed down`);
});
input.addEventListener('keyup', (event) => {
console.log(`key: ${event.key} has been released`);
});
// dispatch keyboard events
input.dispatchEvent(new KeyboardEvent('keypress', {'key':'h'}));
input.dispatchEvent(new KeyboardEvent('keydown', {'key':'e'}));
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
<input type="text" placeholder="foo" />
MDN dispatchEvent
MDN KeyboardEvent
You're now able to do:
var e = $.Event("keydown", {keyCode: 64});
First of all, I need to say that sample from Sionnach733 worked flawlessly. Some users complain about absent of actual examples. Here is my two cents. I've been working on mouse click simulation when using this site: https://www.youtube.com/tv. You can open any video and try run this code. It performs switch to next video.
function triggerEvent(el, type, keyCode) {
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.keyCode = keyCode;
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.keyCode = keyCode;
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
var nextButton = document.getElementsByClassName('icon-player-next')[0];
triggerEvent(nextButton, 'keyup', 13); // simulate mouse/enter key press
For typescript cast to KeyboardEventInit and provide the correct keyCode integer
const event = new KeyboardEvent("keydown", {
keyCode: 38,
} as KeyboardEventInit);
I thought I would draw your attention that in the specific context where a listener was defined within a jQuery plugin, then the only thing that successfully simulated the keypress event for me, eventually caught by that listener, was to use setTimeout().
e.g.
setTimeout(function() { $("#txtName").keypress() } , 1000);
Any use of $("#txtName").keypress() was ignored, although placed at the end of the .ready() function. No particular DOM supplement was being created asynchronously anyway.

Categories