Learn how JavaScript functions work and how to implement them in your web development projects. This tutorial guides you through defining and calling functions, utilizing event listeners, and making your functions flexible with parameters and arguments.
Key Insights
- Functions are a group of reusable codes that perform a specific task, and they are defined by the user, which means the user decides what they do.
- You can define a function using a 'script' tag and a function's name should typically include a verb because functions are meant to perform actions.
- JavaScript functions only get executed when they're called, which can be done by using the function's name followed by parentheses.
- In order to make a function reusable, you can give it parameters. When you call the function, you can then pass information into it, which is known as passing arguments.
- You can use an 'onclick' attribute in HTML to make an element listen for a click event and execute a JavaScript function when the event occurs.
- You can also define event handlers in JavaScript for a more organized and easier-to-edit code. This is done using the 'addEventListener()' method.
Dive into the world of JavaScript and learn how to utilize functions, parameters, event listeners, and more through this comprehensive tutorial that includes practical exercises.
This exercise is excerpted from Noble Desktop’s JavaScript for Front-End training materials and is compatible with JavaScript updates through 2023. To learn current skills in JavaScript with hands-on training, check out our Front-End Web Development Certificate, Full-Stack Web Development Certificate, and coding classes in-person and live online.
Topics Covered in This JavaScript Tutorial:
Defining & Calling Functions, Defining Parameters & Passing Arguments, Using an Event Listener
Exercise Preview
Exercise Overview
In this exercise, you’ll learn how to use functions. A function is a group of reusable code that performs a specific task (or tasks) at a desired time. The function can be run repetitively, potentially using different information each time it runs. Methods such as alert() are similar to functions, but they’re predefined. We can do multiple alerts with varying text, but it’s essentially doing the same task again. Functions, however, are defined by you, so you decide what they do.
Defining Functions
- For the first part of this exercise we’ll be working with the Functions folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
- In your code editor, open index.html from the Functions folder.
-
Add the following bold code before the closing
</head>
tag:<title>Functions</title> <script></script> </head>
-
In the script tag, add the following bold code to define a function:
<script> function displayName() {} </script>
-
In the function’s curly braces, add the following bold code which is what the function will do when we call it:
function displayName() { alert('Dan Rodney'); }
Let’s break this down. We just declared a function named displayName(). It’s good to include a verb in the name, because functions do things.
The function will run the code in the curly braces { }, which is to alert() the name Dan Rodney. Keep in mind that JavaScript is case-sensitive. We used a capital N for our function’s name, displayName(). Later we’ll need to match that case or else things could break.
- Save the file.
- Preview index.html (from the Functions folder) in a web browser.
-
Notice that nothing happens. Code inside functions is only executed when the function is called. Let’s see how to do that.
NOTE: Leave this page open in the browser, so you can reload it to see the changes you make in the code.
Calling Functions
- Switch back to your code editor.
-
Ultimately we’ll want to run this function when the user clicks a button, but for now let’s immediately call the function right after defining it. This means the function will execute immediately on page load.
<script> function displayName() { alert('Dan Rodney'); } displayName(); </script>
-
Save and preview the file in a browser.
Notice the alert is displayed immediately.
- Click OK and return to your code editor.
-
Delete the line of code you just added so you end up with:
<script> function displayName() { alert('Dan Rodney'); } </script>
-
We want to run this function when the user clicks a button. In the body section, type the following text in bold:
<body> <button>Show a Name</button> </body>
-
Now we need the button to “talk” to JavaScript. HTML elements do not listen for events by default. Instead, we need to tell them to listen for events (such as the click of a button). Here we’ll add the onclick attribute and set it equal to the function we want to trigger. Add the following bold code:
<body> <button onclick="displayName();">Show a Name</button> </body>
NOTE: Adding onclick will tell the button to listen for a click event, and only execute the code within the function at that time.
-
Now when the user clicks the button, our displayName() function will run. Let’s check it out. Save the file and preview in a browser.
- Click the Show a Name button. An alert should appear saying Dan Rodney.
- Click OK to close the alert.
- Click the button again to see that the alert appears again. We’re reusing the code!
- Click OK again.
Switch back to your code editor.
Defining Parameters & Passing Arguments
-
An alert that always displays the same thing isn’t very flexible. Let’s make it work with different names. In order to make a function reusable, we give it parameters. Then when we call the function, we can pass information into it. Add these two parameters to your function:
function displayName(firstName, lastName) { alert('Dan Rodney'); }
-
Now edit the alert to use those parameters:
function displayName(firstName, lastName) { alert(firstName + ' ' + lastName); }
-
While a function’s parameters ask for information, the pieces of info we pass to it are called arguments. Below, change the button to pass the arguments
'
Dan'
and'
Rodney'
to the displayName() function.<button onclick="displayName('Dan', 'Rodney');">Show a Name</button>
IMPORTANT! Notice that Dan and Rodney are surrounded by single quotes, not double quotes. JavaScript doesn’t care which are used, but HTML does. For HTML, the double quotes must wrap the onclick attribute’s value. If we used double quotes, HTML would think the onclick attribute would end too early and things would break.
-
Save and preview index.html in a browser.
- Click the Show a Name button. Again, it should alert Dan Rodney, but this time those names were passed into the function.
- Click OK to close the alert.
- Switch back to your code editor.
-
Copy and paste the button to make another.
<button onclick="displayName('Dan', 'Rodney');">Show a Name</button> <button onclick="displayName('Dan', 'Rodney');">Show a Name</button> </body>
-
Alter the second button so it looks as shown below:
<button onclick="displayName('Dan', 'Rodney');">Show a Name</button> <button onclick="displayName('Trevor', 'Smith');">Another Name</button>
-
Save and preview the file in a browser.
- Click each of the buttons. They should give you two different alerts. That is one flexible function!
Product Chooser: Functions & Event Handlers
- In your code editor, close any files you may have open.
- For the rest of this exercise we’ll be working with the Product-Chooser-Function folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
- In your code editor, open product.html from the Product-Chooser-Function folder.
-
Preview product.html in a web browser.
This file is where we left off in a previous exercise for this project. Currently it changes the product photo image and adds a class to one of the buttons (which changes its border color). All this happens on page load, but let’s make it so it happens when we click a button.
-
Back in your code editor, wrap a function around the code that changes the image and adds a class to a button:
<script> let productPhoto = document.getElementById('product-photo'); let colorButton = document.getElementById('red'); function changeColor() { productPhoto.src = 'img/chair-red.jpg'; colorButton.classList.add('selected'); } </script>
-
We want to watch for events involving the colorButton (a variable we’ve already defined). This time we’ll do the event a different way, keeping all our code in JavaScript instead of adding it to the HTML. Add the following code shown in bold:
colorButton.classList.add('selected'); } colorButton.addEventListener(); </script>
NOTE: Unobtrusive JavaScript is an approach that separates JS code from HTML. By defining the event handler in JS instead of HTML, we keep all the JS code together, so it’s easier to find and edit.
-
Inside addEventListener() add the event we want to look for (in this case a click), and the name of the function we want to execute when that event happens (the changeColor function you just defined):
colorButton.addEventListener('click', changeColor);
NOTE: In addEventListener() the function name does NOT have parenthesis after it, because it refers to the function but does not execute it immediately. The event listener will wait until the event is triggered to call the actual function.
- Save and preview the file in a browser.
-
Click the red button to see the image change and the red button get a black border.
We’ll want to reuse this same functionality on all the buttons, not just the red one. To do that we’ll have to work with the group of buttons, which is like a list (called an array in JavaScript) and that will also require looping over all the items in that list (array). So before we finish this project, you’ll have to learn about those concepts (in the following exercises).