Button click animations
Part of the JavaScript in Action section of Coddy's HTML journey — lesson 20 of 27.
Sometimes we want buttons to give instant feedback when clicked — like shrinking, glowing, or bouncing. We can trigger CSS animations or transitions using JavaScript.
First, create a simple button in your HTML:
<button id="animatedButton">Click Me</button>Then, add some basic CSS to style the button:
#animatedButton {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: transform 0.2s, background-color 0.2s;
}Now, add JavaScript to create the click animation:
const button = document.getElementById('animatedButton');
button.addEventListener('click', function() {
// Add a class for the click effect
button.classList.add('button-clicked');
// Remove the class after animation completes
setTimeout(function() {
button.classList.remove('button-clicked');
}, 200);
});Finally, add the CSS for the animation effect:
.button-clicked {
transform: scale(0.95);
background-color: #45a049;
}When clicked, the button will now slightly shrink and change color, providing visual feedback to the user.
Challenge
EasyWhen the button is clicked, add the CSS class "button-clicked" to it for visual feedback.
Add the line that applies this class inside the click event listener.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Button Animation Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Interactive Button Demo</h1>
<p>Click the button below to see a smooth animation effect.</p>
</header>
<main class="content">
<button id="animatedButton" class="btn">Click Me</button>
</main>
<script src="script.js"></script>
</body>
</html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.