Click links with JavaScript

If you want to click on objects, anchors, table cells or any other html element to emulate the javascript behaviour…

November 18, 2009

If you want to click on objects, anchors, table cells or any other html element to emulate the javascript behaviour you can prototype the click function on the HTMLElement object. In the new method we fire the click event on the object. The click event is fired in two different ways (one for IE browser and one for Mozzilla-like browser).

I’ve used this code on a page that use a lightbox/shadowbox gallery. When the page is loaded I fire the click event on the first link of the lightbox gallery.

Watch a demo here.


HTMLElement.prototype.click = function() {
	if (document.createEvent) {
		var evt = this.ownerDocument.createEvent('MouseEvents');
		evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
		this.dispatchEvent(evt);
	} else if (this.fireEvent) {
		this.fireEvent("onclick");
	}
}

// usage
// <a href="http://www.barattalo.it" id="linktoclick">auto click</a>
document.getElementById("linktoclick").click();

Author

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Recommended

How to capture enter key pressed in a form (JavaScript)

Suppose you have a login form and you want to send the form when user press enter on his keyboard…

February 16, 2010

Set “write here” on input type text?

If you are using JQuery framework and you want to set up the default value of some text box in…

November 17, 2009

How do I get the value from a combo in Javascript?

If you don’t use any javascript framework such as jquery.js or prototype.js the combo object isn’t so easy to use,…

November 13, 2009

Add Internet Explorer class to body to detect old browser

When you have clients that still uses an old browser, you need to handle it. This javascript function detects the…

February 27, 2017

Modify list counter in :before pseudo class with jQuery using start attribute

Suppose you have two ordered list ol tags, and the second one has a start attribute. You also have in…

April 20, 2016

Refresh a Google Adsense banner with Javascript

Often bloggers and site owners use galleries to have a greater number of pages, adding pages means adding clicks. Each…

November 9, 2013