CSS transitions
Part of the JavaScript in Action section of Coddy's HTML journey — lesson 18 of 27.
Sometimes we want to create smooth animations (like fading, sliding, or resizing) when an element appears or disappears.
We use CSS transitions for that (covered in CSS mastery section). In JavaScript, we simply add or remove a class—or modify style properties.
HTML:
<button id="toggleBtn">Toggle Box</button>
<div id="box" class="box"></div>The .box has a transition on its opacity, so when the .hidden class is added (which sets opacity to 0), the box fades out instead of disappearing instantly.
.box {
width: 100px;
height: 100px;
background-color: teal;
transition: opacity 0.5s ease; /* for class toggle */
opacity: 1;
}
.hidden {
opacity: 0;
}When the button is clicked - the box fades:
const button = document.getElementById("toggleBtn");
const box = document.getElementById("box");
button.addEventListener("click", function () {
// opacity fades
box.classList.toggle("hidden");
});Challenge
EasyCreate a toggle button that shows/hides a box when clicked.
Steps:
- Create two variables to store:
- The toggle button element
- The fade box element
Usedocument.getElementById()for both
- Add a click event listener to the toggle button
- When the button is clicked, toggle the "hidden" class on the fade box element
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Fade Toggle Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Smooth Fade Example</h1>
<p>Click the button below to toggle the fading box.</p>
<button id="toggleBtn">Toggle Box</button>
<div id="fadeBox" class="box">
<p>This box fades in and out smoothly!</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.