Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate a click in javascript?

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?

like image 606
TIMEX Avatar asked Jan 17 '26 06:01

TIMEX


2 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>
like image 185
Qwerty Jones Avatar answered Jan 19 '26 19:01

Qwerty Jones


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

like image 36
Jacob Mattison Avatar answered Jan 19 '26 19:01

Jacob Mattison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!