One of the features is that when a user clicks on something, something happens. How do I simulate this click without just calling the function?
-
1What exactly is the purprose you want to achieve? – Jani Hartikainen Nov 19 '09 at 19:49
-
Yes, is it that you want to navigate to the url in the `href` of the link? – Crescent Fresh Nov 19 '09 at 19:55
3 Answers
Simulating a click on an element is easily done with an element.click()
;
There is no need to install a 9000 line jquery library just to simulate a click. If you know the ID of an element, clicking it would be as simple as this:
document.getElementById('someID').click();
Getting an element you want to click is harder if there is no id attribute, but luckily there is Xpath, so getting and clicking an element can still be done in a single line of elegant code. Note that contains method needs only a partial match of the src attribute.
document.evaluate(" //a[ contains(@src, 'someURL') ] ", document.body, null, 9, null). singleNodeValue.click();
or and and operators can be used, like this:
document.evaluate(" //*[ contains(@id, 'someID') or contains(@name, 'someName') ] ", document, null, 9, null). singleNodeValue.click();
A complete multi-browser example could look something like that. In IE8 and below if the element you are after has no id, you can get it with document.getElementsByTagName('tagname'); and then use a for loop to evaluate some attribute of the element or its innerHTML.
<html>
<body>
<input type='button' id='someID' value='click it' onclick='myAlert()' />
<p onclick="simulateClick()" >Click the text to simulate clicking the button above - the button will be automatically clicked in 3.5 seconds
<script>
function simulateClick(){
var button;
try{ // Xpath for most browsers
button = document.evaluate(".//input[ contains(@id, 'someID') ] ", document.body, null, 9, null). singleNodeValue;
}catch(err){ // DOM method for IE8 and below
button = document.getElementById("someID");
}
if ( button) { button.click(); }
else { alert("No button was found, so I can't click it"); }
}
function myAlert(){alert("button clicked")}
setTimeout(simulateClick, 3500 );
</script>
</body>
</html>

- 35,521
- 22
- 122
- 171

- 81
- 1
- 2
Using jQuery, you can do $("#myElementId").click()
to simulate a click.

- 50,258
- 9
- 107
- 126
In case anyone bumps into this looking for a framework agnostic way to fire any HTML and Mouse event, have a look here: How to simulate a mouse click using JavaScript?