简体   繁体   中英

Clicking a button in JavaScript

As far as I can tell from my very limited knowledge about JavaScript, it can get all kinds of info about some elements on the page, for example, about a button. JavaScript can get the name of a button, its type, name, and the text in it. It can even disable a button. But can it simulate a click on a button? Or it can and must only be done by a user?

EDIT 1 (my response to the answer below written by Narxx ):

This way doesn't seem to work:

<html>
<head>
<script type="text/javascript">
document.getElementById('my-button').click();
</script>
</head>
<body>
<button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>

EDIT 2 (my response to the comment below written by prash )

This way doesn't work either (the simulate function is written by kangas , modified by TweeZz , and is taken by me from here ):

<html>
<head>
<script type="text/javascript">
function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent)
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}
simulate(document.getElementById("btn"), "click");
</script>
</head>
<body>
<button id="btn" onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html> 

EDIT 3: (my response to the answer below written by Jonco98 ):

( This code is also the answer to my question )

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ClickButton()
{
document.getElementById('my-button').click();
}
</script>
</head>
<body onload="ClickButton()">
<button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>

EDIT 4:

Please note that the answer below given by naomik also solves my problem perfectly well.

I would recommend doing this unobtrusively .

<button id="my-button">The Time is?</button>

<script type="text/javascript">
  var b = document.getElementById("my-button");

  function displayTime(elem) {
    elem.innerHTML = Date();
  }

  b.addEventListener("click", function(event) {
    displayTime(this);
  });

  // fake the click
  b.dispatchEvent(new Event("click"));
</script>

jsfiddle demo

The button loads and is "clicked" with the simulated event immediately. Subsequent clicks will result in the button time being updated.


Here's another example:

The time will stop updating after you click submit

<form id="my-form">
  <input name="time" />
  <input type="submit" />
</form>

<script type="text/javascript">
  var f = document.getElementById("my-form");

  function updateTime() {
    f.time.value = Date();
  }

  var interval = setInterval(updateTime, 1000);

  f.addEventListener("submit", function(event) {
    clearInterval(interval);  
    alert("the submitted time is: " + f.time.value);
    event.preventDefault();
  });

  // prepopulate form
  updateTime();
</script>

References

Yes, you can simulate a click on a button using JavaScript:
HTML:

<button id="my-button">Click me</button>

JS:

document.getElementById('my-button').click();

That's it... you have just triggered a click event on a button without actually clicking it :)

Well, this is not meant as the alternate answer. The answer is already there as suggested by @naomik, and I agree with that.

Let me point out the issue what the OP faced and is unclear why his actual code didn't work though.

Actual code:

<html>
   <head>
      <script type="text/javascript">
         document.getElementById('my-button').click();
      </script>
   </head>
   <body>
      <button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
   </body>
</html>

Simple reason why this didn't trigger the event is because , The <button> was not painted at that time, and you would have got this error in your console Cannot read property 'click' of null

In the first example that @naomik has shared, this seems to work though. Reason being the place where the <script> is executed. It is not in the <head> , Its inside the <body> , and the <button> is painted first before the script execution.

This is good,

<html>
   <head></head>
   <body>
      <button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
      <script type="text/javascript">
         document.getElementById('my-button').click();
      </script>
   </body>
</html>

Apart from this, it is advisable to do this via dispatchEvent() and addEventListener() to simulate and listen to the event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM