3

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?

2
  • 1
    What exactly is the purprose you want to achieve? Commented Nov 19, 2009 at 19:49
  • Yes, is it that you want to navigate to the url in the href of the link? Commented Nov 19, 2009 at 19:55

3 Answers 3

9

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>
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

2

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.