Skip to content

Extending the DVWP with jQuery search, sort and pagination

In this post I’ll show you the quick steps how to extend the Data View Web Part (DVWP) with help of a jQuery plugin named DataTables.
The DVWP can connect to a SharePoint list and you can use it for example to display content in tabular view from a SharePoint list. Let’s say you want to create a news rollup that reads from the pages library with some special styling and condition, the DVWP is one of the options for this task. There’s a lot you can do with only XSLT, HTML and CSS but sometimes you need to add jQuery for some specific functions.

In this example I’ll show how to extend a basic DVWP news rollup with search-as-you type, sort function and pagination.

In order for jQuery DataTables to be able to function correctly, the HTML for the dataview table must be laid out in a well formed manner with the ‘thead’ and ‘tbody’ sections declared. Remember that use filters and limit number of object by server side in the DVWP especially if you’re dealing with large data sets, the datatable.js is there to serve a user friendly presentation layer.

The steps

  1. Create the DVWP
  2. Add the HTML that’s needed for the datatable plugin
  3. Add jQuery and CSS in separate files and reference this from your custom master page

jQuery
What you need for the plugin:

$(document).ready(function() {
$('#example').dataTable({
"oLanguage": {
"sInfo": "_START_ - _END_ of _TOTAL_ pages",
"sSearch": "Search:",
"sZeroRecords": "",
"sInfoEmpty": "No results..",
"sInfoFiltered": "",
"oPaginate": {
"sFirst": "<<",
"sLast": ">>",
"sNext": ">",
"sPrevious": "<"
}},
"sPaginationType": "full_numbers",
"iDisplayLength": 4,
"bLengthChange": false
});
var oTable = $('#example').dataTable();
oTable.fnSort([[0,'desc']]);
});

References
The references in your master page should looks like this:

<SharePoint:CssRegistration name="/Style Library/DVWP/Styles/MSDN.css" After="corev4.css" runat="server"/>
<script type="text/javascript" src="/Style Library/DVWP/Scripts/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="/Style Library/DVWP/Scripts/DataTables-1.9.4/media/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="/Style Library/DVWP/Scripts/addOns.js"></script>

Download
Download the aspx including the DVWP, jQuery and CSS taken from this example. The news pages in this example have the path /press/nyheter/ and the page library is named Sidor. Change the name and URL in the DVWP as you prefer as well as the select query. Do also download the DataTable plugin here.

I like the DVWP, it’s easy to work with and there’s a lot of ways to extend it, however this plugin works great with REST, librarys such as SPServices or in custom code. You can even use it in a custom format (template) for Content Query Web Part as well, maybe I’ll write a post about how to do this later on.

This technique works great in SharePoint 2007, 2010 and 2013, in foundation or server, online or OnPrem.

/ Christian

SharePoint Server MVP 2013

I’m very happy to announce that I’ve been renewed with the award SharePoint MVP 2013 by Microsoft for the third time around!

MVP2013

To receive this award again makes me really proud and of course motivates me to keep on writing articles, speaking at conferences and participate in different projects for the community around SharePoint. Many thanks to Microsoft, my MVP lead, colleagues, friends, readers of this blog and all great people out there in the world wide SharePoint community. If you want to know more about the program, read it from the Microsoft MVP site.

See you around and stay in tune!

/ Christian

How to include a DVWP into a master page in the form of a UserControl

If you the data view web part is one of your tools, you might come across the need to embed a DVWP into a master page. You can do that as long as you make the DVWP reusable all over the site collection if we talking about a DVWP that fetch content from a list at one of the sites in the collection. However, the downside doing that, is that the DVWP will give a lot of extra markup, HTML and XSLT in your master page. Dealing with that makes the master page be a bit harder for further development and for maintain. Optionally you can looking into use a Content Editor in the master page where you link it to a text file containing your DVWP.

However, if you have created a DVWP and just want to include a single reference line link an include file in the master page to the DVWP instead of having the DVWP direct in your master page you can do that with help of Visual Studio. It’s just to create a User Control (UC) and host the DVWP in the UC file and deploy the file to SharePoint file system. When you do that it’s just to include the UC as an include file in the master page.

In the example I’ve created a link list named TopLinkList in the root site of the site collection with one extra column named SortOrder by the type choice where I have set the value 1 up to 5. The idea behind this is to include a set of links from the list in the master page that displays in the header of the pages.

LinkList1

Let’s try this out!

  1. Create the TopLinkList list and the extra column as described above and create let’s say three Items in this list
  2. Create a DVWP and the HTML & CSS that reads and display the list items. Don’t forget to make the DVWP available to all sites in the site collection. You can download my example and use it as an starting point for your further development. See the link at the end of the post
  3. Open your developer environment where you got SharePoint and in this example Visual Studio 2010 installed
  4. Open VS 2010 and create a new project by the type ’Empty SharePoint Project’
  5. Give it the name CustomTopLinks and click OK
  6. Select Deploy as a farm solution and click Finish
  7. In the solution explorer, right click at the project and select Add and then New Item
  8. Select User Control
  9. Name it TopLinks.ascx and click the button Add
  10. Copy the code from the DVWP and paste this just below the register tags and save the page
  11. In the solution explorer, right click at the project and select Build
  12. In the solution explorer, right click at the project and select Deploy. Verify that you got no errors
  13. When this is done, open your custom master page with SharePoint Designer
  14. Add the following register tag at the top of the page:
    <%@ Register TagPrefix="CustomTopLinks" TagName="CustomTopLinks" Src="~/_controltemplates/CustomTopLinks/TopLinks.ascx" %>
    
  15. Add the control somewhere in your markup where you like it to appear in the pages:
    <CustomTopLinks:CustomTopLinks id="CustomTopLinks" runat="server"/>
    
  16. Done!

Download the DVWP taken from this example

Take a look at the following image that shows the columns you’ll need

LinkList2

</ Christian>

Book review: Rapid SharePoint 2013 Collaboration Solution Development and Deployment

I have just read the book and liked it very much and I’m therefore writing a short summary of the book and my thoughts about it.

sharemuchThe book is written by my friend and fellow SharePoint MVP Yaroslav Pentsarskyy, I have read one of his earlier books, SharePoint 2010 Branding in Practice that was mainly about approaches and best practices around branding solutions in Visual studio 2010. This book covers this parts as well for SharePoint 2013 and includes a lot of other components you’ll need to know when you’re developing for example a custom site definition or want to provision files or a structure to SharePoint.

You don’t need to be a backend developer to get value out of this book, If you are a designer that works and are quite familiar with branding in general and knows relevant techniques like CSS, HTML and JS and wants to know more about SharePoint 2013 branding in the developers perspective like packing and deploying your design, this a definitive a book for you.

You will find clear and factual examples and scenarios that you can try out in your environment, you can also download the code that are related to the examples.

This book includes:

• Branding elements in SharePoint 2013
• Extending site templates
• Provisioning and automated installations of branding packages
• Changing the look and feel of Personal Site
• Capturing list events
• Working with user profiles and user profile properties
• Start building SharePoint 2013 apps

My overall impression of the book is very good and I would highly recommend it to anyone that wants to learn more about the art of SharePoint branding & development. You will find a lot of great stuff that takes you to the next level of SharePoint branding.

For more information about the author, Yaroslav Pentsarskyy: http://www.sharemuch.com and to order the book you’ll find it at Amazon from here.

/ Christian

Add an arrow to the global navigation in SharePoint 2010

Sometimes it’s the small details that matters most and makes the difference. This post is about how to customize the look and feel for the global navigation, one important element in the SharePoint interface. The navigation control renders a fairly deep HTML structure with a lot of classes to keep in mind when you need to set your branding on the top of it. Recently I built an Intranet branding where the agency had the desire to include a small arrow for selected links in the navigation. This CSS do also take care of drop downs, in the case you are using that. I hope this could be useful for you if you need to include graphics, like this arrow in the global navigation.

ZeroOne

CSS

a:focus, a:active, a:hover {outline:none}
#s4-topheader2 {
border-bottom:0px transparent solid!important
}
.s4-tn {
background-color:#000; border-bottom:#fff 1px solid;
font-family:"Trebuchet MS"
}
.menu-horizontal {
margin-left:12px; border-left:#000 1px solid;
border-right:#000 1px solid;
}
.s4-tn ul.static > li.static > .menu-item {
height:26px; line-height:26px;
border-left:transparent 1px solid;
border-right:transparent 1px solid;
padding-left:15px; padding-right:15px;
white-space:nowrap; color: #fff;
font-size:12px; font-weight:bold;
}
.s4-tn ul.root > li.static > ul.static > li.selected {
background-color:#0089C5;
}
.s4-toplinks .s4-tn a.selected {
border: 1px solid transparent; margin: 0px;
padding-left:15px; padding-right:15px;
color:#fff; line-height:16px!important;
position:relative; z-index:10; left:0px; top:5px;
background: url('/Style%20Library/Images/MenuDownArrow.png') no-repeat center 30px !important;
}
.s4-tn ul.static > li.static > a:hover {
background-image:none; background-color:#0089C5;
border-left:transparent 1px solid; border-right:#transparent 1px solid;
color:#fff!important; text-decoration:none;
}
.menu-horizontal ul.dynamic a.dynamic-children span.additional-background {
padding-right:0px;
}
.menu-horizontal a.dynamic-children span.additional-background {
background-image:none; padding-right:0px;
}
.s4-tn ul.dynamic {
background-image:none;
border-top:0px; border-right:0;
border-bottom:1px #ccc solid; border-left:1px #ccc solid ;
margin:0px; margin-left:1px;
}
.s4-tn li.dynamic {
background-image:none;
border-top:1px #ccc solid; border-right:1px #ccc solid;
border-bottom:1px #fff solid; border-left:1px #fff solid;
}
.s4-tn li.dynamic > .menu-item {
height:16px; padding:7px 10px;
color:#333; background-color:#f7f7f7;
}
.s4-tn li.dynamic > a:hover {
color:#00557B; background-color:#fff;
}
.dynamic > li.dynamic-children > ul.dynamic {
margin-left:-2px; margin-top:0px;
}

Download the small arrow from here

I’ve written a few blog posts earlier about the global navigation. You can found the posts here.

If you have any questions about this, please feel free to contact me.

/ Christian

User information in SharePoint 2010 with help of the SPCWC control

In this post I’ll show you how you can retrieve something from the current user’s profile and then do something based of its value with a little help of jQuery and CSS. In this example I have used a typical AD field (office) that are imported into SharePoint’s profile information. You can use any field that exist as a property in the profile information like Country, manager, profile picture or even use a custom property in SharePoint.

workingInLondon

Let’s say we want display something at the Intranet for those users that works in London and display some other stuff for the one’s that works in Paris. This can be used in a many different scenarios, hide/show web parts, controls or fields in the page layout or maybe set a cookie based on the value or do something related to the branding, redirect users to different pages and much more. Hopes this example gives you some ideas for a cool implementation of your own!

Let’s try this out

Use SharePoint Designer 2010 and open the custom master page, your custom CSS file and your JS file.

Masterpage
First you need to declare SPCWC tag prefix in your custom master page. It’s just to include the following line for example just below the last existing tag prefix

<%@ Register Tagprefix="SPSWC" Namespace="Microsoft.SharePoint.Portal.WebControls" Assembly="Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

Then you need to load and make the profile properties available through the pages that are connected to your custom master page. This attribute is needed for some of the properties, but in this example you don’t need it. You can for example paste the following tag just below the existing WebPartPages:SPWebPartManager tag.

<SPSWC:ProfilePropertyLoader id="m_objLoader" LoadFullProfileOfCurrentUser="true" runat="server"/>

Finally it’s time to include the HTML somewhere in your custom master page including the profile property value.

<div class="Office">
<SPSWC:ProfilePropertyValue PropertyName="Office" ApplyFormatting="false" runat="server"/>
</div>
<div class="OfficeOutput IfOffice s4-notdlg"></div>

jQuery
Add the following script in an external JS file referenced from your master page.

$(document).ready(function(){	
var office = $('.Office > span').text();
if(office == 'Stockholm') {
$(".OfficeOutput").show().html('Working in Stockholm!');
}
else if(office == 'London') {
$(".OfficeOutput").show().html('Working in London!');
}
else {
// do something else
} 
});

CSS
Add the following CSS in an external CSS file referenced from your custom master page.

.Office > span{display:none}
.OfficeOutput{display:none}
.IfOffice{
padding:4px; background-color:#304F6D;
color:#fff; font-family:"Segoe UI"; font-size:8pt
}

That’s all, hopes this gives some ideas or inspiration. Please comment if you have questions or if just want to discuss this.
/ Christian

Summary of SharePoint Conference 2012

This time around I didn’t get lost too much in the large casinos. This was my third time In Vegas and I almost begin to feel like home in this city, not least because I have only been there in SharePoint business, so this place is for me a kind of SharePoint heaven with a lot of SharePoint fellow nerds more than a resort and gambling city. This year’s conference was as always great and it was in fact the largest SharePoint event ever with + 10,000 attendees and hundreds of sessions, hands on labs and a lot, exhibitions and of different social activities. Meet the Experts Besides of the sessions it’s the place for networking, to meet new as well as old friends from all over. This year I attended at the ‘Ask the experts’ at the Exhibit hall, at hands on labs, at dinners / parties so this days was overloaded with SharePoint in all shapes. The conference was well-organized and everything just worked as it should except for some technical issues regarding the Wi-Fi network and the Hands on labs. SharePoint 2013 – to the cloud Like what Ballmer said “For the cloud, where all in” – The keynote presenters delivered a clear message to the audience in tune with Microsoft’s cloud strategy – SharePoint 2013 is fully supported for the cloud and SharePoint is now built for allowing 90 days updates rather than product releases in three years intervals. For the credibility’s sake and to strengthen the message they used SharePoint Online for all demos in all sessions at least the one’s I attended. If I were to summarize this conference and SharePoint 2013 in three words it would be Cloud, Mobile and Social.

Spotlights from SPC12 & SharePoint 2013

The new App Model

One of the more interesting news is the new app model that gives us new options to build apps with JavaScript/jQuery & HTML5 and other languages for SharePoint and Office. Using the App model, code can live outside SharePoint and the implementation relies on protocols like OData & OAuth. The new App Model removes the requirement to develop in .Net server side code only and give us a new way to develop and integrate applications in the cloud. However, you can still take advantages of server side code, both farm and sandbox and in some scenarios this is the way to go. Take a look at MSDN library ‘Choose the right API set in SharePoint 2013’ for more information about this. However, I think the new App model will attract new types of developers and that we can expect new ideas coming in to SharePoint from new perspectives. SharePoint will for sure continues to evolve, can’t wait to see what comes out of this!

Yammer & Social

One of the main keys for the future of Microsoft and SharePoint is Social. Microsoft has recently bought Yammer for more than 1 billion dollar and this is because SharePoint as well as Office needs real social capabilities and Yammer fits well to Microsoft’s cloud, mobile and social strategies. The story has just begun and we will see deeper integrations of SharePoint and Yammer further on like shared identities and social flows. I think personally that this is just the right path to go for the future of SharePoint. To begin with Yammer will be a part of Office 365 including SharePoint Online for no extra cost, this is a really powerful combination of productivity and social services! Besides of Yammer, SharePoint 2013 have its own social set of Social features like sharing/following content, community features, micro blog and a more.

Web publishing and Enterprise content management

This is one of mine favorite areas in SharePoint, and there are several things that draws my attentions like:

  • Native support for HTML5/CSS3, what I have been waiting for this!
  • The new web part (CSWP) Content Search Web Part for cross site aggregation. It displays content that have been added to the search index and can for example display categories of a product in conjunction to managed navigation
  • Design manager that lets you create and import a set of branding files created outside SharePoint, this will simplify the branding process for pure web designers, no need for them to understand .net, master pages or page layouts
  • Device channels, now possibly to have multiple master pages per device.
  • Meta data driven navigation
  • Content authoring. A lot of new improvements for editors like Image renditions, better copy content from Word and new features for videos.
  • All the ‘under the hood’ investments like HTML rendering

Search

The search engine will simple provide the content that matches the query better than ever before and the narrowing and refinements functions will be the icing on the cake. FAST is now a part of the new improved search in SharePoint and it’s now the search engine that runs several functions in SharePoint like social, recommendations or analyzed user actions. The search works great just out of the box and are end user friendly but can be highly customized for specific needs. There’s several interesting features related to the search and if should pick just one it would be the ‘Continuous Crawl’ which means that changes in content can be reflected very quickly by the search result compared to incremental crawl engine.

SharePoint Designer & Branding

SharePoint Designer is still alive and you can do exactly the same branding and customization stuff that could be done before by SPD 2007/2010 but as you may know the design view/split view is gone by the new version. This means that it will be a harder for end users/business user to adopt SPD as a tool for branding and no code solutions, let’s hope the new possibilities with the new app model, VS LightSwitch or third part tools fills the gap for those users.

When it comes to branding, SharePoint have now a feature called Design Manager that let you convert standard HTML & CSS to a valid SharePoint master page. This means you can create the branding outside SharePoint with the tool of your choice. Note that you need the publishing feature enabled to use the design manager. When you need to create a ‘full SharePoint branding’ and you want to have full control of the markup or when you need to create a branding solution you still need SPD or Visual Studio in my point of view.

Another kid is the new Composite Looks, the new Theme engine in SharePoint 2013. This works really great when you need to add a custom look & feel with custom fonts and colors at a specific site. If you are coming to SharePoint Days 2012 – The Slovenian SharePoint conference next week, I’ll show you the highlights of branding in SharePoint 2013!

Stay in tune!
Christian

5 PowerShell snippets for SharePoint branders

Just as I wrote in my last blog post 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.

PowerShell is a command-line scripting tool that provides an administrator full access to applicable application programming interfaces (APIs), along with the ability to unlock the capability to interact directly with SharePoint 2010 Products to manipulate Web applications, site collections, sites, lists and much more. So what’s a useful thing to do with PowerShell as a SharePoint brander or a front end developer? Well, there are a lot of different types of tasks you can use PowerShell to, for example populate a list with a large amount of objects when you need to performance test your Data View Web Part or if you need to apply a theme to let’s say some site in the structure including its sub sites or if you need to batch update properties of a collection page layouts.

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. Take these snippets as they are, try them first in your developer or test environment and feel free to use them and modify in the way you want.

Running PowerShell scripts is easy and you will find many resources out there if you never used PowerShell before, when you know the basics it’s just to go ahead and try these out. This stuff is written for SharePoint 2010 but most of this can be used in SharePoint 2013 as it is.

1. Change Master Page for all sites in the collection

In this example I’ll apply a customer master to all the sites in the site collection, this can be rewritten specific for SharePoint foundation, where PowerShell is much useful for such task. In this snippet I have set V4.master, so have to change the name of the master page file if apply a custom master page.

# ----- For publishing sites and non publishing sites
$site = Get-SPSite http://intranet
foreach ($web in $site.AllWebs) {
$web; $web.CustomMasterUrl = "/_catalogs/masterpage/V4.master"; 
$web.Update(); $web.CustomMasterUrl;
$web.Dispose()
}
foreach ($web in $site.AllWebs) {
$web; $web.MasterUrl = "/_catalogs/masterpage/v4.master"; 
$web.Update(); $web.MasterUrl;
$web.Dispose()
}
$site.Dispose()
write-host "Complete! V4.master is now applied";

2. Set alternate CSS

In this way you can set a custom CSS file as an alternate CSS at the top site of your site collection, publishing sub sites will inherit the alternate CSS by default.

$web = Get-SPWeb http://intranet
$web.AlternateCssUrl = "/Style Library/MyStyles/main.css"
$web.AllProperties["__InheritsAlternateCssUrl"] = $True
$web.Update()

3. Set a site logo

With this one you can associate a logo with all sites in the site collection by entering the URL to an image file.

(get-spsite http://intranet).AllWebs | foreach {
$_.SiteLogoUrl = "/Style%20Library/MyClient/Images/ClientLogo.png";

4. Set regional setting/locale

This one can be handy when you need to specify the way the site displays numbers, dates, and time. In this example I set locale to Swedish (1053).

$site = Get-SPSite http://intranet
foreach ($web in $site.AllWebs) {
$web; $web.Locale = 1053; 
$web.Update(); $web.Locale;
$web.Dispose()
}
$site.Dispose() 

5. Set a theme

This one will set a theme to all sites in the site collection. This script is originally written by my friend MVP Yaroslav Pentsarskyy

$SiteUrl = "http://intranet"
$NewTheme = "Azure"
# Loading Microsoft.SharePoint.PowerShell 
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
# Setting site themes on sites and sub sites
$SPSite = Get-SPSite | Where-Object {$_.Url -eq $SiteUrl}
if($SPSite -ne $null) 
{
$themes = [Microsoft.SharePoint.Utilities.ThmxTheme]::GetManagedThemes($SiteUrl);
foreach ($theme in $themes) 
{ 
if ($theme.Name -eq $NewTheme) 
{ 
break; 
} 
} 
foreach ($SPWeb in $SPSite.AllWebs)
{
$theme.ApplyTo($SPWeb, $true); 
Write-Host "Set" $NewTheme "at :" $SPWeb.Title "(" $SPWeb.Url ")"
}
}
Write-Host "Themes updated at:" $SPSite.Url -foregroundcolor Green

More

If you’re a truly SharePoint Designer guy, why not use PowerShell to check if you allowed to do your branding stuff before fire it up…

Get-SPDesignerSettings -webapplication http://intranet

There’s lot of blogs about using PowerShell in SharePoint but here’s a pic of a few cool scripts that somehow are related to this topic.

N8Design Stefan Bauer – Hide fields from list forms using PowerShell

MSDN Samples Stefan Bauer – version cleanup in SharePoint

Gary Lapointe – Reset Theme

Finally I’d like to give thanks to MVP Cathy Dew for inspiring discussions about this topic; PowerShell from a brander’s perspective as well as I’d like to thanks Falak Mahmood for general discussions and suggestions for the use of PowerShell.

Stay in tune!
Christian

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

Use jQuery & cookies in SharePoint 2010

In this 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 doesn’t support cookies natively but you can use a super small plugin called ‘jquery.cookie.js’  that contains all kind of basic functions and options you’ll need for your scripting. This plugin is also included in jQuery UI development-bundle.

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

<!-- Session -->
<div class="Wrapper">
	<div class="Red">Red</div>
	<div class="Pipe">|</div>
	<div class="Green">Green</div>
</div>

jQuery
Put this in an external JS file referenced from your master page

$(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");
};

});

CSS
Put this in an external CSS file referenced from your master page

.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
}

Maybe you want to set the cookie to a life span of 2 days, take a look at the jQuery script and the part where you set the name and the property:

$.cookie('Wrapper-', 'Green-');

Just add a path and a value; a number or a specific date, this will create the cookie

$.cookie('Wrapper-', 'Green-', {path: '/', expires: 2});

Take a look at the cookie in your disk, if you are using IE, you will find it through this path

C:\Users\...\AppData\Local\Microsoft\Windows\Temporary Internet Files

The file will contain the name of the cookie, the property and the path like this

Wrapper-Green-ecmtest67/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

<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>

The jQuery goes here

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'})
})
});

If you prefer to use this in the ItemStyle.xsl and use it as a format for the Content Query web part, it works fine as well. If you want to take a look at a video of this, take a look here: http://youtu.be/kKEE_yktk8c

Hopes this give some ideas or inspiration for your cookie scripting adventures!
/ Christian

Follow

Get every new post delivered to your Inbox.

Join 912 other followers