Sunday, July 14, 2013

10 jQuery Snippets for SharePoint 2010

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 the latest jQuery in the master page or into the text file.

1. Text manipulation

In this example I replace ‘All site content’ with the help of the each function.
2012-09-30-10jQuery-01.png

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

2. Check the URL

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

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

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

01var url = window.location.href;
02/* --- Doc ready ---*/
03$(document).ready(function() {
04if (url.search("&SortDir=Asc") > 0) {
05$(".ms-viewheadertr").css('background-color','lime');
06};
07else if (url.search("&SortDir=Desc") > 0) {
08$(".ms-viewheadertr").css('background-color','yellow');
09};
10/* --- End doc ready ---*/
11});

3. Timestamp

If each page you create needs to have a unique name, you can set a time stamp when it is created. 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.
2012-09-30-10jQuery-02.png

01// create a timestamp with random
02var now = new Date();
03var year = now.getFullYear();
04var month = now.getMonth();
05var day = now.getDay();
06var hours = now.getHours();
07var minutes = now.getMinutes();
08var seconds = now.getSeconds();
09var milliseconds = now.getMilliseconds();
10var rand = Math.floor((Math.random()*1000000)+1);
11var pageID = ('ID-')
12var CustomInput = pageID + '' + year + '' + month + '' + day + '' + hours + '' + minutes + '' + seconds + '' + milliseconds + '' + rand;
13 
14/* --- Doc ready ---*/
15$(document).ready(function() {
16$("input[name='ctl00$PlaceHolderMain$nameInput']").val(CustomInput);
17/* --- End doc ready ---*/
18});

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.

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

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 this to set a custom attribute.
2012-09-30-10jQuery-03.png

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

5. Change CSS

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

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

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.
2012-09-30-10jQuery-04.png

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

6. Add expand / collapse web parts

The following code will expand/collapse for all standard web parts.
2012-09-30-10jQuery-05.png

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

7. Modify form field

jQuery can be used in many ways for standard list forms in SharePoint. This fist example shows how to set read only, a color and a specific width for the title field in edit mode.
2012-09-30-10jQuery-06.png

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

The next example shows how to set a field limit and add a counter that shows the number of characters left
2012-09-30-10jQuery-07.png

01// Show Nr of Characters left in a common list field
02(function($){ 
03$.fn.fieldLimit = function(options) { 
04return this.each(function() { 
05var characters = 30;
06$(this).keyup(function(){
07if($(this).val().length > characters){
08$(this).val($(this).val().substr(0, characters));
09}  
10var remaining = characters - $(this).val().length;
11$(options.result).html(remaining + " characters left");        
12});
13}); 
14}; 
15})(jQuery);
16 
17/* --- Doc ready ---*/
18$(document).ready(function() {
19$('.ms-formtable').prepend("<div class='CharactersLeft'></div>");
20$('input[title$=Title]').fieldLimit({
21result:".CharactersLeft",
22});
23/* --- End doc ready ---*/
24});

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 the help of the site template ID. I have only covered a few templates below.

01/* --- Doc ready ---*/
02$(document).ready(function(){
03CurrentTemplate = g_wsaSiteTemplateId;
04TeamSite = 'STS#0'
05EnterpriseWiki = 'ENTERWIKI#0';
06PublishingSite = 'CMSPUBLISHING#0';
07if (CurrentTemplate == TeamSite){
08alert('Im a Team site');}
09else if (CurrentTemplate == EnterpriseWiki){
10alert('Im a Enterprise Wiki');}
11else if (CurrentTemplate == PublishingSite){
12alert('Im a Publishing Site');}
13else {
14alert('Sitetemplate not defined yet..');}
15/* --- End doc ready ---*/
16});

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.
2012-09-30-10jQuery-08.png

01/* --- Doc ready ---*/
02$(document).ready(function(){
03var WelcomeMenuContent = $('.ms-welcomeMenu > a.ms-menu-a > span');
04var UserName = WelcomeMenuContent.text();
05var FirstName = UserName.split(" ")[0];
06var Display;
07var Digital = new Date()
08var Hours = Digital.getHours()
09Morning = 'Good morning' + " " + FirstName;
10Lunch = 'Lunch time' + " " + FirstName;
11Evening = 'Good evening' + " " + FirstName;
12Night = 'Time to go home' + " " + FirstName;
13TimeElse = 'Welcome' + " " + FirstName;
14if (Hours >= 5 && Hours <= 11)
15WelcomeMenuContent.text(Morning);
16else if (Hours == 12)
17WelcomeMenuContent.text(Lunch);
18else if (Hours >= 13 && Hours <= 17)
19WelcomeMenuContent.text(Evening);
20else if (Hours >= 18 && Hours <= 23)
21WelcomeMenuContent.text(Night);
22else
23WelcomeMenuContent.text(TimeElse); 
24/* --- End doc ready ---*/
25});

10. Append today’s date

While we’re talking about get date with JS, let’s see how you can use this to display the current date somewhere on the page like this.
2012-09-30-10jQuery-09.png

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

No comments:

Post a Comment