Nov 18 2009

Click links with JavaScript

Category: JavascriptGiulio Pons @ 12:18 pm

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

Tags: , , , ,


Nov 13 2009

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

Category: JavascriptGiulio Pons @ 12:52 pm

If you don’t use any javascript framework such as jquery.js or prototype.js the combo object isn’t so easy to use, because when you try to get the selected value or the selected option string you can’t do it simply with obj.value as you do for a input type text box.
You can add this two function to the object:

HTMLSelectElement.prototype.getValue = function () {
	return this.options[ this.options.selectedIndex ].value ;
}
HTMLSelectElement.prototype.getText = function () {
	return this.options[ this.options.selectedIndex ].innerHTML ;
}

So you can reach the value and the option string simply this way:

var SelectedValue = document.form.comboname.getValue();
var SelectedOptionString = document.form.comboname.getText();
Share

Tags: ,