recipe.jpg

Adding jQuery to SharePoint

Options, Options, Options

As I research and learn more about SharePoint programming, I occasionally come across blog posts that start with titles like “the best way…” or “the correct way…” to accomplish a certain task. If there’s anything I’ve learned with SharePoint along the way, it’s that there is rarely one correct and proper way of doing things; rather, there are usually a variety of approaches, each with its own pros and cons. To that end, this post attempts to document some of the ways one might include jQuery in a SharePoint site.

Note that this article isn’t intended to be a tutorial for jQuery (click here to learn more about jQuery). The presumption is that you’re reading this because you already know something about the power of jQuery and you wish to unleash that power in the context of SharePoint 2010. Also, note that I’m not trying to document every single way this problem can be solved; I’m just serving up some recipes that have worked for me. In addition, this article assumes that you already have some knowledge about SharePoint programming (such as using Visual Studio 2010 to create SharePoint projects). Finally, note that the demos below assume that you have Visual Studio 2010 and that you’re working against a Team Site.

A Fork in the Road

As Yogi Berra is alleged to have said, “If you see a fork in the road… take it!” In our case, there are several forks in the road:

  1. Do you need to include jQuery for the majority of the pages in a site, or just for one or two?
  2. Where do you need to use jQuery (i.e. in a Visual Web Part, on an Application Page, on a Site Page)?
  3. Will you be working with a Sandboxed Solution?

The answers to these questions will influence which of the following recipes will work for you.

Recipe 1: Loading jQuery from a Document Library with a Custom Action

This approach is useful when you need to have jQuery available to most or all of the pages in a site. It is also useful in the scenario where you’re working in a Sandboxed Solution, since such solutions cannot store files in the SharePoint Root (or “14 hive”). Additionally, it is useful in that .js files stored in a document library can be easily maintained without administrator intervention.

On the downside, storing .js files in a library means they could accidentally or intentionally be deleted or changed, resulting in improper functioning of the application.

This recipe also includes a small bit of custom jQuery code that will be included on each page for demonstration.

1. Create a Visual Studio 2010 Empty SharePoint Project (either Farm Solution or Sandboxed Solution).

2. Add a Module named DeployJQuery; delete the sample.txt file and add your jQuery file to the module.

DeployJQuery Module

3. Modify the Elements.xml file for the DeployJQuery module as follows (note that all line numbers are provided for convenience only, and should not be included in source):

<xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="DeployJQuery">
<File Path="DeployJQuery\jquery-1.6.4.js"&nbsp;Url="SiteAssets/jquery-1.6.4.js" />
</Module>
</Elements>

4. Add a second Module named DeployCustomJS; rename the sample.txt file to Custom.js.

5. Modify the contents of the Custom.js file:

$(document).ready(function () {
$('.static.menu-item').mouseover(function () {
$(this).fadeTo("fast", 0.33);
$(this).fadeTo("fast", 1);
});
});

6. Modify the Elements.xml for the DeployCustomJS module as follows:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="DeployCustomJS">
<File Path="DeployCustomJS\Custom.js" Url="SiteAssets/Custom.js" />
</Module>
</Elements>

7. Add an Empty Element named LoadJQuery and then modify its Elements.xml file as follows:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction Id="BlogSample.LoadJQuery" ScriptSrc="~site/SiteAssets/jquery-1.6.4.js"
Location="ScriptLink" Sequence="10020" />
</Elements>

8. Add a second Empty Element named LoadCustomJS; modify its Elements.xml to match the following:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction Id="BlogSample.Script"
ScriptSrc="~site/SiteAssets/Custom.js"
Location="ScriptLink" Sequence="10030" />
</Elements>

9. Deploy the project.

10. Navigate to the site. As you float your mouse over the menu items in the quick-launch menu you should see them pulse from solid to opaque to solid.

Recipe 2: Loading jQuery from SharePoint Root using ScriptLink Control

This is useful when you’re using jQuery on an application page or a Visual Web Part; both can easily be configured to use one or more ScriptLink controls.

Obvious limitations include: jQuery is only made available to one page at a time; use of ScriptLink control is limited to certain kinds of pages; and deployment of files to SharePoint root precludes the use of this technique for Sandboxed Solutions.

1. Create a new Farm Solution in Visual Studio 2010.

2. Add a new SharePoint mapped folder to the project; the mapped folder should point to {SharePointRoot}\Template\LAYOUTS\1033.

3. Underneath the mapped folder create a new mapped folder with the same name as your project (in my case, Recipe2 is the name of the sample project). You can see the results below:

4. Deploy the project (this is done here so the ScriptLink control won’t produce an error on a later step when you try to use the .js file).

5. Add a Visual Web Part to the project and name it jQueryPart.

6. Add a ScriptLink control to the web part (see source below). Set the ScriptLink’s Name property to <projectname>/jquery-1.6.4.js (where <projectname> is the name of the folder you created in step 3 above).

<SharePoint:ScriptLink ID="ScriptLinkJQuery" runat="server"
Name="Recipe2/jquery-1.6.4.js" />

7. Add the following markup to the web part just below the ScriptLink:

<script type="text/javascript">
var colors = ['lime', 'aqua', 'orange'];
var i = 0; $(document).ready(function () {
$('#sample').css('background-color', colors[i]);
$('#sample').click(function () {
i++;
if (i >= colors.length) { i = 0; }
$(this).css('background-color', colors[i]);
});
});
</script>

<span id="sample" style="cursor: pointer"> Click me </span>

8. Deploy the project.

9. Navigate to the site and then navigate to the Site Pages library.

10. Add a new page named jQueryTest.

11. On the jQuery test page click Insert tab | Web Part | Custom | jQueryPart; then click the Add button to place the part on the page as follows:

12. Click the Save and Close button to save your changes.

13. Click the “Click me” text and observe the color change.

Recipe 3: Loading jQuery from a Content Delivery Network (CDN) using the Content Editor web part

This approach is beneficial when you only need to use jQuery on one or a small number of site pages (both Wiki and Web Part Pages). It is also advantageous in that it does not require storing any extra files on the SharePoint server: the jQuery source is loaded from a Content Delivery Network while the jQuery code that you author is embedded directly into the page itself. Additionally, this solution doesn’t violate any of the tenets of Sandboxed Solutions.

Obviously this isn’t a useful approach for site-wide jQuery needs. Also, there may be some rare cases where you can’t accomplish what you want with this approach because the jQuery links and source are placed down within the document as opposed to the preferred approach of locating script in the <head> section of the HTML markup.

1. Navigate to the site pages library and add a new page named jQueryContent.

2. Add a Content Editor Web Part to the page.

3. Edit the Content Editor Web Part and click on the “Click Here to add new content” link.

4. On the Ribbon select HTML | Edit HTML Source.

5. In the Edit HTML Source dialog enter the following markup and then click OK:

<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> </script> <script language="javascript" type="text/javascript">
$(document).ready(function() { alert("jQuery"); });
</script>

6. Click OK to stop editing web part, then click Save and Close button.

7. The page should now display a popup as follows:

What about Master Pages?

One can certainly embed the needed jQuery references directly in a master page, using either a ScriptLink control or a simple <script> tag. However, I’ve chosen not to focus on that approach simply because I’m inclined to view modifying the Master Page as something I don’t want to do unless I absolutely must. If you’ll be changing the Master Page as a part of a bigger branding solution then it certainly makes sense to embed jQuery there; otherwise, Recipe 1 above will give you similar site-wide functionality in what is perhaps an easier and safer way.

Learning to be a great cook

One of the attributes of a great cook is the ability to synthesize ingredients to come up with something new and delicious. The same can be said of these SharePoint recipes. For example, the use of a Content Delivery Network to serve up jQuery isn’t limited to just one recipe. Experience and experimentation will allow you to find the mix of ingredients that works best for your masterpiece.

Careful not to burn yourself…

There are always hazards when cooking: hot stoves, sharp knives, and dropped pans. Likewise there are hazards involved in integrating jQuery with SharePoint, including the following:

  • The risk that some other developer would introduce their own jQuery solution, resulting in a possible conflict of versions or files.
  • Failure to test thoroughly resulting in erratic behavior in the SharePoint UI.
  • The lack of Microsoft providing an “officially sanctioned” approach to introducing jQuery into SharePoint means that any introduction of jQuery involves a certain amount of wizardry.

Hazards notwithstanding, the power of jQuery makes it a compelling option for customizing and enhancing the SharePoint UI.

John UnderwoodAdding jQuery to SharePoint
Share this post

7 comments

Join the conversation
  • rohan - February 4, 2012 reply

    Nice article. A correction is required in Recipe1. you cannot use “ScriptSrc=”~site/SiteAssets/jquery-1.6.4.js”” in the custom actions menu. In “ScriptSrc” only locations within the _layouts folder can be specified. Please refer the below article.

    http://weblogs.asp.net/jan/archive/2010/03/01/scriptsrc-referencing-javascript-files-with-sharepoint-2010-custom-actions.aspx

  • John Underwood - February 4, 2012 reply

    Thanks for the comment, Rohan

    I do actually have a copy of Recipe1 working in my SharePoint development environment. The sample you see is taken directly from that environment. The key is using the ~site prefix on the relative URL for ScriptSrc to resolve to the correct location.

    See the “Url Tokens for Custom Actions” section in this article for more details: http://msdn.microsoft.com/en-us/library/ms458635.aspx

  • Marc Grabow - April 19, 2012 reply

    Hi John, I used Recipe 1 and it worked straight away due to your detailed explanation. Thanks a lot!

    John Underwood - April 19, 2012

    Great, glad to hear it was helpful!

  • Martinez Fulcher - May 4, 2012 reply

    John,

    Thanks so much for this… unfortunately I don’t have access to Sharepoint Designer at the moment because my company requires that we go through a class which hasn’t even been offered in my area. Right now my only option is to add Jquery to a CEWP… do you think the same procedure could be used to access Jquery UI? I would really like to add an accordion view where I need it and possibly tabs, etc.

    John Underwood - May 8, 2012

    I haven’t tried that approach, so I can’t say for certain. I did find a thread on StackOverflow that might help… check it out and see if it addresses your question: http://stackoverflow.com/questions/488194/deploy-jquery-using-a-sharepoint-feature-or-physical-files

    BTW, thanks for reading the blog!

Join the conversation

Related Posts