Sunday, July 14, 2013
10 jQuery Snippets for SharePoint 2010
1. Text manipulation
In this example I replace ‘All site content’ with the help of the each function.
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.1 | if (document.URL.indexOf( "news" ) != -1){ |
2 | alert( "News site" ); |
3 | } else { |
4 | alert( "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
01 | var url = window.location.href; |
02 | /* --- Doc ready ---*/ |
03 | $(document).ready( function () { |
04 | if (url.search( "&SortDir=Asc" ) > 0) { |
05 | $( ".ms-viewheadertr" ).css( 'background-color' , 'lime' ); |
06 | }; |
07 | else 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.
01 | // create a timestamp with random |
02 | var now = new Date(); |
03 | var year = now.getFullYear(); |
04 | var month = now.getMonth(); |
05 | var day = now.getDay(); |
06 | var hours = now.getHours(); |
07 | var minutes = now.getMinutes(); |
08 | var seconds = now.getSeconds(); |
09 | var milliseconds = now.getMilliseconds(); |
10 | var rand = Math.floor((Math.random()*1000000)+1); |
11 | var pageID = ( 'ID-' ) |
12 | var 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 () { |
3 | if (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.
1 | /* --- Doc ready ---*/ |
2 | $(document).ready( function () { |
3 | $( ".ms-socialNotif-Container > a" ).attr({ |
4 | title: "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.

01 | /* --- Doc ready ---*/ |
02 | $(document).ready( function () { |
03 | var WPtitle = $( '.ms-WPTitle span' ); |
04 | for ( var i = 0; i <= WPtitle.length; i++) { |
05 | if ($(WPtitle[i]).text() == 'Links' ) { |
06 | $(WPtitle[i]).css({ 'color' : 'red' }); |
07 | $(WPtitle[i]).parents().eq(10).css({ 'border' : '1px black solid!important' }); |
08 | } |
09 | else 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.
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>' ); |
05 | var Collapse = "/_layouts/images/collapse.gif" ; |
06 | var Expand = "/_layouts/images/expand.gif" ; |
07 | $( '.min' ).click( function (){ |
08 | var 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.
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

01 | // Show Nr of Characters left in a common list field |
02 | ( function ($){ |
03 | $.fn.fieldLimit = function (options) { |
04 | return this .each( function () { |
05 | var characters = 30; |
06 | $( this ).keyup( function (){ |
07 | if ($( this ).val().length > characters){ |
08 | $( this ).val($( this ).val().substr(0, characters)); |
09 | } |
10 | var 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({ |
21 | result: ".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 (){ |
03 | CurrentTemplate = g_wsaSiteTemplateId; |
04 | TeamSite = 'STS#0' |
05 | EnterpriseWiki = 'ENTERWIKI#0' ; |
06 | PublishingSite = 'CMSPUBLISHING#0' ; |
07 | if (CurrentTemplate == TeamSite){ |
08 | alert( 'Im a Team site' );} |
09 | else if (CurrentTemplate == EnterpriseWiki){ |
10 | alert( 'Im a Enterprise Wiki' );} |
11 | else if (CurrentTemplate == PublishingSite){ |
12 | alert( 'Im a Publishing Site' );} |
13 | else { |
14 | alert( '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.
01 | /* --- Doc ready ---*/ |
02 | $(document).ready( function (){ |
03 | var WelcomeMenuContent = $( '.ms-welcomeMenu > a.ms-menu-a > span' ); |
04 | var UserName = WelcomeMenuContent.text(); |
05 | var FirstName = UserName.split( " " )[0]; |
06 | var Display; |
07 | var Digital = new Date() |
08 | var Hours = Digital.getHours() |
09 | Morning = 'Good morning' + " " + FirstName; |
10 | Lunch = 'Lunch time' + " " + FirstName; |
11 | Evening = 'Good evening' + " " + FirstName; |
12 | Night = 'Time to go home' + " " + FirstName; |
13 | TimeElse = 'Welcome' + " " + FirstName; |
14 | if (Hours >= 5 && Hours <= 11) |
15 | WelcomeMenuContent.text(Morning); |
16 | else if (Hours == 12) |
17 | WelcomeMenuContent.text(Lunch); |
18 | else if (Hours >= 13 && Hours <= 17) |
19 | WelcomeMenuContent.text(Evening); |
20 | else if (Hours >= 18 && Hours <= 23) |
21 | WelcomeMenuContent.text(Night); |
22 | else |
23 | WelcomeMenuContent.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.
1 | var d = new Date(); |
2 | var month = d.getMonth(); |
3 | var date = d.getDate(); |
4 | var year = d.getFullYear(); |
5 | /* --- Doc ready ---*/ |
6 | $(document).ready( function () { |
7 | $( '.s4-pagedescription' ).append( "<div style='float:right'>" + month + "/" + date + "/" + year + "</div>" ); |
8 | }); |
Use jQuery & cookies in SharePoint 2010
In this blog article I’ll show you how to use Cookies in jQuery for your SharePoint Designer 2010 no code applications.
With help of a cookie you can write information to the user’s
computer and this can be useful if you need to store stuff like visitors
preferences, for example if the user has checked a check box or not at
some page. Cookies can be very useful in many ways, but in some
situations you need to write such information to the server like a
database instead, cookies should not be used for critical information or
any kind of sensitive information especially at a public faced site.
However a cookie can be a great choice for many tasks in your front end
development.Some examples of the usefulness of a cookie
- Change color schemes
- Hide / Show elements at the page
- Resizing fonts, scale up or down
- Form, auto save inputs in fields, selected check box or radio button
- Accordion / tabs, remember last state of collapsed/opened
- Navigation, remember the last location
- Welcome message, for example if you want to show a popup only once at specific date at the start page.
Jquery.cookies gives a couple of options like:
- Expires
The lifetime for the cookie. You can use a number of days or a specific date. If omitted, the cookie is a session cookie - Path
Where the cookie is valid. If you want it to be valid at every site in the site collection, just use a slash /, if you want it to be valid at let’s say only the news site set e.g /news/
Get going
Let’s start with a simple example just to get going, the following example will set the top row to a red or green background color depending of which link you click. Let’s say you clicked at green one and then reload the page, the green background color will remain. If you restart the browser, the top row will be white again. This script do not have any expired date, therefore, the cookie will expire automatically when you close the browser.Let’s try this out:
Download jquery.cookies.js and create a reference to this file in your custom master, don’t forget to include an reference to latest jQuery API as well.
HTML
Put this somewhere in your custom master page
1
2
3
4
5
6
| <!-- Session --> <div class= "Wrapper" > <div class= "Red" >Red</div> <div class= "Pipe" >|</div> <div class= "Green" >Green</div> </div> |
Put this in an external JS file referenced from your master page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| $(document).ready(function() { // Click red $( '.Red' ).click(function() { $( '.Wrapper' ).css( "background-color" , "red" ); $.cookie( 'Wrapper' , 'red' ); }); // Click green $( '.Green' ).click(function() { $( '.Wrapper' ).css( "background-color" , "green" ); $.cookie( 'Wrapper' , 'green' ); }); // Cookies var Wrapper = $.cookie( 'Wrapper' ); if (Wrapper == 'red' ) { $( '.Wrapper' ).css( "background-color" , "red" ); }; if (Wrapper == 'green' ) { $( '.Wrapper' ).css( "background-color" , "green" ); }; }); |
Put this in an external CSS file referenced from your master page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| .Wrapper{ width : 100% ; height : 16px ; background-color : #fff ; color : #000 ; } .Red{ cursor : pointer ; padding-left : 5px ; float : left ; } .Green{ cursor : pointer ; float : left ; } .Pipe{ float : left ; padding : 0px 5px 0px 5px } |
1
| $.cookie( 'Wrapper-' , 'Green-' ); |
1
| $.cookie( 'Wrapper-' , 'Green-' , {path: '/' , expires: 2 }); |
1
| C:\Users\...\AppData\Local\Microsoft\Windows\Temporary Internet Files |
1
| Wrapper-Green-ecmtest 67 / 108815182001923024639810215318430245996 * |
How to use cookies in a Data View web part
If we take this a step further and try to use cookies in a typical news roller DVWP. In this example, If you click at the icon next to the header for a news item that section will disappear, a kind of ‘I Have Read This’ function. At the bottom of the web part there’s a reset link that will delete the cookie.
The HTML part of the DVWP, it’s important to use @ID for the id, classes and href as the script shows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| <div class= "NewsRow {@ID}" > <div class= "NewsContentContainer" > <div class= "NewsTitle" > <div class= "NewsHider" ><a href= "{@ID}" id= "{@ID}" ><img alt= "" src= "/Style%20Library/Custom/Images/IhaveReadThis.png" width= "22" height= "22" /></a></div> <div class= "NewsTitleInner" ><a href= "/news/Pages/{@LinkFilename}" ><xsl:value-of select= "@Title" /></a></div> <div class= "GeneralClearBoth" ></div> </div> </div> <div class= "NewsAuthorCreatedWrap" > <span class= "NewsAuthor" >By <xsl:value-of select= "@PublishingContact.title" />,</span> <span class= "NewsCreated" ><xsl:value-of select= "@ArticleStartDate" /></span> </div> <div class= "NewsContent" > <xsl:call-template name= "FirstNWords" > <xsl:with-param name= "TextData" select= "$DescText" /> <xsl:with-param name= "WordCount" select= "15" /> <xsl:with-param name= "MoreText" select= "'...'" /> </xsl:call-template> </div> </div> |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| jQuery(function ($) { var removedLinks = 'removedLinks' ,Options = { expires: 7 , path: '/news' }, c=$.cookie(removedLinks)|| '#DebuggingCode' $(c).remove(); $( ".NewsHider a" ).click(function (e) { e.preventDefault(); var LinkClass = '.' + $(this). attr ( 'id' ), removeLinksClasses=c.split( ',' ) $(LinkClass).remove() removeLinksClasses.push(LinkClass) c=removeLinksClasses.join( ',' ) $.cookie(removedLinks, c, Options) }); $( '#NewsResetCookie' ).click(function(){ $.cookie(removedLinks, '' ,{expires: -1 ,path: '/news' }) }) }); |
SharePoint Form field date validation using javascript
<script language=”javascript” type=”text/javascript”>
function PreSaveAction()
{
var date1 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”Start Date”);
var date2 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”End Date”);
var arrDate1 = date1.value.split(“/”);
var useDate1 = new Date(arrDate1[2], arrDate1[1]-1, arrDate1[0]);
var arrDate2 = date2.value.split(“/”);
var useDate2 = new Date(arrDate2[2], arrDate2[1]-1, arrDate2[0]);
if(useDate1 > useDate2)
{
alert(“The End Date cannot happen earlier than the Start Date”);
return false; // Cancel the item save process
}
return true; // OK to proceed with the save item
}
function getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length – len)) {
return tags[i];
}
}
return null;
}
</script>
function PreSaveAction()
{
var date1 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”Start Date”);
var date2 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”End Date”);
var arrDate1 = date1.value.split(“/”);
var useDate1 = new Date(arrDate1[2], arrDate1[1]-1, arrDate1[0]);
var arrDate2 = date2.value.split(“/”);
var useDate2 = new Date(arrDate2[2], arrDate2[1]-1, arrDate2[0]);
if(useDate1 > useDate2)
{
alert(“The End Date cannot happen earlier than the Start Date”);
return false; // Cancel the item save process
}
return true; // OK to proceed with the save item
}
function getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length – len)) {
return tags[i];
}
}
return null;
}
</script>
IIS Manager Error: The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)
There is another application(SKYPE) that is using port 80
1. Open the Skype window, then click on Tools menu and select Options.
2. Click on Advanced tab, and go to Connection sub-tab.
3. Uncheck the check box for Use port 80 and 443 as an alternatives for incoming connections option.
4. Click on Save button
5. Restart Skype to make the change effective.
Enjoy :)
Send Email using Object Model
In First we need to configure Out going email on Central Administration.
Method 1 : –Code retrieves the SMTP host’s address from the SharePoint configuration database.
public static bool SendMail(string Subject, string Body,bool IsBodyHtml, string From, string To, string Cc, string Bcc)
{
bool mailSent= false;
try
{
SmtpClient smtpClient = new SmtpClient();
Method 1 : –Code retrieves the SMTP host’s address from the SharePoint configuration database.
public static bool SendMail(string Subject, string Body,bool IsBodyHtml, string From, string To, string Cc, string Bcc)
{
bool mailSent= false;
try
{
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = SPContext.Current.Site.WebApplication.
OutboundMailServiceInstance.Server.Address;
MailMessage mailMessage = new MailMessage(From, To, Subject, Body);
if (!String.IsNullOrEmpty(Cc))
{
MailAddress CCAddress = new MailAddress(Cc);
mailMessage.CC.Add(CCAddress);
}
if (!String.IsNullOrEmpty(Bcc))
{
MailAddress BCCAddress = new MailAddress(Bcc);
mailMessage.Bcc.Add(BCCAddress);
}
mailMessage.IsBodyHtml = IsBodyHtml;
smtpClient.Send(mailMessage);
mailSent = true;
}
catch (Exception) { return mailSent; }
return mailSent;
}
OutboundMailServiceInstance.Server.Address;
MailMessage mailMessage = new MailMessage(From, To, Subject, Body);
if (!String.IsNullOrEmpty(Cc))
{
MailAddress CCAddress = new MailAddress(Cc);
mailMessage.CC.Add(CCAddress);
}
if (!String.IsNullOrEmpty(Bcc))
{
MailAddress BCCAddress = new MailAddress(Bcc);
mailMessage.Bcc.Add(BCCAddress);
}
mailMessage.IsBodyHtml = IsBodyHtml;
smtpClient.Send(mailMessage);
mailSent = true;
}
catch (Exception) { return mailSent; }
return mailSent;
}
This ensures that you get the advantages of.NET-style mail delivery while keeping your configuration in Central Administration.
If however, you are not working in a SharePoint context, you can get the SPWebApplication reference from a new SPSite object like below
If however, you are not working in a SharePoint context, you can get the SPWebApplication reference from a new SPSite object like below
public static string GetSharePointMailService(string mysite)
{
string address;
using (SPSite site = new SPSite(mysite))
{
address = site.WebApplication.OutboundMailServiceInstance.Server.Address;
}
return address;
}
{
string address;
using (SPSite site = new SPSite(mysite))
{
address = site.WebApplication.OutboundMailServiceInstance.Server.Address;
}
return address;
}
Method 2 : –
This uses the embedded SharePoint SendEmail which has fewer
capabilities, but is as straightforward as possible, and is the
preferred approach if you simply want to send e-mail:
SPUtility.SendEmail(web, useHtml, htmlEncode, to, subject, htmlBody)
The Paramets are :
web(SPWeb) – An object that represents the site
headers(StringDictionary) – A collection of additional headers
useHtml(bool) – Used to append an HTML tag to the message (true)
htmlEncode(bool) – Encodes the message and replaces characters in HTML tags with entities
to(string) – The address to which to send the e-mail
subject(string) – Contains the subject for the e-mail message
htmlBody(string) – Contains the body of the e-mail message
addFooter(bool) – Used if there is a footer to be appended to the e-mail
web(SPWeb) – An object that represents the site
headers(StringDictionary) – A collection of additional headers
useHtml(bool) – Used to append an HTML tag to the message (true)
htmlEncode(bool) – Encodes the message and replaces characters in HTML tags with entities
to(string) – The address to which to send the e-mail
subject(string) – Contains the subject for the e-mail message
htmlBody(string) – Contains the body of the e-mail message
addFooter(bool) – Used if there is a footer to be appended to the e-mail
The headers parameter is used instead of the to and subject parameters.
It allows you to set all possible mail headers and forces you to add at
least the to header that way. An example follows:
StringDictionary headers = new StringDictionary();
headers.add(“to”,”authors@apress.com”);
headers.add(“cc”,”joerg@krause.net”);
headers.add(“bcc”,”checkthis@apress.com”);
headers.add(“from”,sp2010@apress.com);
headers.add(“subject”,”Send an EMail from SPUtility”);
headers.add(“content-type”,”text/html”);
string bodyText =”This is an html formatted message.”;
SPUtility.SendEmail(web, headers, bodyText);
Note that StringDictionary is defined in the System.Collections.Specialized namespace.
headers.add(“to”,”authors@apress.com”);
headers.add(“cc”,”joerg@krause.net”);
headers.add(“bcc”,”checkthis@apress.com”);
headers.add(“from”,sp2010@apress.com);
headers.add(“subject”,”Send an EMail from SPUtility”);
headers.add(“content-type”,”text/html”);
string bodyText =”This is an html formatted message.”;
SPUtility.SendEmail(web, headers, bodyText);
Note that StringDictionary is defined in the System.Collections.Specialized namespace.
Method 3 : - Sending E-Mail from a WCF Service
Sending an e-mail from a service when SPContext is not available could
fail. As a workaround, you have to prevent the mail function from
reading the current context by using HttpContext.Current = null. If it
can’t, it will retrieve the right context and it will then work. The
next example shows this.
Sending E-mail Using SendMail from a WCF Service
try
{
using (SPSite site = new SPSite(“http://sharepointserve”))
{
SPWeb thisWeb = site.RootWeb;
{
string to = “someone@apress.com”;
string subject = “Book Message”;
string body = “A message from SharePoint”;
HttpContext curCtx = HttpContext.Current;
HttpContext.Current = null;
bool success = SPUtility.SendEmail(thisWeb, true, true, to, subject, body);
HttpContext.Current = curCtx;
}
}
}
catch (Exception ex)
{// Exception handling skipped for clarity}
try
{
using (SPSite site = new SPSite(“http://sharepointserve”))
{
SPWeb thisWeb = site.RootWeb;
{
string to = “someone@apress.com”;
string subject = “Book Message”;
string body = “A message from SharePoint”;
HttpContext curCtx = HttpContext.Current;
HttpContext.Current = null;
bool success = SPUtility.SendEmail(thisWeb, true, true, to, subject, body);
HttpContext.Current = curCtx;
}
}
}
catch (Exception ex)
{// Exception handling skipped for clarity}
In the above code the current context is set to null to force the
context to be retrieved again. Saving the current context ensures that
the service works properly after the method has been executed.
Subscribe to:
Posts (Atom)