How to run a function with a button click in JavaScript
JavaScript, Web Design
In JavaScript, there are times when you need a block of code to just sit back, relax, and not run right when the page loads. This is where JavaScript functions come in. A function is a block of code that runs when we tell it to. In this example, we will show how to run a function when a button is clicked. The first thing we’ll want to do is create the button and give it an id using HTML:
<button id=”clickMe”>Run Function</button>
This will create on the page a button that says “Run Function” and has an id of “clickMe”. That should do it for the HTML. Now we need to write the code that will select the button and wait for it to be clicked:
<script>
var btn = document.getElementById(“clickMe”);
btn.addEventListener(“click”, alertMe);
function alertMe(){
alert(“The button has been clicked!”);
}
</script>
The first line of code here is using getElementById to go out and select the button and store it in the variable btn.
The next line is attaching the event listener to the button, which is stored in btn. The event it’s listening for is a click event so when the button is clicked, it will run a function called “alertMe”
The third line is the actual function itself. We create a function using the “function” keyword followed by the name of the function which is alertMe()
The next line is the code that runs when the function is called. An alert is a pop up window that appears and this one will say “The button has been clicked!”
You can put all kinds of other things inside of the function besides the alert, this is just a very simple example. But hey, at least you know how to fire off some code when a button is clicked now! (: Here is what the code would look like when finished:
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title>Buttons and Functions!</title>
</head>
<body>
<button id=”clickMe”>Run Function</button>
<script>
var btn = document.getElementById(“clickMe”);
btn.addEventListener(“click”, alertMe);function alertMe(){
alert(“The button has been clicked!”);
}
</script>
</body>
</html>
If you want to learn more, be sure to check out our JavaScript Training. Have an amazing day!