How to count the number of notifications on an icon?


Overview

A notification icon is a common feature that exists in each and every application. In order to count the number of notifications and display it on an icon can be achieved with basic knowledge of JavaScript. So to build this feature we should have some prior knowledge about HTML Document Object Model (DOM), CSS, and Bootstrap.

Approach

To start building this feature first we had to link some of the Content Delivery Network (CDN) links to our HTML page.

  • Font Awesome CDN Link

<link rel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  • Bootstrap CDN Link

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

Algorithm

  • Step 1 − Create a HTML page and link the above Content Delivery Network (CDN) link in the head tag of the page.

  • Step 2 − Create a skeleton of the feature by adding the badge component of bootstrap, replace the text written inside the component with the font awesome notification bell icon. Inside the span tag replace the “99” with <span id=”component”> </span>.

<button type="button" class="btn btn-success position-relative m-3">
   <i class="fa fa-bell" aria-hidden="true"></i>
   <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill" id="counter">
      <span id="output" class="badge rounded-pill bg-danger">0</span>
   </span>
</button>
  • Step 3 − Create the notification section using bootstrap list-group component, add the id attribute with value as “notis”.

<ul class="list-group container" id="notis"> </ul>
  • Step 4 − Create the buttons as “Show Notifications” and “Remove Notifications” with onclick() event handler as “showNoti()” and “clearAll()” respectively.

<button class="btn btn-success ms-3 mt-3" onclick="showNoti()" id="showNoti">
   Show Notifications
</button>
<button class="btn btn-danger mt-3" onclick="clearAll()">
   Remove Notification
</button>
  • Step 5 − Now inside the script tag make the functioning of the feature. Create an empty array that contains all the upcoming notifications.

var Notifications = [ "News Article added", "User login Failed", "Article was sucessfully
propmted", "Device was found at 127.0.0.1", "New login alert" ];
  • Step 6 − Access the notifications section with its id as document.getElementById() and iterate over the array “arr” which contains all the notifications. Insert the notification inside the list group concatenating the particular notification using innerHTML.

var noti = document.getElementById("notis");
for (var n = 0; n < Notifications.length; n++) {
   var a = '<li class="list-group-item bg-light ms-3 my-2 rounded" id="noti">' + Notifications[n] + '</li>'
   noti.innerHTML += a;
}
  • Step 7 − Create a JavaScript arrow function “showNoti()”, access the inner text of the output badge. Use parseInt() property to get the value in Number type. Change the style to the notification section to “block” using DOM styling property.

showNoti = () => {
   var a = parseInt(document.getElementById("output").innerText);
   document.getElementById("output").style.background = "red";
   document.getElementById("output").innerText = Notifications.length;
   if (Notifications.length == 0) {
      alert("No notification found");
   }
   noti.style.display = "block";
}
  • Step 8 − Create a JavaScript arrow function “clearAll()”, access the inner text of the output badge. parseInt() property to get the value in Number type. Use the pop() method of the array object which will remove the element from an array, simultaneously use remove() method of DOM to remove the notification element also.

clearAll = () => {
   var a = parseInt(document.getElementById("output").innerText);
   if ((Notifications.length) == 0 || (Notifications.length) == 1) {
      alert("No notification found");
   }
   Notifications.pop();
   document.getElementById("output").innerText = Notifications.length;
   document.getElementById("noti").remove();
}
  • Step 9 − Now our feature is ready to use. Click the “show notifications” to get all the notifications and click “Remove Notification” to remove the notification.

Example

<html>
<head>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="crossorigin="anonymous" referrerpolicy="no-referrer" />
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
   <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
   <title> Count the Number of notifications on an icon </title>
</head>
   <body class="container">
      <button type="button" class="btn btn-success position-relative m-3">
         <i class="fa fa-bell" aria-hidden="true"></i>
         <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill" id="counter">
            <span id="output" class="badge rounded-pill bg-danger">0</span>
         </span>
      </button><br>
      <ul class="list-group container" style="display: none;" id="notis"></ul>
      <button class="btn btn-success ms-3 mt-3" onclick="showNoti()" id="showNoti"> Show Notifications</button>
      <button class="btn btn-danger mt-3" onclick="clearAll()">Remove Notification</button>
      <script>
         var Notifications = ["New Article added", "Login Failed", "Article was
         sucessfully propmted", "Device was found at 127.0.0.1", "New login alert"];
         var noti = document.getElementById("notis");
         for (var n = 0; n < Notifications.length; n++) {
            var a = '<li class="list-group-item bg-light ms-3 my-2 rounded" id="noti">' + Notifications[n] + '</li>' noti.innerHTML += a;
         }
         showNoti = () => {
            var a = parseInt(document.getElementById("output").innerText);
            document.getElementById("output").style.background = "red";
            document.getElementById("output").innerText = Notifications.length;
            if (Notifications.length == 0) {
               alert("No notification found");
            }
            noti.style.display = "block";
         }
         clearAll = () => {
            var a = parseInt(document.getElementById("output").innerText);
            if ((Notifications.length) == 0 || (Notifications.length) == 1) {
               alert("No notification found");
            }
            Notifications.pop();
            document.getElementById("output").innerText = Notifications.length;
            document.getElementById("noti").remove();
         }
      </script>
   </body>
</html>

Description

The output of the above example, when none of the buttons are clicked it shows a notification icon with “0” notification as till now the array is not been rendered to the icon badge.

So when the “Show Notifications” button is clicked the showNoti() function is triggered and the style of the notification section is changed to block, all the notifications are rendered on the screen. When all the notifications are rendered, now we can also remove the notification using the “Remove Notification” button when the button is clicked the clearAll() function is triggered and removes the notification from the section.

On clicking the remove notification when all the notifications are removed you will get an alert message of “No notification found”.

Conclusion

To work in real-time projects with the notification icon, we can call Application Program Interface (API) for notifications. We can store the notifications in an array and can iterate over the array using any loop or map function and can display the notification in our application. We can also add the animation to our notification panel with notification sound, so when the notification arrives it should produce the arrival sound with a good animation.

Updated on: 20-Nov-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements