Simulate click without directly calling the function

Asked

Viewed 994 times

1

Using pure javascript, I wanted to click a button and trigger its events, but the important thing is that I don’t want to call the function directly. So far I’ve tried it:

var send = document.getElementsByName("send");
window.addEventListener("keyup", function( e ){
    if(e.which == 13 || e.keyCode == 13){
        send.dispatchEvent(new Event('click'));
    }
});

I’ve searched several articles, but I need the equivalent of jQuery element.click();, but the articles only teach to call the function directly connected to the element.

<button name="send" onclick="alert('foo')">Enviar</button>

Using pure javascript, how do I click on that button without being directly or calling the function that is on onclick

  • 1

    Try to better detail your goal

2 answers

2


Your code seems to be correct, there’s only one thing wrong getElementsByName returns a list of items (equivalent to array), sure would be:

var send = document.getElementsByName("send");
window.addEventListener("keyup", function( e ){
    if(e.which == 13 || e.keyCode == 13){
        send[0].dispatchEvent(new Event('click'));//send[0] pega o primeiro button que achar
    }
});
  • Fantastic. The fact is that I had forgotten that getElementsByName returns an element array, so the need to use the index 0. I was able to correct in two ways by placing send[0] or searching for send with getElementeById. Hug

0

Has the aply

Reply in English

var elem = document.getElementById("linkid");
if (typeof elem.onclick == "function") {
    elem.onclick.apply(elem);
}

Browser other questions tagged

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