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
5132

 

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
 

Get the Alerts – SharePoint PowerShell

Sathish Nadarajan
 
Solution Architect
June 2, 2016
 
Rate this article
 
Views
7634

 

In this article, we will see, how to retrieve the Alerts from the SharePoint WebApplication using PowerShell.

 ######################### this method will return the Alerts in the WebApplication
 
 function GetAlerts()
 {
     Write-Host "Entered GetAlerts Method" -ForegroundColor Yellow 
     Add-Content "$ProgressFile" "Entered GetAlerts Method"
     $script:Progress = "6:Entered"
     
     # Get WebApplication Object
     $WebApplication = Get-SPWebApplication $Config.Configuration.WebApplication.URL
 
     # Assign the XML Output File Paths
     $Alerts_XML_Path = $scriptBase + "Reports-$LogTimeAlerts.xml"
     
     # Create the XML File Tags
     
     $xmlWriter = New-Object System.XMl.XmlTextWriter($Alerts_XML_Path,$Null)
     $xmlWriter.Formatting = 'Indented'
     $xmlWriter.Indentation = 1
     $XmlWriter.IndentChar = "`t"
     $xmlWriter.WriteStartDocument()
     $xmlWriter.WriteComment('Files List On the WebApplication ' + $WebApplication.DisplayName)
     $xmlWriter.WriteStartElement('WebApplication')
     $xmlWriter.WriteEndElement()
     $xmlWriter.WriteEndDocument()
     $xmlWriter.Flush()
     $xmlWriter.Close()
     
     # Get All the Site collections
     $SiteCollections =  $WebApplication | Get-SPSite -Limit All
     #$SiteCollections =  Get-SPSite "http://ctsc00556722901:5555/sites/TeamSite2/"
     
     # write the output on XML File
     $xmlDoc = [System.Xml.XmlDocument](Get-Content $Alerts_XML_Path);
     $siteCollectionNode = $xmlDoc.CreateElement("SiteCollections")
     $xmlDoc.SelectSingleNode("//WebApplication").AppendChild($siteCollectionNode)
     $xmlDoc.Save($Alerts_XML_Path)
     
     # Iterate through the SiteCollections
     foreach($SiteCollection in $SiteCollections)
     {
         $siteCollectionName = $SiteCollection | select @{label = "Title";Ex = {$_.rootweb.Title}} 
         
         # write the output on XML File
         
         $xmlDoc = [System.Xml.XmlDocument](Get-Content $Alerts_XML_Path);
         $siteCollectionNode = $xmlDoc.CreateElement("SiteCollection")
         $xmlDoc.SelectSingleNode("//WebApplication/SiteCollections").AppendChild($siteCollectionNode)
         $siteCollectionNode.SetAttribute("Name", $siteCollectionName.Title)
         
         
         $subSitesNode = $siteCollectionNode.AppendChild($xmlDoc.CreateElement("SubSites"));
         $xmlDoc.Save($Alerts_XML_Path)
         
         # Get the Webs
         $Webs = Get-SPWeb -site $SiteCollection -Limit All 
         
         # Iterate through the Webs
         foreach($Web in $Webs)
         {
             # write the output on XML File
             
             $subSiteNameNode = $subSitesNode.AppendChild($xmlDoc.CreateElement("SubSite"));
             $subSiteNameNode.SetAttribute("Name", $Web.Title)
             $subSiteNameNode.SetAttribute("Url", $Web.Url)
             $subSiteNameNode.SetAttribute("WebID", $Web.Id)
             
             $parentWebTitle = ""
                             
             if($Web.ParentWebID -ne "00000000-0000-0000-0000-000000000000")
             {
                 $parentWeb = $SiteCollection.OpenWeb($Web.ParentWebID)
                 $parentWebTitle = $parentWeb.Title
                 
             }
             else
             {
                 $parentWebTitle = "RootWeb"
             }    
             $subSiteNameNode.SetAttribute("ParentWebName", $parentWebTitle)
             $subSiteNameNode.SetAttribute("ParentWebID", $Web.ParentWebID)
             
             $AlertsNode = $subSiteNameNode.AppendChild($xmlDoc.CreateElement("Alerts"));
             
             $xmlDoc.Save($Alerts_XML_Path)
             
             # Iterate through the Users
             foreach ($user in $Web.SiteUsers)
             {
                 # Get the User Alerts and Iterate
                 foreach($alert in $user.Alerts)
                 {
                     $AlertNode = $AlertsNode.AppendChild($xmlDoc.CreateElement("Alert"));
                     $AlertNode.SetAttribute("Name", $alert.Title)
                     $AlertNode.SetAttribute("List", $alert.List)
                     $AlertNode.SetAttribute("AssociatedUser", $user.LoginName)
                     $AlertNode.SetAttribute("AlertFerequency", $alert.AlertFrequency)
                     $AlertNode.SetAttribute("AlertType", $alert.AlertType)		
                                                                             
                     $xmlDoc.Save($Alerts_XML_Path)
                 }
             }
         }
     }    
     # write the output on XML File
     $xmlDoc.Save($Alerts_XML_Path)
     
     Write-Host "Completed GetAlerts Method" -ForegroundColor Yellow 
     Add-Content "$ProgressFile" "Completed GetAlerts Method"
     $script:Progress = "6:Success"
 }
 
 ########### End of Method #################
 
 

The snippet is self-explanatory.

Happy Coding,

Sathish Nadarajan.

Category : PowerShell, SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment