How do I simulate a click on a button on a web page automatically via JavaScript?
How do I simulate a click on a button on a web page automatically via JavaScript?
To simulate a click simply use the click()
method, to get support most browsers use the function below.
function click(id)
{
var element = document.getElementById(id);
if(element.click)
element.click();
else if(document.createEvent)
{
var eventObj = document.createEvent('MouseEvents');
eventObj.initEvent('click',true,true);
element.dispatchEvent(eventObj);
}
}
click('el');
<button id="el" onclick="alert('teste')">
teste
</button>
If you want a more generic function, to trigger several types of events:
function trigger (element, eventName) {
var event,
eventClass;
switch (eventName) {
case 'click': // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case 'mousedown':
case 'mouseup':
eventClass = 'MouseEvents';
break;
case 'focus':
case 'change':
case 'blur':
case 'select':
case 'submit':
eventClass = 'HTMLEvents';
break;
default:
throw 'fireEvent: Couldn\'t find an event class for event "' + eventName + '".';
break;
}
event = document.createEvent(eventClass);
event.initEvent(eventName, true, true);
event.eventName = eventName;
element.dispatchEvent(event);
}
Let's test. I put an alert () in the body click event
document.body.addEventListener('click', function(){ alert('clicou'); });
Let's fire the event:
trigger(document.body, 'click');