Simple implementation of notifications using Jquery

Web Development Simple implementation of notifications using Jquery

Introduction

In today's web development landscape, user experience is paramount. A key aspect of enhancing user experience is providing timely and informative notifications. jQuery, a popular JavaScript library, offers a straightforward approach to implementing custom notifications. This article will guide you through a simple yet effective method to create visually appealing and functional notifications using jQuery.

Goal

Implement simple and lightweight notification functionality using Jquery, CSS, HTML, Bootstrap 5, Bootstrap Icons.

HTML

<div id="notify-layout"></div>
<div id="notify-block" class="notify-block bg-success">
    <i class="bi bi-info-square me-1"></i>
</div>

First of all create an empty div notify-layout in which we will insert notifications. Also create a hidden template notify-block for notifications.

Class bi-info-square is Bootsrap Icon element. Class bg-success is Bootsrap background class.

CSS

#notify-layout {
  width: 260px;
  position: fixed;
  top: 80px;
  right: 20px;
  z-index: 100;
}

.notify-block {
  display: none;
  width: 260px;
  padding: 12px;
  border-radius: 6px;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 400;
  margin-bottom: 12px;
}

Element with class notify-layout will always be placed in the top right corner of the screen, even if scrolling is used.

Element with class notify-block is hidden and is template for all notifications.

JavaScript

$(document).ready(function() {
    // Call notification
    notify(message);

    // Notification
    function notify(message) {
        // Clone notification template and create new notify block 
        var notifyBlock = $("#notify-block").clone();

        // Insert the message into the notify block
        notifyBlock.append(message);

        // Show notify block
        notifyBlock.css('display', 'inline-block');

        // Create and change ID for notify block
        var datetime = new Date();
        notifyBlock.attr('id', 'notify-block-' + datetime.getTime());

        // Insert new notify block into notify-layout
        $("#notify-layout").append(notifyBlock);
        
        // Hide notification after 2 seconds
        setTimeout(function() {
            $(notifyBlock).slideToggle('slow');
        }, 2000);
    }
});

Script Overview:

  1. Create a notification block from a template.
  2. Make the block visible.
  3. Assign a unique ID to the block.
  4. Add a message to the block.
  5. Place the notification block within the main container.