JavaScript is a full-fledged programming language — it contains all the classic programming features you may have seen in other programming languages (or at least heard about), such asvariables,loops, andfunctions.
JavaScript, when used on web pages (though it can also be used in other places), generally works by:
- Getting references to one or more values such as numbers or to elements on the page.
- Doing something with those values, such as adding the numbers together.
- Returning a result that can be used to do something else later on. For example, you might want to display the sum of those numbers on the page.
Let's look at an example. We'll use the same basic list we saw in the last couple of articles:
html
<p>Instructions for life:</p><ul> <li>Eat</li> <li>Sleep</li> <li>Repeat</li></ul>
We'll also define a CSS class called.done
that will style any element it's applied to, making it look like a completed task with green text color and a strikethrough. We'll apply it to our<li>
elements using JavaScript in the next step.
css
.done { color: darkseagreen; text-decoration: line-through solid black 2px;}
Now on to the JavaScript. Here, we first store references to the<li>
elements inside a variable calledlistItems
. We then define a function calledtoggleDone()
that adds thedone
class to a list item if it doesn't already have it, and removes the class if it does. Finally, we loop through the list items (usingforEach()
) and add an event listener (usingaddEventListener()
) to each list item so that when it is clicked, thedone
class is toggled, applying the CSS we defined earlier.
js
const listItems = document.querySelectorAll("li");function toggleDone(e) { if (!e.target.className) { e.target.className = "done"; } else { e.target.className = ""; }}listItems.forEach((item) => { item.addEventListener("click", toggleDone);});
Don't worry if you don't understand the above JavaScript now. Getting comfortable with JavaScript is more challenging than getting comfortable with HTML and CSS, but things will become clearer later on in the course.
This example will render as follows in a web browser:
Try clicking the list items a few times and note how the "done" styles are toggled on and off as a result. Not that bad for 11 lines of JavaScript.