Back
Crafting a Playful Bouncing Rubber Button
Learn to build an engaging, squishy button that bounces like a rubber ball when pressed, bringing tactile motion into the digital realm.
HTML
In our HTML, we keep it simple with a single button element. The button resides within a div to aid in centering it within the viewport.
<div class="button-container">
<button class="rubber-button" onclick="bounce()">Click Me</button>
</div>
JavaScript
The JavaScript snippet adds a bounce animation to the button. When the button is clicked, the bounce function adds a bounce class, which triggers a CSS animation. A setTimeout function is used to remove the bounce class after the animation concludes, allowing the effect to be reapplied upon subsequent clicks.
function bounce() {
const button = document.querySelector('.rubber-button');
button.classList.add('bounce');
setTimeout(() => {
button.classList.remove('bounce');
}, 600);
}
CSS
The CSS is where the magic happens. We start with a container that centers the button on the page using flexbox.
.button-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
The button is styled to look fun and inviting. It has a rounded shape, a vibrant color, and a box shadow to create depth.
.rubber-button {
background-color: #ff6b6b;
border: none;
border-radius: 50px;
color: white;
padding: 15px 30px;
font-size: 16px;
cursor: pointer;
outline: none;
transition: transform 0.3s ease;
box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}
The bounce class uses a keyframes animation to make the button move vertically, mimicking the behavior of a rubber ball bouncing. The sequence of transforms at different keyframes creates this effect.
.bounce {
animation: bounce 0.6s;
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {
transform: translateY(0);
}
40% {
transform: translateY(-30px);
}
60% {
transform: translateY(-15px);
}
}
This CSS-only approach ensures smooth and delightful interaction, adding an extra touch of fun to your web page.Whole code
<div class="button-container">
<button class="rubber-button" onclick="bounce()">Click Me</button>
</div>
<script>
function bounce() {
const button = document.querySelector('.rubber-button');
button.classList.add('bounce');
setTimeout(() => {
button.classList.remove('bounce');
}, 600);
}
</script>
<style>
.button-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.rubber-button {
background-color: #ff6b6b;
border: none;
border-radius: 50px;
color: white;
padding: 15px 30px;
font-size: 16px;
cursor: pointer;
outline: none;
transition: transform 0.3s ease;
box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}
.bounce {
animation: bounce 0.6s;
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {
transform: translateY(0);
}
40% {
transform: translateY(-30px);
}
60% {
transform: translateY(-15px);
}
}
</style>
Thank you for reading this article.
Comments