3

I need to now how to fire a mouse click event on a button automatically. I have this but doesn't work :(

window.setInterval(function() { simulateClick(); }, 2000);

function simulateClick() {
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", false, false, window, 0, 684, 571, 684, 508, false, false, false, false, 0, null);
        var a;
    a.dispatchEvent(evt);
}

Thanks in advance

Oscar

locrizak
  • 12,192
  • 12
  • 60
  • 80
Oscar
  • 31
  • 1
  • 1
  • 2
  • My guess is that you're not initiating a. IT just says "var a;" but you never specify which element it is. Other than that I think it looks fine. – Mamsaac May 06 '11 at 20:56
  • If you want to simulate for testing purposes you can use selenium http://seleniumhq.org/ – ariel May 06 '11 at 21:12
  • Looks like you're trying to do this: http://stackoverflow.com/questions/6157929/how-to-simulate-mouse-click-using-javascript/6158050 – Nate Jan 07 '14 at 19:55

2 Answers2

2

If all you want to do is click a button, button elements have a click method that can be invoked:

<input type="button" id="theButton" onclick="javascript:alert('The button was clicked!');" value="A button" />

<script language="javascript">

setTimeout(function(){
    document.getElementById("theButton").click();
}, 1000); // wait one second then click the button

</script>

There's no need to "actually" simulate the mouse click at a specific x,y position.

Oliver Moran
  • 5,137
  • 4
  • 31
  • 45
  • 2
    There's IS need. thinking a input text with cursor position changing. – Jiang YD Sep 30 '16 at 09:50
  • @JiangYD that's a different. question. You can set the position of a cursor in a text box like this: http://stackoverflow.com/questions/512528/set-cursor-position-in-html-textbox – Oliver Moran Dec 20 '16 at 12:28
1

I dont know if its posible to do that on javascript but if you need automatic and periodic clicks maybe you can do that with external tools like autohotkey

Dave
  • 532
  • 5
  • 8
  • mmmmm ,aybe..... is it possible to move the pointer mouse automatically to certain position on the web page? – Oscar May 09 '11 at 03:00
  • with autohotkey you can send a click on the specific coordinates see this [page](http://www.autohotkey.com/docs/commands/Click.htm) – Dave May 09 '11 at 15:55