1

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();
Charlie
  • 11,380
  • 19
  • 83
  • 138
scripter
  • 132
  • 8

4 Answers4

3

Check out initMouseEvent

Intializes the value of a mouse event once it's been created (normally using document.createEvent method.

Live Demo

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);

Example provided by MDN as well

Loktar
  • 34,764
  • 7
  • 90
  • 104
1

You can do this following Way

document.getElementById("a").onclick=function(){f1()};
function f1()
       {
   document.getElementById("demo").innerHTML=3;
       }
Arunkumar
  • 5,150
  • 4
  • 28
  • 40
0

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'.
redV
  • 684
  • 1
  • 9
  • 26
-1

jQuery will do what you want here quite nicely:

http://api.jquery.com/click/

$("#a").click();

This will automatically call the href and the dom event attached to the matched element.

Pierre Tasci
  • 450
  • 2
  • 8
  • Downvoted because if the user wanted a jQuery solution they would've asked or tagged it so. – Hamish Apr 26 '14 at 05:14
  • I disagree. The question was "is it possible to execute DOM events manually" and I linked to a solution that accomplishes that "through code". I would have downvoted the answer for lack of an example, not the jquery solution – Pierre Tasci Apr 26 '14 at 05:17
  • 3
    The convention here on SO is that you don't provide answers using jQuery (or any other library) if that library is not mentioned specifically in the question. – jfriend00 Apr 26 '14 at 05:19
  • 2
    Feel free to suggest jQuery in the comments, but "use jQuery" answers dilute the value of SO for vanilla javascript questions. – Hamish Apr 26 '14 at 05:26