Is it possible to execute DOM events manually? For example, if you have a link and want to call the default event function of it through code:
<a href="one.html" id="a">main page<\a>
document.getElementById("a").onclick();
Is it possible to execute DOM events manually? For example, if you have a link and want to call the default event function of it through code:
<a href="one.html" id="a">main page<\a>
document.getElementById("a").onclick();
Check out initMouseEvent
Intializes the value of a mouse event once it's been created (normally using document.createEvent method.
var event = document.createEvent("MouseEvents"),
anchor = document.querySelector('a');
event.initMouseEvent("click", true,
true, window, 0,
0, 0, 0, 0, false,
false, false, false,0, null);
anchor.dispatchEvent(event);
You can do this following Way
document.getElementById("a").onclick=function(){f1()};
function f1()
{
document.getElementById("demo").innerHTML=3;
}
Use trigger events like below
var triggerEvent = function (element, name, data) {
var event;
if (window.CustomEvent) {
event = new CustomEvent(name, {
detail: data || {},
bubbles: true,
cancelable: true
});
} else {
event = document.createEvent("Event");
event.initEvent(name, true, true);
event.detail = data;
}
element.dispatchEvent(event);
};
You will use it like
triggerEvent(input, 'change', {changedText : "Custom data here in this Object"}
You may get below error based on configuration
Refused to display 'https://www.some.com/?gfe_rd=cr&ei=50JbU_yHKdGQiAec9IH4Bg' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
jQuery will do what you want here quite nicely:
$("#a").click();
This will automatically call the href and the dom event attached to the matched element.