Functions and Buttons

W3schools onclick event attribute example


You can make <button> elements trigger JavaScript functions.

This example has two functions that change a <p> element:

<p id="text">Boring Text</p>

<script>
myText = document.getElementById("text");

function red(){
	myText.innerHTML = "Red is best!";
	myText.style.color = "red";
}

function blue(){
	myText.innerHTML = "Blue rocks!";
	myText.style.color = "blue";
}

</script>

So far they aren’t connected to a button, but you can test the functions using your console in the browser’s developer tools.

In Chrome or Firefox, you can hit F12 to bring up the developer tools. (You might also need to click the “Console” tab.)

Now just call the function from the console and see what happens:

When you hit enter, it should update the text:

Now we create two <button> elements:

<button>Red</button>
<button>Blue</button>

So far the buttons don’t do anything. To fix that, we need to give each button an onclick event attribute:

<button onclick="red()">Red</button>
<button onclick="blue()">Blue</button>

This assigns a function to be called whenever the button is clicked.