Click on a button on a web page automatically

Asked

Viewed 3,786 times

1

Like a button click on a web page automatically via Javascript?

  • there would be no way to take the logic of clicking the button to a function and simply calling it?

  • I don’t understand the context you’re in... using a webbrowser ? you’re making the page ?

  • I have a program that opens a certain web page by itself according to the time of day. i want when opening the page to automatically activate the page button.

  • What program would that be? What this click will do?

3 answers

3


To simulate a click just use the method click(), to get support most browsers use the function below.

function click(id)
{
    var element = document.getElementById(id);
    if(element.click)
        element.click();
    else if(document.createEvent)
    {
        var eventObj = document.createEvent('MouseEvents');
        eventObj.initEvent('click',true,true);
        element.dispatchEvent(eventObj);
    }
}

click('el');
<button id="el" onclick="alert('teste')">
teste
</button>

  • Duate, The web page will open itself and have to press a button alone as well. in case it is catching the onclick event

  • Unfortunately I could not understand what you want, this page is generated automatically? is an iframe? is a load?

0

If you want a more Enerica function, to triggar various event types:

function trigger (element, eventName) {
  var event,
      eventClass;

  switch (eventName) {
    case 'click': // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
    case 'mousedown':
    case 'mouseup':
      eventClass = 'MouseEvents';
      break;

    case 'focus':
    case 'change':
    case 'blur':
    case 'select':
    case 'submit':
      eventClass = 'HTMLEvents';
      break;

    default:
      throw 'fireEvent: Couldn\'t find an event class for event "' + eventName + '".';
    break;
  }

  event = document.createEvent(eventClass);
  event.initEvent(eventName, true, true);
  event.eventName = eventName;
  element.dispatchEvent(event);
}

Let’s test. I put an Alert() in the body click event

document.body.addEventListener('click', function(){ alert('clicou'); });

Let’s fire the event:

trigger(document.body, 'click');

-1

Wouldn’t it be more practical to do something like:

window.onload = Function() { Document.getElementById("id_do_button"). click(); };

Browser other questions tagged

You are not signed in. Login or sign up in order to post.