Your browser does not support JavaScript!
Upvotes Anonymous 1 User 0

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:
When I click the button, I see an alert window:
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.
Was this helpful?

Tags

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License