Search code examples
javascriptoperaopera-extension

Using element.click() to simulate a Button Click in Javascript


I'm trying to write an extension for Opera that automatically sends specific chat messages. (Commands, to be exact.) For that, I want to enter the message into the textarea, simulate a button click to send the message and read the reply I get.

I've been trying to use the Element.click() function of JavaScript to simulate the click, but it doesn't work. My code goes something like this:

document.getElementsByClassName("text-area")[0].value = "test";
document.getElementsByClassName("send-chat-button")[0].click();

The textarea gets filled in with the value I want, but it doesn't click the button. I am also not getting any output on the console. I'd be glad about any help I can get.

Regards, Kileraptor1

UPDATE: You were right, the button does not have an OnClick event like I thought it had. I'm honestly not sure how it submits a message. Since I am writing a plugin for a website I do not own, I can not edit the source or anything.


Solution

  • The easiest way would be with the trigger() function in jQuery:

    $(".send-chat-button:first").click(function()
    {
        // Whatever actions you want to perform on click
    });
    
    $(".send-chat-button:first").trigger("click"); // Executes the click event handler
    

    trigger(event) will execute whatever specified events that are attached to an element at any point in the code.

    If you want to use pure JavaScript, there's already a good answer here. As I said though, jQuery makes this extremely simple.