17

How to programmatically click on a non-button element using javascript? Or is it atleast possible in browsers like Firefox and Chrome?

0

5 Answers 5

17

Believe it or not, for a fairly basic click, you can just call click on it (but more below): Live Example | Live Source

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Artificial Click</title>
</head>
<body>
  <div id="foo">xxxxxxx</div>
  <script>
    (function() {
      var foo = document.getElementById("foo");
      foo.addEventListener("click", function() {
        display("Clicked");
      }, false);
      setTimeout(function() {
        display("Artificial click:");
        foo.click(); // <==================== The artificial click
      }, 500);
      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>

You can also create the relevant type of Event object and use dispatchEvent to send it to the element:

var e = new MouseEvent("click", {
  view: window,
  bubbles: true,
  cancelable: true
});
foo.dispatchEvent(e);

This gives you the opportunity to do things like set other information (the typical pageX and pageY, for instance) on the event you're simulating.

More about the various event object types in Section 5 of the DOM Events spec.

Sign up to request clarification or add additional context in comments.

2 Comments

What about other built-in event types?
@Givi: See Section 5 of the DOM Events spec.
9

You can use HTMLElementObject.click()

Something like document.getElementById('div1').click()

See more

Comments

5

Or in jQuery (documentation) to click on a non-button element

$( "#nonButton" ).click();

or to listen for a click on that non-button element

$("#nonButton").on("click", doSomething);

1 Comment

jQuery-only answers to non-jQuery questions are not useful.
1
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
document.getElementById("nonButton").dispatchEvent(evt);

see: https://developer.mozilla.org/en-US/docs/Web/API/event.initMouseEvent

Comments

1
document.querySelectorAll('#front-chat-container div[role]')[0].click()

worked for me - to click a div element.

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.