How to Wire up a Button in JavaScript

Here's an example of handling what happens when a user clicks a button:

<!DOCTYPE html>
  <title>My Page</title>

<button id="mybutton">Submit</button>


function MyButtonClick() {
    alert("You clicked the button!");

var button = document.getElementById("mybutton");
button.onclick = MyButtonClick;



Here's what the page looks like in Firefox:

a web page with a submit button on it

When I click the button, I see an alert window:

a web page with an alert dialog showing

Let's look at each part of the JavaScript. This part:

function MyButtonClick() {
    alert("You clicked the button!");

is a function. Functions are used to organize your code into separate pieces. We've created a function named MyButtonClick and used it to alert the user when they click the button.

This line:

var button = document.getElementById("mybutton");

searches our HTML document for an element that has an id attribute with mybutton as the attribute's value, and if that exists, we'll store that object in a variable. Our document has a button element that satisfies this criteria:

<button id="mybutton">Submit</button>

Now that we can refer to the HTML button in our JavaScript code, we set the onclick attribute to point to our MyButtonClick function, and we can change our function to do whatever we like.


Leave a comment

What color are green eyes? (spam prevention)
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.