How to Wire up a Button in JavaScript

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

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

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

<script>

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

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

</script>

</body>
</html>

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.

Comments

Leave a comment

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