2

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.

Community
  • 1
  • 1
brilliant
  • 2,805
  • 11
  • 39
  • 57

3 Answers3

3

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

Mulan
  • 129,518
  • 31
  • 228
  • 259
  • I see. Thank you for your answer and for the references. – brilliant Jul 13 '14 at 17:58
  • @brilliant, the answer you have selected is a very antiquated way of doing javascript; it doesn't keep the javascript separate from the HTML. I added a section to my fiddle that shows an automatically updating timer that stops when a button is pushed. I hope that helps. – Mulan Jul 13 '14 at 18:00
  • "a very antiquated way of doing javascript; it doesn't keep the javascript separate from the HTML" - Ah, I see. I just tried your code completely out of the HTML "field" (that is, the opening – brilliant Jul 13 '14 at 18:19
  • 1
    @brilliant, correct. You can have scripts anywhere in your HTML, but that's another topic entirely. A pretty safe way is to load most of them just before the closing `

    ` tag. This ensures the DOM elements are loaded before the scripts attempt to reference them. Other methods include loading them in the `

    ` but using some sort of `DOMContentLoaded` listener to make sure they don't run before the rest of the DOM is loaded.

    – Mulan Jul 13 '14 at 18:21
1

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 :)

Narxx
  • 7,929
  • 5
  • 26
  • 34
  • Thank you! It works. Now, how can I simulate it in such a way so that I get the same result as when you click on the button with your computer mouse? – brilliant Jul 13 '14 at 15:55
  • What do you mean? This works as if you have clicked it with a mouse. It fires the same event (if I'm not mistaken). What is it *EXACTLY* you're trying to do? – Narxx Jul 13 '14 at 16:24
  • Sorry. I thought you were just pulling my leg. However, when I try your way - that is, when I run an HTML file on my computer with the code suggested by you (please, refer to the EDIT1 section in my question to see it) - it doesn't work. The button's inner text doesn't change into a date info. – brilliant Jul 13 '14 at 16:45
  • Because you load the script BEFORE the DOM element is loaded. In my code, I first create the DOM element, and then call the JS. Either use a `script` tag after the ` – Narxx Jul 14 '14 at 09:09
  • Yes, **naomik** and **prash** already explained that to me last night. Thank you for your time, and I am really sorry for my rude response yesterday to your answer. – brilliant Jul 14 '14 at 09:34
  • You are very welcome, and don't worry about the response. I'm glad it works for you. Cheers :) – Narxx Jul 14 '14 at 10:12
1

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.

spiderman
  • 10,892
  • 12
  • 50
  • 84