Custom Alert Message on SharePoint Page using Content Editor Web Part and JQuery

Ahamed Fazil Buhari
 
Senior Developer
February 28, 2018
 
Rate this article
 
Views
5251

 

Hi,

I just came across with the simple requirement and I thought to share this to everyone so some get benefit from this. The requirement was, we need to show an alert kind of message at the top of the page and this alert message should be visible for few seconds based on user need. This requirement can be done easily using JQuery, so I do not want to make complex things J

We maintained the information about this alert message (like Message itself, time to disappear and visibility for specific days) in a SharePoint list and added the following columns.

clip_image002

So the form looks like below, you can modify the form as per you requirement.

clip_image003

It is simple OOTB form it contains, Body where user can enter the message which he/she wants to show that on the page. This message appears only if the current date falls within StartDate and EndDate. SecondsToDisappear is the number field which is used to disappear the message after given seconds (leave empty if you want to show the message regardless of time), Level field applied CSS to the message which gives better look.

Below is the javascript code which implements the above mentioned requirement.

 'use strict';
 var CustomAlertLabel = CustomAlertLabel || {};
 
 CustomAlertLabel.MyMessage = (function () {
     return {
         init: init
     };
     function init() {
       //SP.SOD.executeFunc('sp.js', 'SP.ClientContext', generateLinks);     
         ExecuteOrDelayUntilScriptLoaded(generateLinks, "sp.js");        
     
         function generateLinks() {   
             //List name where we saved the message and other properties
             var announcementList = 'Announcements';
             var siteAbsoluteUrl = _spPageContextInfo.siteAbsoluteUrl;    
             //Get current date with 00:00:00 as time 
             //so that the message will be displayed even if the End Date is Today                
             var today = new Date();   
             var d = today.toISOString().substring(0,10) + "T00:00:00";
                        
             var endpoint = siteAbsoluteUrl + "/_api/web/lists/GetByTitle('" + announcementList + "')/items?$filter=StartDate le datetime'" + d + "' and Expires ge datetime'" + d + "'";
             //AJAX call to get List Items and filter applied in URL
             $.ajax({
                 url: endpoint,
                 type: "GET",
                 dataType: "json",
                 beforeSend: function (xhr) {
                     xhr.setRequestHeader("accept", "application/json; odata=verbose");
                 }
                 }).then(function (data) {
                     var results = data.d.results;               
                     for (var i = 0; i < results.length; ++i) {   
                       var messageContent = results[i].Body; 
                       var status = results[i].Level;
                       
                       var newDiv = "";
                       //applying css based on the Level of message
                       if(status.match("^Red")) {
                         newDiv = "<div id=messageDiv"+ i +" class='message-red'>";
                       }
                       else if(status.match("^Yellow")) {
                         newDiv = "<div id=messageDiv"+ i +" class='message-yellow'>";       
                       }
                       else if(status.match("^Green")){
                         newDiv = "<div id=messageDiv"+ i +" class='message-green'>";       
                       }
                       else {
                         newDiv = "<div id=messageDiv"+ i +">";           
                       }
                         
                       $("#mymessage").append(newDiv + messageContent + '</div>');                                                        
                       var disappearTime = results[i].SecondsToDisappear;
                       //Disappear the message based on number of seconds
                       if(disappearTime != null && disappearTime != 0) {
                         disappearTime = disappearTime*1000;
                         $('#messageDiv'+i).delay(disappearTime).fadeOut('slow');                          
                       }
                     }                   
                 });
             }    
         }
 })();
 $.ready(CustomAlertLabel.MyMessage.init());
 

We created simple html page in Site Assets and referred this JavaScript file and CSS as shown below,

clip_image004

Now go to the SharePoint Page where you would like to show the message. Add a Content Editor web part and refer the html created in the above step and set Chrome Type to None to avoid title from Content Editor webpart. Save the page

clip_image006

clip_image008

I created the below item on Feb 23rd

clip_image010

And the output will be,

clip_image012

Thank you for reading. J

Happy Coding

Ahamed

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Leave a comment