Office 365 – Using jQuery with SharePoint Online
JavaScript, whether you love it or hate it, it’s here to stay. Now, JavaScript does have its quirks and irritations, especially if you’re used to managed code such as VB.Net or C#. However, despite the bad rep a lot of folks have given it, it is one heck of a powerful language.
If you’re like me, you like to get the job done. Sure, sure, it’s fun to dig into the code to see exactly how stuff is done, but that is not really an option when you have a deadline. That is why I choose to use jQuery when I need to liven up a web page or do some web programming magic.
JQuery was first released in 2006 and has since become one of the most popular JavaScript libraries on the web. Microsoft has thrown its weight behind it and now also provides developer support as well as adopting it in their AJAX and ASP.Net MVC frameworks.
So, how do we use all this jQuery goodness in SharePoint Online? That is what I hope to show you in today’s article where we’ll write a fairly simple SharePoint WebPart and add some jQuery logic to it.
Referencing jQuery from SharePoint
Before we can use jQuery in our SharePoint web part we need to find a way to reference the library. There are a few options available to us, of which one is to simply add a reference to the script via a Content Delivery Network (CDN). In the example below we’re referencing the jQuery library via Google’s CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
Using a content delivery network like Google’s is a great way to speed up your website as the chances are the user visiting your website has already visited a website that also references a library in the Google CDN and it is already in the users’ cache. To see a list of libraries available via the Google CDN, have a look at the Google Libraries API – Developer’s Guide.
Another option and the one we’ll be using for this example is to create a SharePoint document list to hold all your scripts. Create a new document library in SharePoint by selecting New Document Library from the Site Actions menu.
Name the library Scripts and click Create.
Next, we need to add the jQuery library file to the Scripts SharePoint library. Head over to https://jquery.com/ to download jQuery. Name the file jquery.js and upload it to the Scripts library. One benefit of storing your javascripts in a SharePoint list is that you can reuse it.
The nice thing about jQuery is that it has a whole host of community developed plug-ins, one of which is Hovercard. We’ll use this plugin to show more details about items in a SharePoint list called Books. Download Hovercard and also add it to the Scripts SharePoint library.
Creating the SharePoint WebPart
With the jQuery library and Hovercard plugin file uploaded, let’s create a new Empty SharePoint Project in Visual Studio 2010. Today we will not use the “ADX SharePoint Ribbon” project template because our Ribbon Designer for SharePoint and Office 365 would add a new SharePoint feature already containing ribbon while we need a new empty project.
Select a local SharePoint site for debugging and make sure to select Deploy as a sandboxed solution.
Next, add a Visual Web Part (Sandboxed) item to your project. If you don’t see the Web Part (Sandboxed) item, you need to install the Visual Studio 2010 SharePoint Power Tools.
We won’t add any visual controls to our web part, but we’ll do everything in mark-up. The entire code listing for the Visual Web Part is as follows:
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %> <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Import Namespace="Microsoft.SharePoint" %> <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="jQueryWebPart.ascx.cs" Inherits="jQueryAndSP.jQueryWebPart.jQueryWebPart" %> <script src="../Scripts/jquery.js" type="text/javascript"></script> <script src="../Scripts/hovercard.js" type="text/javascript"></script> <h2> Books</h2> <div id="books"> </div> <script type="text/javascript"> ExecuteOrDelayUntilScriptLoaded(LoadList, "sp.js"); function LoadList() { var context = new SP.ClientContext.get_current(); var web = context.get_web(); var bookList = web.get_lists().getByTitle('Books'); var query = SP.CamlQuery.createAllItemsQuery(); allItems = bookList.getItems(query); context.load(allItems, 'Include(Title,Synopsis)'); context.executeQueryAsync(Function.createDelegate(this, this.ListRetrieved), Function.createDelegate(this, this.RetrievalFailed)); } function ListRetrieved() { var listEnumerator = this.allItems.getEnumerator(); var count = 1; while (listEnumerator.moveNext()) { var currentItem = listEnumerator.get_current(); var id = 2; var title = currentItem.get_item('Title'); var synop = currentItem.get_item('Synopsis'); $("#books").append('<div id="book-"' + count + ' class="book" title="' + synop + '">' + title + '</div><br/><br/>'); count++; } $('.book').each(function () { var synop = $(this).attr("title"); $(this).hovercard({ detailsHTML: "<div><p>" + synop + "</p></div>", width:400 }); }); } function RetrievalFailed(sender, args) { alert("Could not retrieve list:" + args.get_message()); } </script>
In the code above we referenced the jQuery and the Hovercard files we’ve added to our Scripts document library earlier. The ExecuteOrDelayUntilScriptLoaded method is a built-in SharePoint method, which will execute the specified function only after, in this case the sp.js javascript file, is loaded. SP.js is a javascript library that gives us access to the SharePoint client object model.
The LoadList function retrieves all items from the Books SharePoint list and the ListRetrieved function loops through all the list items and appends the values, using jQuery, to the books Div.
Finally, we loop through each html element that has a class name containing the word book and add a Hovercard to it with the elements’ title attribute as the Hovercards’ detailsHTML.
Packaging and deploying to Office 365 SharePoint Online
Once everything is tested you can package the SharePoint solution by selecting Package from the Visual Studio Build menu. This will create a .wsp file in your projects’ bin folder. Check your Output window for the full path to the file if you’re not sure.
Next, log into your Office 365 SharePoint Online account, and click on the Site Actions > Site Settings menu item.
Next, click on the Solutions link under the Galleries heading.
Click on the Upload Solution button on the Solution tab:
Select and upload the .wsp file and click OK. When prompted activate your solution by clicking on the Activate button.
Navigate to a SharePoint page, and insert the jQuery web part we’ve just uploaded.
Once you’re finished editing the page, and the page loads, it will display a list of all the items in the SharePoint Books list. When you hover the mouse cursor over a book title it will display the books’ synopsis:
Thank you for reading. Until next time, keep coding!
15 Comments
Hello,
I would like to know, is it possible to upload file using c# code?
If yes, what is the best practice?
Thank you for you answers.
Hi there,
Yes, it is possible to upload files to Sharepoint using C#. Please check out my blog post Office 365 – Save Outlook e-mails & attachments to SharePoint Online programmatically
Hope this helps! Thanks for your comment.
Hello,
I’m beginner of SharePoint. (Install-and using day : just two days)
First, I live in South Korea, I can’t understand English well.
I tried your posting and Well-maked webpart.
but can’t bring data ‘Books’.
I can’t understand ‘Books’ Object. What is this?
then I Making the ‘Books’ page in Library, Can’t bring Column Title and Synopsis.
What’s problem?
Thank you for you answers.
Hi Mordekai,
Thanks for your comment.
The Books object is a SharePoint List, you need to add the Title and Synopsis columns to this list if it does not already have it.
Hope this answers your question.
Kind regards,
Pieter
Thanks, Pieter.
My SharePoint2010 Language is Korean.
but Finally, I Created Books object.
and,
var title = currentItem.get_item(‘Title’);
var synop = currentItem.get_item(‘Synopsis’);
alert(title);
alert(synop);
i tried this script.
‘title’ is Correctly data.
But, ‘synop’ bring this data.
Alert message : this is TEST BOOK
ooops.
cracked [$(“#books”).append(”)] in HTML language.
I need Help!
*Internet Explorer 8.0 ver is not showing Title and Hovering area.
* oooops, html code is deleted!
Alert message : (div class=”ExternalClassE12D6QGA6AC221SEC”)(b) this is TEST BOOK (/b)(/div)
lol,
Success!
var title = currentItem.get_item(‘Title’);
var synop = currentItem.get_item(‘Synopsis’);
var syn = synop.toString().split(“>”);
synop = syn[2].replace(“</p", "");
$("#books").append('’ + title + ”);
Hi Mordekai,
Thank you for your comments!
It looks like you have found the answer. Am I right? Could you please confirm?
Hi to all,
I am using the same proedure created locally sandbox solution and packaging in to the office 365 online.but i am not able to find that in the office 365 which is working in the lical site perfectly….
Thank you.
Hi,
I got the answer for my issue that why i am not getting my sandboxes visual web part.
When i added my visual web part in new project there some “usercontrol.ascx.g.cs” file is missing.
because of this i am not getting my solution.
Please any one tell me why its happens and relation of that file with the visual web part.
Hi Udaya,
The ascx.g.cs file is a designer file that is created by Visual Studio. Please have a look at the following pages, this problem is rather common:
SharePoint Web Part with Custom User Control – ascx.g.cs is cleared
SharePoint 2010 Visual Web Parts Missing .ascx.g.cs In Visual Studio 2012
Sand boxed Visual webpart
So, it seems to be a bug in Visual Studio, you can try to open a new case at the Microsoft Connect web-site.
Thank you very much for our reply…..
sorry for mistake your reply*
You have deploy jquery library to document library like style library and refer it from there. You can use CDN too if you prefer to do so.
Hi Uriah,
Yes that is another option, I’ve mentioned in the article.