Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate a mouse-click in Javascript [duplicate]

Tags:

javascript

Looking for a Javascript that do a left-mouse click on a image/button identified by ID or CLASS name, wait x seconds and repeat. And able to run in developer tools Console tap, in chrome and firefox.

Tried to write it myself, cause i figured it would be a simple code, but after 2 hours of trial and error with no luck, i am starting to run out of options.

Hopefully a Javascript pro out there got time to help out a very novice user ;)

Thanks

like image 804
zyl1647 Avatar asked Dec 16 '13 01:12

zyl1647


People also ask

How do you simulate a click in Javascript?

Method 1: Using the click() method: The click() method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.

How do I simulate a mouse click on my website?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

How do I make MouseEvent?

Common events using this interface include click , dblclick , mouseup , mousedown . MouseEvent derives from UIEvent , which in turn derives from Event . Though the MouseEvent. initMouseEvent() method is kept for backward compatibility, creating of a MouseEvent object should be done using the MouseEvent() constructor.


3 Answers

What's wrong with

document.getElementById(id).click()
like image 123
Diego Carrion Avatar answered Oct 02 '22 15:10

Diego Carrion


If you're willing to use jQuery, you can use this simple function to do it:

window.setInterval(function(){
    $("#divToClick").trigger("click");
}, 1000);

That will call it every 1000 milliseconds, or 1 second

For a pure Javascript solution, you should take a look at How to trigger event in Javascript

or, if you're not interested in supporting IE, you can do it the simple way, with an Event() constructor, and event.dispatch()

like image 21
scrblnrd3 Avatar answered Oct 02 '22 13:10

scrblnrd3


You'd use the event constructor and dispatchEvent for that :

var support = true; // check if event constructor is supported

try {
    if (new MouseEvent('click', {bubbles: false}).bubbles !== false) {
        support = false;
    } else if (new MouseEvent('click', {bubbles: true}).bubbles !== true) {
        support = false;
    }
} catch (e) {
    support = false;
}

setInterval(function() {
    if (support) {
        var event = new MouseEvent('click');
    }else{
        var event = document.createEvent('Event');
        event.initEvent('click', true, true);
    }
    elem.dispatchEvent(event);
},1000);

FIDDLE

like image 43
adeneo Avatar answered Oct 02 '22 15:10

adeneo