Me & My SharePoint [FrontEnd]

© Christian Stahl – All about SharePoint branding & customizations

10 jQuery snippets for SharePoint 2010 — September 27, 2012

10 jQuery snippets for SharePoint 2010

I like to collect pieces of code snippets, sooner or later I’ll found them useful and they could save time and other efforts. My intention with this post is just to share a couple of my snippets and I hope that you’ll found something useful here.

Maybe you see something that can be written more efficient or if you have some cool snippets of your own you like to share, please drop this in a comment. These snippets are all plugin independent and should be easy to follow and modify and they can be used in SharePoint Designer 2010, Visual Studio or be included in a text file in SharePoint linked from a content editor. Don’t forget to create a reference to latest jQuery in the master page or into the text file.

1. Text manipulation
In this example I replace ‘All site content’ with help of the each function.

/* --- Doc ready ---*/
$(document).ready(function() {
$('.ms-splinkbutton-text').each(function(i){ $(this).text($(this).text().replace('All Site Content','More stuff here..'))
})
})

2. Check the URL
If the URL contains ‘news’, let’s do something conditionally with JS.

if(document.URL.indexOf("news") != -1){ 
alert("News site"); 
} else{ 
alert("Not the news site"); 
}

Another way is to getting a URL parameter and maybe their values and to something based on a condition with help of jQuery. Let’s give the background different colors depending if the view are sorted by Desc or Asc

var url = window.location.href; 
/* --- Doc ready ---*/
$(document).ready(function() {
if (url.search("&SortDir=Asc") > 0) { 
$(".ms-viewheadertr").css('background-color','lime');
};
else if (url.search("&SortDir=Desc") > 0) { 
$(".ms-viewheadertr").css('background-color','yellow');
};
/* --- End doc ready ---*/
});

3. Timestamp
If each page you create needs to have a unique name, you can set a time stamp when it creates. In this example I’ve used year to milliseconds and a random number at the end. This may be useful for a news site with many pages.

// create a timestamp with random
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var day = now.getDay();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var milliseconds = now.getMilliseconds();
var rand = Math.floor((Math.random()*1000000)+1);
var pageID = ('ID-')
var CustomInput = pageID + '' + year + '' + month + '' + day + '' + hours + '' + minutes + '' + seconds + '' + milliseconds + '' + rand;

/* --- Doc ready ---*/
$(document).ready(function() {
$("input[name='ctl00$PlaceHolderMain$nameInput']").val(CustomInput);
/* --- End doc ready ---*/
});

If you only want this function for let’s say a news site, you can use an If statement and identify the URL. But don’t forget that URL can be changed.

/* --- Doc ready ---*/
$(document).ready(function() {
if(document.URL.indexOf("news") != -1) { 
// Unique page title
$("input[name='ctl00$PlaceHolderMain$nameInput']").val(CustomInput);
} else{}
/* --- End doc ready ---*/
});

4. Change the attribute
Let’s say you want to change for example the title tag for the ‘I Like It’ button, you can do like this to set a custom attribute.

/* --- Doc ready ---*/
$(document).ready(function() {
$(".ms-socialNotif-Container > a").attr({
title: "Click the button if you like this page",
}); 
/* --- End doc ready ---*/
});

5. Change CSS
Let’s change the header text to red if the name is Link.

/* --- Doc ready ---*/
$(document).ready(function() {
$(".ms-WPTitle span:contains('Links')").css("color", "red"); 
});

Another way is to use a condition and a variable for this, if the web part header is equal to Shared Documents set the color to green, if the text is eq to Link set a border around the web part and set the text to red color. Normally I set the CSS into a CSS file, and you can use addClass to set the class as an option to set the CSS inline the script if you like.

/* --- Doc ready ---*/
$(document).ready(function() {
var WPtitle = $('.ms-WPTitle span'); 
for (var i = 0; i <= WPtitle.length; i++) { 
if ($(WPtitle[i]).text() == 'Links') { 
$(WPtitle[i]).css({'color': 'red'});
$(WPtitle[i]).parents().eq(10).css({'border': '1px black solid!important'});
}
else if ($(WPtitle[i]).text() == 'Shared Documents') { 
$(WPtitle[i]).css({'color': 'green'}); 
}} 
/* --- End doc ready ---*/
});

6. Add expand / collapse web parts
The following code will get expand/collapse for all standard web parts.

/* --- Doc ready ---*/
$(document).ready(function() {
$(function($) { 
$('.s4-wpTopTable').find('tr:first h3').append('<a class=\'min\' style=\'float:left; margin-right:5px\'><img src=\'/_layouts/images/collapse.gif\'/></a>'); 
var Collapse = "/_layouts/images/collapse.gif"; 
var Expand = "/_layouts/images/expand.gif"; 
$('.min').click(function(){      
var img = $(this).children(); 
$(this).closest('.s4-wpTopTable').find('tr:first').next().toggle().is(":visible") ? img.attr('src',Collapse) : img.attr('src',Expand ); 
}); 
});
});

7. Modify form field
jQuery can be used in many ways for standard list forms in SharePoint and this fist example shows how to set read only, a color and a specific width for the title field in edit mode.

/* --- Doc ready ---*/
$(document).ready(function() {
$("input[title='Title']").attr("readonly","true").css('background-color','#ccc').width(70);
/* --- End doc ready ---*/
});

Next example shows how to set a field limit and add a counter that shows number of characters left

// Show Nr of Characters left in a common list field
(function($){  
$.fn.fieldLimit = function(options) {  
return this.each(function() {  
var characters = 30;
$(this).keyup(function(){
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}	
var remaining = characters - $(this).val().length;
$(options.result).html(remaining + " characters left");			
});
});  
};  
})(jQuery);

/* --- Doc ready ---*/
$(document).ready(function() {
$('.ms-formtable').prepend("<div class='CharactersLeft'></div>");
$('input[title$=Title]').fieldLimit({
result:".CharactersLeft",
});
/* --- End doc ready ---*/
});

8. Check site template
If you need to do something based on which site template a site has been created from, you can identify this with help of the site template ID. I have only covered a few templates below.

/* --- Doc ready ---*/
$(document).ready(function(){
CurrentTemplate = g_wsaSiteTemplateId;
TeamSite = 'STS#0'
EnterpriseWiki = 'ENTERWIKI#0';
PublishingSite = 'CMSPUBLISHING#0';
if (CurrentTemplate == TeamSite){
alert('Im a Team site');}
else if (CurrentTemplate == EnterpriseWiki){
alert('Im a Enterprise Wiki');}
else if (CurrentTemplate == PublishingSite){
alert('Im a Publishing Site');}
else {
alert('Sitetemplate not defined yet..');}
/* --- End doc ready ---*/
});

9. Welcome message
This example shows how to work with variables. You’ll also find some plain old good JS date stuff that can be useful when you need to check times.

/* --- Doc ready ---*/
$(document).ready(function(){
var WelcomeMenuContent = $('.ms-welcomeMenu > a.ms-menu-a > span');
var UserName = WelcomeMenuContent.text();
var FirstName = UserName.split(" ")[0];
var Display;
var Digital = new Date()
var Hours = Digital.getHours()
Morning = 'Good morning' + " " + FirstName;
Lunch = 'Lunch time' + " " + FirstName;
Evening = 'Good evening' + " " + FirstName;
Night = 'Time to go home' + " " + FirstName;
TimeElse = 'Welcome' + " " + FirstName;
if (Hours >= 5 && Hours <= 11) 
WelcomeMenuContent.text(Morning);
else if (Hours == 12) 
WelcomeMenuContent.text(Lunch);
else if (Hours >= 13 && Hours <= 17) 
WelcomeMenuContent.text(Evening);
else if (Hours >= 18 && Hours <= 23) 
WelcomeMenuContent.text(Night);
else
WelcomeMenuContent.text(TimeElse);	
/* --- End doc ready ---*/
}); 

10. Append today’s date
While we’re talking about get date with JS, let’s see how you can use this to display current date somewhere at the page like this.

var d = new Date();
var month = d.getMonth();
var date = d.getDate();
var year = d.getFullYear();
/* --- Doc ready ---*/
$(document).ready(function() {
$('.s4-pagedescription').append("<div style='float:right'>" + month + "/" + date + "/" + year + "</div>"); 
});

Stay in tune!

/ Christian Ståhl