In this tutorial we create a ringing bell animation with JavaScript and we learn how to create a simple bell icon that you can place in a corner of your web page (e.g. to collect subscribers to your push notifications).
Bell, button and animation
Basically we will draw a bell icon, inside a red circle, and we will position it at the bottom of the page. We will also add a nice animation with JavaScript to attract the user's attention: the bell will ring and vibrate every few seconds.
First you need to create an HTML button
with a bell icon inside it:
<button id="bell">
<svg viewBox="0 0 448 512" width="40" height="40">
<path d="M224 0c-17.7 0-32 14.3-32 32V51.2C119 66 64 130.6 64 208v18.8c0 47-17.3 92.4-48.5 127.6l-7.4 8.3c-8.4 9.4-10.4 22.9-5.3 34.4S19.4 416 32 416H416c12.6 0 24-7.4 29.2-18.9s3.1-25-5.3-34.4l-7.4-8.3C401.3 319.2 384 273.9 384 226.8V208c0-77.4-55-142-128-156.8V32c0-17.7-14.3-32-32-32zm45.3 493.3c12-12 18.7-28.3 18.7-45.3H224 160c0 17 6.7 33.3 18.7 45.3s28.3 18.7 45.3 18.7s33.3-6.7 45.3-18.7z"/>
</svg>
</button>
This example uses an SVG from Font Awesome, but there are many websites where you can download a bell icon.
Then we apply some styling with CSS:
#bell {
position: fixed;
bottom: 20px;
right: 20px;
width: 60px;
height: 60px;
border: none;
border-radius: 50%;
background-color: red;
fill: white;
}
Basically we are drawing a red circle with CSS, using background color and border radius, and we apply a white color to the bell icon. We also position the button in a corner of the web page.
Finally we can use JavaScript and the function Element.animate()
to add an animation (a vibration every second in this case):
document.getElementById('bell').animate([
{ transform: 'rotate(0deg)' },
{ transform: 'rotate(15deg)' },
{ transform: 'rotate(-15deg)' },
{ transform: 'rotate(10deg)' },
{ transform: 'rotate(-10deg)' },
{ transform: 'rotate(0deg)', offset: 0.5 }
], {
duration: 1500,
iterations: Infinity
});
We use the CSS transform
directive to rotate
the bell left and right. We also use offset
and duration
to control how frequently the bell is shaken.
Alternatively you can also use CSS animations directly, but using JavaScript it's often easier to define dynamic behaviors or use variables defined in JavaScript.
Using the button for push notifications (optional)
Once you have your custom button, it's easy to use it for collecting subscribers to web push notifications.
For example, you can use a small code snippet like this:
document.getElementById('bell').addEventListener('click', function () {
pushpad('subscribe', function () {
alert("You have successfully subscribed to notifications.");
});
});
Or you can also see a more complete example in the docs.
If you don't need custom styling for your bell, you can even skip this entire tutorial and simply use pushpad('widget')
, which already creates an animated bell for notifications.