A document wide handler for multiple events. Also used for a SO answer, see http://stackoverflow.com/questions/2705583/how-to-simulate-a-click-with-javascript
<p>clicking button 1 will fire a click on button 2</p>
<button id="b1">button 1</button>
<button id="b2">button 2</button>
<button id="clear">clear</button>
<p id="result"></p>
CSS
body {margin: 2em; font: 12px/16px normal verdana, arial;}
JavaScript
var d = document;
// add a global handler (on document) here
listen(d,'click',listenerFunction);
function listenerFunction(e) {
clearTimeout(0);
var originator = e.target || e.srcElement;
// if the event doesn't originate from one of the
// designated elements, do nothing
if (!/clear|b1|b2/i.test(originator.id)) {return true;}
log('clicked ','button#'+originator.id);
// now if buttonid is b1, button#b2 will be clicked too
if ( /b1/i.test(originator.id) )
eventFire(d.querySelector('#b2'),'click');
// handle buttton#clear if applicable
if (/clear/i.test(originator.id)) {
log('clear');
}
}
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);
}
}
// helpers
function log() {
log.result = log.result || d.querySelector('#result');
if (/^clear$/i.test(arguments[0])) {
log.result.innerHTML = '*cleared*';
return setTimeout(function () {
log.result.innerHTML = '';
},300);
}
var nwline = d.createElement('div');
nwline.innerHTML = [].slice.call(arguments).join('');
log.result.appendChild(nwline);
}
function listen(el,etype,fn,nobubble,stopdefault){
nobubble = nobubble || false;
stopdefault = stopdefault || false;
var fnwrap = function(e){
e = e || event;
if (nobubble) {
noBubbles(e);
}
if (stopdefault){
noDefault(e);
}
return fn.apply(el,Array.prototype.slice.call(arguments));
}
;
if (el.attachEvent) {
el.attachEvent('on' + etype, fnwrap);
} else {
el.addEventListener(etype, fnwrap,...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.