Posts Tagged ‘Javascript’

SharePoint – Creating a Rotating Image Banner using JavaScript

April 27, 2015 2 comments

In this post I will show you how easily we can create a Rotating Image banner in SharePoint 2013. (I saw the requirement from

Images are stored in an Images Library (Picture Library)

First you need to place anĀ img tag into the Page. This is the tag which loads Images from Library and cycles images every 5 seconds.

<img id="imageRotator" >

Once this is added, you can use below JavaScript code

	var arrayOfImageObjects = new Array();
	var currentImageIndex = 0;
	function GetImagesAndRotate() {
		var url = "http://siteurl/_api/web/lists/getbytitle('ImageLibrary')/items?$expand=File"
			url: url,
			type: "GET",
			headers: { 
				"accept": "application/json;odata=verbose",
				"content-type": "application/json;odata=verbose",
				"X-RequestDigest": $("#__REQUESTDIGEST").val(),				
			success: function(data){
				var result = data.d.results;
					var image = result[i];
					var imageObject = { };
					imageObject.Name = image.File.Name;
					imageObject.Url = image.File.ServerRelativeUrl;
					imageObject.Width = image.File.ImageWidth;
					imageObject.Height = image.File.ImageHeight;					
			error: function(){
				alert("request failed");
	function NextImage(){		
		if(currentImageIndex < arrayOfImageObjects.length) {
			currentImageIndex = 0;		

Finally you can invoke this using


SharePoint – JSOM Sample for SP.AttachmentCollection.getByFileName Method

Today I found a question in StackExchange.

The OP was asking how to use this method using Client Side Object Model. Since this is not available in MSDN ( I thought of creating it.

Here is the sample – You should change the LISTNAME, ID & FILENAME

var clientContext = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle("LISTNAME");
var listItem = list.getItemById(ID);
clientContext.executeQueryAsync(Function.createDelegate(this, onSuccess), Function.createDelegate(this, onFailure));

function onSuccess(sender, args) {
	var item = listItem;
	var total = item.get_attachmentFiles().get_count();
	if (total > 0) {
		console.log(total + " file attachments");

function onFailure(sender, args) {

SharePoint 2013 – Hide page title

December 4, 2013 7 comments

Here is a snippet which can be used to hide page title. All you need to do is edit the master page and place the script inside head tag

<script type="text/javascript">
	function hidePageTitle() {
		var elem = document.getElementById('pageTitle'); = 'block';


JavaScript – Object Oriented Programming

December 2, 2013 Leave a comment

The use of JavaScript is increasing heavily. It’s the right time to learn about writing good, clean and efficient JavaScript code rather than simply writing in an unorganized fashion. In this post I am trying to bring up some of the concepts we should be aware while using JavaScript.

JavaScript is a prototype based language. Its a style of object-oriented programming in which classes are not present.

In JavaScript defining a class is equal to creating a function. For example

function Employee() {

To create instances of this we use

var e = new Employee();

Creating an object will executes the statements inside the function, thus it acts as a constructor. For example

function Employee() {
    alert("I am an employee");
var e1 = new Employee();

This will bring up the alert window

Properties & Methods

JavaScript object properties are varibales declared inside the class. We can refer properties inside the class using the this keyword (similar to C#).


function Employee(name) { = name;
var e1 = new Employee("Amal Hashim");
alert("I am an employee with name = " +;


Methods are defined as functions, and they are invoked similar to how properties are used


function Employee(name) { = name;
Employee.prototype.getName = function() {
var e1 = new Employee("Amal Hashim");


Inheritance & Encapsulation

JavaScript supports only single class inheritance. Inheritance enables the creation of parent child relationships.


//Define Parent Class
function Employee(name) { = name;
Employee.prototype.whoAmI = function() {
	alert("Employee Object");
Employee.prototype.getName = function() {

//Define Child Class
function Manager() {
	//Invoke parent constructor;
//Inheritance - Manager inherits Employee
Manager.prototype = new Employee();
Manager.prototype.constructor = Manager;
//Over ride whoAmI
Manager.prototype.whoAmI = function() {
	alert("Manager Object");

var manager = new Manager();
manager.whoAmI(); = "Amal Hashim";
alert(manager instanceof Manager);
alert(manager instanceof Employee);


In the above example, Manager object doesn’t need to define getName method. Its encapsulated in the parent Employee class.

Categories: jQuery Tags: ,

SharePoint 2013 – Document Library – Download a copy button

November 29, 2013 8 comments

I found a question in technet forum, the user was asking on How to add “DOWNLOAD A COPY” button in document library COLUMN?

And to answer this question, I did a bit of research and came up with below solution

First step is to add a new column to the document library. I named it as “Download a copy”


Ensure to add the new column as the last column in the View.

Now go back to the view, then edit page. Now add a new Script Editor webpart and paste below code

<script type="text/javascript">
function runAfterEverythingElse(){
var elementArray = document.getElementsByClassName("ms-vb-lastCell");
var idArray = document.getElementsByClassName("ms-listlink");
for(var i = 0; i < elementArray.length; i++)
	elementArray[i].innerHTML = '<a unselectable="on" href="javascript:;" onclick="\''+ idArray[i]['href'] + '\')" class="ms-cui-ctl-large " aria-describedby="Ribbon.Documents.Copies.Download_ToolTip" mscui:controltype="Button" role="button" id="Ribbon.Documents.Copies.Download-Large"><span unselectable="on" class="ms-cui-ctl-largeIconContainer"><span unselectable="on" class=" ms-cui-img-32by32 ms-cui-img-cont-float"><img unselectable="on" alt="" src="/_layouts/15/1033/images/formatmap32x32.png?rev=31" style="top: -409px; left: -35px;"></span></span><span unselectable="on" class="ms-cui-ctl-largelabel">Download a<br>Copy</span></a>';

Click Ok, and stop editing the page. Final result


SharePoint 2013 – Directly open list item edit form

November 21, 2013 Leave a comment

Sometimes it will become a difficult job to edit a list item (not for everyone :D). You should first open the context menu, and then click edit item or you can open the item in view mode and then click edit item.

Using jQuery we can easily change this behavior by directly opening edit form instead of view. Below is a simple snippet which can achieve this. Just add a script editor webpart and paste below code

<script type="text/javascript" src=""></script>
<script type="text/javascript">
  // Change all display form links to edit form links
  $('.ms-vb a[href*="listform.aspx"]').each(function(){
      var url = $(this).attr('href');
      url = url.replace("PageType=4", "PageType=6");
      $(this).attr('href', url);

JavaScript – Escaping quotes

While passing data through AJAX post we might want to escape quote characters. One option is to escape using JavaScript method, but this will encode the entire string. The simplest approach is using the replace method.

     data.replace(/(['"])/g, "\\$1")
Categories: jQuery, Misc Tags: ,

Javascript – Refresh or Reload Page

One line code that can refresh the page

Categories: jQuery Tags: ,

Javascript – Global Error Handler

March 8, 2013 1 comment
window.onerror = function(error, url, line) {
    var errorDetails = "Error Description = " + error;
    errorDetails += "\nUrl = " + url;
    errorDetails += "\nLine Number = " + line;

Categories: jQuery Tags: ,