Webkit browsers getting Uncaught TypeError

I got this simple test page linked here that is suppose to automatically “click” a box at load time.

Works in all browsers, except for Chrome and Safari (webkit browsers).

I’m getting the error …

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

Do a “view source” and you will see all the code there as being …


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style>
.box {
	width: 100px;
	height: 100px;
	margin-right: 100px;
	float:left;
	background-color:#0099CC;
}
</style>
</head>

<body onload="doit()">
<div class="box" onclick="alert('box1');">box 1</div>
<div class="box" onclick="alert('box2');">box 2</div>
<div class="box" onclick="alert('box3');">box 3</div>

<script>
function doit() {
	var randbox=Math.floor(Math.random()*3);
	var boxes = document.getElementsByClassName('box');
	boxes[randbox].click();
}
	
	/*
	if(document.getElementsByClassName){
		alert('yes i can get');
	} else {
		alert('no i can not get element by class name');
	}
	*/
	
</script>
</body>
</html>

The message means exactly what it says. The click method is not standard, nor in my view should it be.
In your case you can just call the relevant onclick handler.

Okay, if I were to use JQuery. What JQuery statement would invoke a “click” on a random box every 3 seconds?

You would use setInterval to achieve the timed interval, within which you would use the jQuery .trigger() command to trigger the appropriate event on the element.

What Logic Ali was trying to get you to realize, I think, is that instead of calling the click() method, you can call the onclick() method of the element which allows you to trigger that appropriate handler for that element.