Archive

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 http://sharepoint.stackexchange.com/a/139738/34350)

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"
		
		jQuery.ajax({
			url: url,
			type: "GET",
			headers: { 
				"X-HTTP-Method":"MERGE",
				"accept": "application/json;odata=verbose",
				"content-type": "application/json;odata=verbose",
				"X-RequestDigest": $("#__REQUESTDIGEST").val(),				
			},
			success: function(data){
				var result = data.d.results;
				for(i=0;i<result.length;i++){
					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;					
					arrayOfImageObjects.push(imageObject);
				}				
				setTimeout(NextImage,5000);
			},
			error: function(){
				alert("request failed");
			}
		});
	}
	
	function NextImage(){		
		if(currentImageIndex < arrayOfImageObjects.length) {
			jQuery('#imageRotator').attr('src',arrayOfImageObjects[currentImageIndex].Url);
			currentImageIndex++;
		}
		else
			currentImageIndex = 0;		
		setTimeout(NextImage,5000);
	}

Finally you can invoke this using

	jQuery(document).ready(function(){
		GetImagesAndRotate();
	});
Advertisements

SharePoint – JSOM Sample for SP.AttachmentCollection.getByFileName Method

Today I found a question in StackExchange.

http://sharepoint.stackexchange.com/questions/136304/fetch-list-item-attachment-by-name

The OP was asking how to use this method using Client Side Object Model. Since this is not available in MSDN (https://msdn.microsoft.com/en-us/library/office/jj245502.aspx) 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.load(listItem);
clientContext.load(listItem.get_attachmentFiles().getByFileName("FILENAME"));
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) {
	//failed
}

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');
		elem.style.display = 'block';
	}

	_spBodyOnLoadFunctionNames.push("hidePageTitle"); 
</script>

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
JS1

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#).

Example

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

JS2

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

Example

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

JS3

Inheritance & Encapsulation

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

Example

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

//Define Child Class
function Manager() {
	//Invoke parent constructor
	Employee.call(this);
}
//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();
manager.name = "Amal Hashim";
alert(manager.getName());
//checking
alert(manager instanceof Manager);
alert(manager instanceof Employee);

JS4
JS6
JS4
JS4

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”

D1

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="window.open(\''+ 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>';
}  
}
_spBodyOnLoadFunctionNames.push("runAfterEverythingElse");  
</script>

Click Ok, and stop editing the page. Final result

D1

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="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() 
{
  // 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);
  });
});
</script>