Dynamically create subscribe to alert link JavaScript SharePoint

Code for creating an alert for a list dynamically on a page. I have created the following HTML file, upload it somewhere in your site collection and link to it from a content editor web part, change the title of the list you want people to subscribe to and the message 🙂 

Note that this is sitting on a discussion site home page therefore is looking for /sitepages – if you want it to look for /pages change this, or if you want to hard code the link to a root level list for subscription change it even more 😛 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
</head>

<body>
<script type="text/javascript">
	$().ready(function () {
	    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { });
	    SP.SOD.executeOrDelayUntilScriptLoaded(initiateDiscussionsAlerts, "sp.js", "SP.ClientContext");
	})

	var discussionList;
	var discussionWeb;
	function initiateDiscussionsAlerts() {
		// load web
		clientContext = new SP.ClientContext.get_current();                    
	    discussionWeb = clientContext.get_web();
	    clientContext.load(discussionWeb);
	    
	    // load discussions list and ID
	    discussionList = discussionWeb.get_lists().getByTitle("Discussions List");
	 	clientContext.load(discussionList); 
	
		clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
	}
	  
	function onQuerySucceeded() {
		var webUrl = window.location.href;
		if (webUrl.toLowerCase().indexOf('/sitepages') != -1) {
			var listGuid = discussionList.get_id();
		    webUrl = webUrl.substr(0, webUrl.toLowerCase().indexOf('/sitepages'));
		    
		    $('.discussion-alert > a').attr('href', webUrl + '/_layouts/SubNew.aspx?List=' + listGuid + '&Source=' + webUrl);
		}
	}
	             
	function onQueryFailed(sender, args) {
		alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
	}
</script>

	<div class="discussion-alert"><a href="">Subscribe to Alerts for this Discussion Board</a></div>
</body>

</html>

 

Leave a Reply

Your email address will not be published. Required fields are marked *