Back
Learn to build an engaging, squishy button that bounces like a rubber ball when pressed, bringing tactile motion into the digital realm.
<div class="button-container">
<button class="rubber-button" onclick="bounce()">Click Me</button>
</div>
function bounce() {
const button = document.querySelector('.rubber-button');
button.classList.add('bounce');
setTimeout(() => {
button.classList.remove('bounce');
}, 600);
}
.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.
<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
oLNUaYurJWldsJVibwqFJmrv
oLNUaYurJWldsJVibwqFJmrv
oLNUaYurJWldsJVibwqFJmrv