looks here:
that from One page that show me that element have event of doubleclick "dblclick"
but when i try to perform it from console:
dblclick is not a method, it is a type of event.
Let's say you have a button, and you wanted to manually fire that event. You could do so like this.
<button id='myButton'>Click Me!</button>
Now you can do this
var evt = new Event('dblclick');
var button = document.getElementById('myButton');
// This is where the magic happens
button.dispatchEvent(evt);
This manually fires the dblclick event.
You must call 'dispatchEvent' on a dom node, and it takes an 'Event' object.
For your use case, just replace the 'button' element with your own 'a' variable, and it should work as expected.
That answer works as well:
thank you both guys
noahnu and epascarello
var event; // The custom event that will be created
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent("dblclick", true, true);
} else {
event = document.createEventObject();
event.eventType = "dblclick";
}
event.eventName = "dblclick";
if (document.createEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent("on" + event.eventType, event);
}
Related
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.
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.
I want to apply a click event to an entire page in Javascript, to everything but a single banner on top. Let's say that the banner that I don't want the event in has an id of 'bannerID'. I tried doing the following:
document.onclick = function(){clickEvent()}
document.getElementById("bannerID").onclick = function(){return false;}
However, it looks like the document event overrides everything. Does anyone have any advice?
Check for the element-id within the handler, something like;
document.onclick = clickEvent;
function clickEvent(e) {
var from = e.target || e.srcElement;
if (from.id === 'bannerID') { return; }
/* ... the handling continues ... */
}
This is called event delegation
Pass in an event parameter to the callback and check if the id is 'bannerID'
document.onclick =
function(event){
if(event.target.id != 'bannerID'){
clickEvent()
}
};
demo
In the code you have above, you are adding two click events to "bannerID" - so it will execute clickEvent() and return false.
You can, however, exclude the specific element from the onclick function. This might help:
document.onclick = function(e) {
if (e.target.id === 'bannerID') {
return false;
} else {
clickEvent();
}
};
I need to capture an event instead of letting it bubble. This is what I want:
<body>
<div>
</div>
</body>
From this sample code I have a click event bounded on the div and the body. I want the body event to be called first. How do I go about this?
Use event capturing instead:-
$("body").get(0).addEventListener("click", function(){}, true);
Check the last argument to "addEventListener" by default it is false and is in event bubbling mode. If set to true will work as capturing event.
For cross browser implementation.
var bodyEle = $("body").get(0);
if(bodyEle.addEventListener){
bodyEle.addEventListener("click", function(){}, true);
}else if(bodyEle.attachEvent){
document.attachEvent("onclick", function(){
var event = window.event;
});
}
IE8 and prior by default use event bubbling. So I attached the event on document instead of body, so you need to use event object to get the target object. For IE you need to be very tricky.
I'd do it like this:
$("body").click(function (event) {
// Do body action
var target = $(event.target);
if (target.is($("#myDiv"))) {
// Do div action
}
});
More generally than #pvnarula's answer:
var global_handler = function(name, handler) {
var bodyEle = $("body").get(0);
if(bodyEle.addEventListener) {
bodyEle.addEventListener(name, handler, true);
} else if(bodyEle.attachEvent) {
handler = function(){
var event = window.event;
handler(event)
};
document.attachEvent("on" + name, handler)
}
return handler
}
var global_handler_off = function(name, handler) {
var bodyEle = $("body").get(0);
if(bodyEle.removeEventListener) {
bodyEle.removeEventListener(name, handler, true);
} else if(bodyEle.detachEvent) {
document.detachEvent("on" + name, handler);
}
}
Then to use:
shield_handler = global_handler("click", function(ev) {
console.log("poof")
})
// disable
global_handler_off("click", shield_handler)
shield_handler = null;
Can somebody tell me what I am doing wrong?
window.onload = initForm;
function initForm() {
var allTags = document.getElementsByTagName("*");
for(i=0; i<allTags.length; i++) {
if (allTags[i].className.indexOf("textbox") > -1) {
allTags[i].onFocus = fieldSelect;
allTags[i].onBlur = fieldDeSelect;
}
}
}
function fieldSelect() {
this.style.backgroundImage = "url('inputBackSelected.png')";
}
function fieldDeSelect() {
this.style.backgroundImage = "url('inputBack.png')";
}
I am a beginner at JavaScript so I am not used to debugging code yet.
Thanks
Luke
Your problem lies in attaching your event handlers. You should bind to onfocus and onblur (note the lowercase event name).
As a suggestion, you may want to look at a very simple cross browser addEvent() with a quick line of code added to ensure the proper this pointer:
function addEvent(obj, evType, fn, useCapture){
if (obj.addEventListener){
obj.addEventListener(evType, fn, useCapture);
return true;
} else if (obj.attachEvent){
// fix added by me to handle the `this` issue
var r = obj.attachEvent("on"+evType, function(){
retrun fn.apply(obj, arguments);
});
return r;
} else {
alert("Handler could not be attached");
}
}
And then use the addEvent function instead of allTags[i].onfocus = you will probably have better mileage in the future binding events.
addEvent(allTags[i], 'focus', fieldSelect);
addEvent(allTags[i], 'blur', fieldDeSelect);
jsfiddle demonstration
The problem is that when fieldSelect and fieldDeselect are getting called, this refers to the window object, not to the element that fired the event. You might want to consider using jQuery:
$(document).ready(function() {
$('.textbox').focus(fieldSelect).blur(fieldDeselect);
});
function fieldSelect() {
$(this).css('background-image', 'url("inputBackSelected.png")');
}
function fieldDeselect() {
$(this).css('background-image', 'url("inputBack.png")');
}
jQuery takes care of making sure that when your event handlers are getting called, this refers to the element that fired the event.
Two things, the events should be all lower case (onfocus, onblur) and this doesn't point to the object that triggered the event in IE. Try this:
function fieldSelect(e) {
var event;
if(!e) {
event = window.event;
} else {
event = e;
}
event.target.style.backgroundImage = "url('inputBackSelected.png')";
}
function fieldDeSelect(e) {
var event;
if(!e) {
event = window.event;
} else {
event = e;
}
event.target.style.backgroundImage = "url('inputBack.png')";
}
Standards complient browsers will pass an event object to the event handler. IE uses a global window.event object instead. Either way you can use that object to get the target of the event that triggered the handler.
Another, probably preferable option would be to have your functions set and remove a className instead of directly changing the style. Then put a style called maybe selected in your stylesheet that overrides the background image. That way you keep style info and behavior separate.
Instead of window.onload=initform try window.onload=function(){/the init function/}
Also when refering to a function you should use () even if there are no arguments.