21

How would you trigger a click event from an element that supposedly does not have native clickable behaviours?

For example, I know that you could simply just use the following:

document.getElementById('x').click();

But what happens if 'x' is a 'DIV'? I have an implementation, and it doesn't seem to trigger... I get the error (chrome 12):

Uncaught TypeError: Object #<HTMLDivElement> has no method 'click'

Ideas?

Quick Edit - I'm looking for vanilla JS here... I like reinventing the wheel in my image... :-)

Abhishek
  • 4,190
  • 11
  • 39
  • 52

7 Answers7

33

For classic clickable elements like buttons or links, click() should work in all browsers. However for other elements like divs, you need onclick() in some browsers and click() in others.

I would strongly recommend that instead of trying to figure this out for yourself, you use a javascript library such as MooTools, jQuery, Prototype, YUI, or many others. The reason is that getting this stuff right cross-browser is hard. Why waste your time when others have worked and worked to get it right and make it super simple to use? I guarantee that if you spend your time learning how to use a framework you will get farther in your javascript development skill faster. Later you can come back and see how it's all done in the nitty gritty if you want to.

That said, here's script that will work cross-browser, and will do nothing if neither of these properties have a function assigned:

el = document.getElementById('id');
if (el.onclick) {
   el.onclick();
} else if (el.click) {
   el.click();
}

You could also do this, but perhaps this is a little less clear:

(el.onclick || el.click || function() {})();

Some empirical tests firing the click event on a div:

  • Firefox 3 and 4 use onclick.
  • IE7, 8 use both.
  • Chrome uses onclick (as checked in v. 12.0.742.100).
  • Safari on iPhone 4 with iOs 4.2.1 uses onclick.

Test script:

var d = document.createElement('div'); d.style.position = 'absolute'; d.style.top = '0'; d.style.left = '0'; d.style.width = '200px'; d.style.height = '200px'; d.style.backgroundColor = '#fff'; d.style.border = '1px solid black'; d.onclick = function() {alert('hello');}; document.body.appendChild(d);

Run this in developer tools in your browser, or javascript: in front and void(0); at the end then paste into the address bar and hit Enter. Then try d.click() and d.onclick(). You can click the div itself to prove it works with real clicks too.

ErikE
  • 48,881
  • 23
  • 151
  • 196
  • just found the same @ http://stackoverflow.com/questions/5701093/how-do-i-emulate-a-click-on-a-div-then-fire-the-onclick-event-in-webview-programa/5702740#5702740 – roberkules Jun 16 '11 at 05:14
  • @Roberkules - Whoops... I guess that makes this a duplicated question then... I did google it, but only found solutions for natively clickable elements... – Abhishek Jun 16 '11 at 06:39
  • You made good points, but heads up, if the target element is clickable by default behaviour (such as a – Abhishek Jun 16 '11 at 06:40
8

Use this if you actually want to trigger an event programmatically:

function eventFire(el, etype){
  if (el.fireEvent) {
   (el.fireEvent('on' + etype));
  } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype, true, false);
    el.dispatchEvent(evObj);
  }
}
//usage
eventFire(document.getElementById('x'),'click');
KooiInc
  • 119,216
  • 31
  • 141
  • 177
5

You will need to feature detect as different browsers (using non-html5 doctype) can support different dom methods:

var ele = document.getElementById('x');
if(typeof ele.click == 'function') {
  ele.click()
} else if(typeof ele.onclick == 'function') {
  ele.onclick()
}
Ben Rowe
  • 28,406
  • 6
  • 55
  • 75
  • I guess it should be made part of JS coding guidelines, "Detect a feature before using it". – Kumar Jun 16 '11 at 05:32
  • @Kumar the problem originates from inconsistent DOM APIs, not the JavaScript language itself. But yes, feature detection is a Good Thing. – Matt Ball Jun 16 '11 at 05:35
  • 1
    Right said Fred err..Matt. Well, I am not blaming JS. I fear JS more than I fear GOD. God may forgive you for your mistakes but badly written JS code may not. – Kumar Jun 16 '11 at 05:36
  • @Kumar [jslint](http://jslint.com) will help fix any badly written JS code! First among them using only two equal signs instead of three, and second among them missing semicolons after statements. – ErikE Jun 16 '11 at 05:39
  • @Ben I don't think it's really necessary to check for a function type, just check if the property exists. If someone stuck a non-function on one of these properties then you have bigger problems. – ErikE Jun 16 '11 at 05:40
  • I use jslint at work, have to use it, when I started using jslint, it hurt me a lot, trying to follow the best practices now :-) – Kumar Jun 16 '11 at 05:41
  • @Erik agreed, I just prefer to be verbose when answering questions for the sake of OP. – Ben Rowe Jun 16 '11 at 06:08
  • 1
    Or just use a library like jQuery that already has 1000s of man-hours invested in making these things cross-browser. It's OK to look at this stuff academically, but don't fool yourself into thinking you are going to be writing jQuery-quality cross-browser code anytime soon in the general case. – Peter Lyons Jun 16 '11 at 16:01
1

You can attach an onclick method to anything, but if you don't have any events attached to the actual element itself, it will error out, or simply do nothing.

var el = document.getElementById('x');
el.onclick = function() { //do something };
el.click();
Jordan
  • 31,971
  • 6
  • 56
  • 67
1

Vanilla JS (without jQuery)

/**
 * Simulate a click event.
 * @public
 * @param {Element} elem  the element to simulate a click on
 */
var simulateClick = function (elem) {
    // Create our event (with options)
    var evt = new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window
    });
    // If cancelled, don't dispatch our event
    var canceled = !elem.dispatchEvent(evt);
};

To use it, call the function, passing in the element you want to simulate the click on.

var someLink = document.querySelector('a');
simulateClick(someLink);

https://gomakethings.com/how-to-simulate-a-click-event-with-javascript/

DevWL
  • 17,345
  • 6
  • 90
  • 86
0

I've had a similar issue while trying to use the .click method on stock android browsers. Seems like substituting .click with $('selector').on('click', cb); solves the issue.

ronalddddd
  • 111
  • 2
  • 8
0

Try doing something like the following:

var my_div = document.getElementById('x');
my_div.onclick = function() {
   alert('hello world');
}
Aaron Hathaway
  • 4,280
  • 2
  • 19
  • 17
  • Help me clear this, but what this is doing is essentially giving the div an onclick event... That's not what I'm looking for, as I already have a event setup, but I need to trigger it through some other user interaction... Like, on page load, this button should execute its trigger, hence running whatever animation it had in store... – Abhishek Jun 16 '11 at 06:42