SEF 2012 - A jQuery Primer for Sharepoint

76
A jQuery Primer for SharePoint Marc D Anderson Co-Founder & President Sympraxis Consulting LLC [email protected]

description

These are the slides from my two sessions at the SharePoint and Exchange Forum 2012 (SEF12 - http://seforum.se) in Stockholm, Sweden on October 23, 2012. A jQuery Primer for SharePoint: Overview, jQuery and CSS, and Selectors Developer, level 200 jQuery is a JavaScript framework that allows you to develop great client side solutions. If you've been meaning to learn jQuery but haven't found the time, come to this introductory session where we'll cover some of the important basics of jQuery in a SharePoint context. Understanding how jQuery relates to CSS and JavaScript is an important hurdle in the learning curve. Selectors are the key concept you need to understand to be able to work with SharePoint’s pages. By the end of this session, you'll understand what jQuery is and how to start adding it to your SharePoint solutions. A jQuery Primer for SharePoint: Attributes, Traversing, Manipulation, Events, and Effects Developer, level 200 Once you know how to start working with jQuery, you’ll want to be able to change what happens in the page by querying existing elements and adding new behaviors. In this session, we’ll look at Attributes, Traversing, Manipulation, Events, and Effects. This will get you to the point where you can roll up your sleeves and start creating solutions. We’ll also look at using plugins like SPServices to make your work easier. Both sessions are based on my articles at SharePoint Magazine.

Transcript of SEF 2012 - A jQuery Primer for Sharepoint

Page 1: SEF 2012 - A jQuery Primer for Sharepoint

A jQuery Primer for SharePoint

Marc D AndersonCo-Founder & PresidentSympraxis Consulting [email protected]

Page 2: SEF 2012 - A jQuery Primer for Sharepoint

What is jQuery?

is

Page 3: SEF 2012 - A jQuery Primer for Sharepoint

GETTING STARTED

Page 4: SEF 2012 - A jQuery Primer for Sharepoint

Getting Started

• Add references to the jQuery library– Master page– Page layout– Individual aspx pages

Page 5: SEF 2012 - A jQuery Primer for Sharepoint

<!-- Reference the jQueryUI theme's stylesheet on the Google CDN. Here we're using the "start" theme --><link type="text/css" rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/start/jquery-ui.css" /><!-- Reference jQuery on the Google CDN --><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script><!-- Reference jQueryUI on the Google CDN --><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script><!-- Reference SPServices on cdnjs (Cloudflare) --><script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.2/jquery.SPServices-0.7.2.min.js"></script>

Referencing Script Libraries from CDNs

More:http://sympmarc.com/2012/04/20/referencing-jquery-jqueryui-and-spservices-from-cdns/

Page 6: SEF 2012 - A jQuery Primer for Sharepoint

• HTML– Hypertext Markup Language– Content and structure

• CSS– Cascading Style Sheets– Presentation and style

• JavaScript and jQuery– Interactive behavior

SharePoint Web Technology

Page 7: SEF 2012 - A jQuery Primer for Sharepoint

HTML Elements

Powered by <a href="http://office365.com">Office365</a>.

Opening tag Closing tag

Attribute Value

Page 8: SEF 2012 - A jQuery Primer for Sharepoint

INTRO TO CSS

Page 9: SEF 2012 - A jQuery Primer for Sharepoint

• CSS = Cascading Style Sheets• jQuery uses selectors that are very

similar to CSS selectors• CSS is the fundamental styling

mechanism for the Web• HTML + CSS + jQuery = AWESOME

Intro to CSS:Why does CSS matter?

Page 10: SEF 2012 - A jQuery Primer for Sharepoint

CSS Styles

.article { color: red;}

Select HTML element(s)

Modify them!

Page 11: SEF 2012 - A jQuery Primer for Sharepoint

CSS Element Selectors

<p>

Paragraph of

text.

</p>

p {

color:

red;

}

Paragraph of text.

Page 12: SEF 2012 - A jQuery Primer for Sharepoint

CSS Class Selectors

<div

class="article">

This is an

article.

</div>

.article {

color: red;

}

This is an article.

Page 13: SEF 2012 - A jQuery Primer for Sharepoint

CSS ID Selectors

<div id="header">

This is a header.

</div>

#header {

color: red;

}

This is a header.

Page 14: SEF 2012 - A jQuery Primer for Sharepoint

CSS Descendant Selectors

<div id="header"> <h1> This is a header. </h1></div>

#header h1 {

color: red;

}

This is a header.

Page 15: SEF 2012 - A jQuery Primer for Sharepoint

CSS Composite Selectors<div id="header">

<ul class="top-nav">

<li>Item 1</li>

<li>Item 2</li>

<li>Item 3</li>

</ul>

</div>

#header ul.top-nav li {

color: red;

}

• Item 1

• Item 2

• Item 3

Page 16: SEF 2012 - A jQuery Primer for Sharepoint

CSS Complex Selectors<ul class="top-nav"> <li>Item 1</li> <li> Item 2 <ul class="menu"> <li>Menu 1</li> </ul> </li></ul>

ul.top-nav > li

{

color: red;

}

• Item 1

• Item 2

• Menu 1

Page 17: SEF 2012 - A jQuery Primer for Sharepoint

• Use truly unique class and id names• Choose a prefix for your project, e.g.

‘xyz-’ or ‘x51-’• All of your classes and ids will be easy

to select:xyz-home-page-articlex51-top-section

• Don’t be afraid of verbose class and ID names!

My CSS "Best" Practices

Page 18: SEF 2012 - A jQuery Primer for Sharepoint

DOCUMENT OBJECT MODEL (DOM)

Page 19: SEF 2012 - A jQuery Primer for Sharepoint

• The DOM starts as the page’s markup (HTML) as delivered to the browser by the server: View Source

• Styled by the CSS which gives the page its look and feel

• The DOM is acted upon by any script in the page

What is the Document Object Model (DOM)?

Page 20: SEF 2012 - A jQuery Primer for Sharepoint

• Add or remove CSS classes• Create new HTML elements• Remove HTML elements• Change HTML element attributes• And so much more

What Can We Do With the DOM?

The DOM is HTML, which is XML, which is data!

Page 21: SEF 2012 - A jQuery Primer for Sharepoint

IMPORTANT TOOLS

Page 22: SEF 2012 - A jQuery Primer for Sharepoint

• Shows the Internet Explorer view of the DOM in SharePoint’s pages – some pages and controls are rendered differently in other browsers

Internet Explorer Developer Tools (F12)

Page 23: SEF 2012 - A jQuery Primer for Sharepoint

• Better for debugging and looking at Net traffic

The Firebug Add-On for Firefox

Page 24: SEF 2012 - A jQuery Primer for Sharepoint

JQUERY BASICS

Page 25: SEF 2012 - A jQuery Primer for Sharepoint

The Basic Idea of jQuery

$('.article').hide();

Select something

Do something!

Page 26: SEF 2012 - A jQuery Primer for Sharepoint

$(document).ready(function({ // do something});

• Processing is suspended until the page’s DOM is fully loaded

• Ensures that all of the elements you need are available

jQuery’s Document Ready

Page 27: SEF 2012 - A jQuery Primer for Sharepoint

• The jQuery documentation is arranged to help you

• What you need to know is arranged sequentially from top to bottom

jQuery Documentation: Your Friend

Page 28: SEF 2012 - A jQuery Primer for Sharepoint

SELECTORS

Page 29: SEF 2012 - A jQuery Primer for Sharepoint

• Selectors are the most important jQuery concept

• Selecting the right DOM object(s) is half the battle

• Selectors return a collection of DOM objects – 0 to n matching elements

jQuery Selectors

Page 30: SEF 2012 - A jQuery Primer for Sharepoint

jQuery Element Selectors

$("p")

<p>

Paragraph of

text.

</p>

Page 31: SEF 2012 - A jQuery Primer for Sharepoint

jQuery Element Selectors

var allParagraphs = $("p");

<p>Paragraph 1 of text.</p><p>Paragraph 2 of text.</p>

allParagraphs is now defined as a jQuery object which contains pointers to all of the paragraphs in the page

Page 32: SEF 2012 - A jQuery Primer for Sharepoint

jQuery Class Selectors

$(".article")

<div class="article"> This is an article.</div>

Page 33: SEF 2012 - A jQuery Primer for Sharepoint

jQuery ID Selectors

$("#header")

<div id="header"> This is a header.</div>

Page 34: SEF 2012 - A jQuery Primer for Sharepoint

jQuery Descendant Selectors

$("#header h1")

<div id="header"> <h1> This is a header. </h1></div>

Page 35: SEF 2012 - A jQuery Primer for Sharepoint

jQuery Composite Selectors

$("#header ul.top-nav li")

<div id="header"> <ul class="top-nav"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul></div>

Page 36: SEF 2012 - A jQuery Primer for Sharepoint

jQuery Complex Selectors

$("#header ul.top-nav ul.menu

li")

<div id="header"> <ul class="top-nav"> <li>Item 1</li> <li> Item 2 <ul class="menu"> <li>Menu 1</li> </ul> </li> </ul></div>

Page 37: SEF 2012 - A jQuery Primer for Sharepoint

Selectors for SharePoint<DIV id=ctl00_PlaceHolderLeftNavBar_QuickLaunchNavigationManager class=ms-quicklaunch-navmgr> <DIV> <DIV id=zz18_V4QuickLaunchMenu class=s4-ql> <DIV class="menu vertical menu-vertical"> <UL class="root static"> <LI class=static> <A class="static menu-item" href="/sitename/_layouts/viewlsts.aspx?BaseType=1">

$("div.ms-quicklaunch-

navmgr")

Page 38: SEF 2012 - A jQuery Primer for Sharepoint

Selectors for SharePoint

$

("#ctl00_PlaceHolderLeftNavBar_QuickLaunchNavigationMana

ger")

<DIV id=ctl00_PlaceHolderLeftNavBar_QuickLaunchNavigationManager class=ms-quicklaunch-navmgr> <DIV> <DIV id=zz18_V4QuickLaunchMenu class=s4-ql> <DIV class="menu vertical menu-vertical"> <UL class="root static"> <LI class=static> <A class="static menu-item" href="/sitename/_layouts/viewlsts.aspx?BaseType=1">

Page 39: SEF 2012 - A jQuery Primer for Sharepoint

Selectors for SharePoint

$(".ms-quicklaunch-navmgr a.static.menu-item")

<DIV id=ctl00_PlaceHolderLeftNavBar_QuickLaunchNavigationManager class=ms-quicklaunch-navmgr> <DIV> <DIV id=zz18_V4QuickLaunchMenu class=s4-ql> <DIV class="menu vertical menu-vertical"> <UL class="root static"> <LI class=static> <A class="static menu-item" href="/sitename/_layouts/viewlsts.aspx?BaseType=1">

Page 40: SEF 2012 - A jQuery Primer for Sharepoint

• .NET Applications like SharePoint generate some long and ugly markup and IDs• These selector tricks really help$("[id='foo']"); // Equal to$("[id!='foo']"); // Not equal to$("[id^='foo']"); // Starts with$("[id$='foo']"); // Ends with$("[id*='foo']"); // Contains$("[id~='foo']"); // Contains word$("[id|='foo']"); // Contains prefix$("[id]"); // Has$("[id][class][style]"); // Has all

Useful jQuery Selector Tricks

Page 41: SEF 2012 - A jQuery Primer for Sharepoint

NEXT SESSION AT 12:50

A jQuery Primer for SharePoint: Attributes, Traversing, Manipulation, Events, and Effects

Page 42: SEF 2012 - A jQuery Primer for Sharepoint

ATTRIBUTES

Page 43: SEF 2012 - A jQuery Primer for Sharepoint

• Once you’ve selected the right DOM element, you can use jQuery to get or set its attributes

• As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes

jQuery Attributes

Page 44: SEF 2012 - A jQuery Primer for Sharepoint

jQuery Attributes: Get and Set

GET: var thisClass = $

("#helloDiv").attr("class");

SET: $("#helloDiv").attr("class", "ms-

hidden");

<div id="helloDiv" class="ms-bold"> Hello, world! </div>

Page 45: SEF 2012 - A jQuery Primer for Sharepoint

Example with SharePoint Attributes: Get

<DIV id=ctl00_PlaceHolderLeftNavBar_QuickLaunchNavigationManager class=ms-quicklaunch-navmgr> <DIV> <DIV id=zz18_V4QuickLaunchMenu class=s4-ql> <DIV class="menu vertical menu-vertical"> <UL class="root static"> <LI class=static> <A class="static menu-item" href="/sitename/_layouts/viewlsts.aspx?BaseType=1">

var thisHref = $(".ms-quicklaunch-navmgr a.static.menu-

item:first")

.attr("href");

Page 46: SEF 2012 - A jQuery Primer for Sharepoint

Example with SharePoint Attributes: Set

<DIV id=ctl00_PlaceHolderLeftNavBar_QuickLaunchNavigationManager class=ms-quicklaunch-navmgr> <DIV> <DIV id=zz18_V4QuickLaunchMenu class=s4-ql> <DIV class="menu vertical menu-vertical"> <UL class="root static"> <LI class=static> <A class="static menu-item" href="/sitename/mypage.aspx">

$(".ms-quicklaunch-navmgr a.static.menu-item:first")

.attr("href", "/sitename/mypage.aspx");

Page 47: SEF 2012 - A jQuery Primer for Sharepoint

TRAVERSING

Page 48: SEF 2012 - A jQuery Primer for Sharepoint

• Traversing lets you move around the DOM based on your initial selection

• This is how you get at elements which are difficult to select directly

• Ancestry matters in XML / HTML

Traversing

Page 49: SEF 2012 - A jQuery Primer for Sharepoint

Find an Element’s Ancestors<div id="helloDiv" class="ms-bold"> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul></div>

$("ul").parent();

$("ul").closest("div");=

Page 50: SEF 2012 - A jQuery Primer for Sharepoint

Traversing Down:Initial Selector

<DIV class=ms-quicklaunchheader>   <A accessKey=3 id=ctl00_PlaceHolderLeftNavBar_idNavLinkViewAll href="/Intranet/JQueryLib/_layouts/viewlsts.aspx">     View All Site Content   </A> </DIV>

$("div.ms-quicklaunchheader").find("a");

Page 51: SEF 2012 - A jQuery Primer for Sharepoint

Traversing Down:Finding Specific Children

<DIV class=ms-quicklaunchheader>   <A accessKey=3 id=ctl00_PlaceHolderLeftNavBar_idNavLinkViewAll href="/Intranet/JQueryLib/_layouts/viewlsts.aspx">     View All Site Content   </A> </DIV>

$("div.ms-quicklaunchheader").find("a");

Page 52: SEF 2012 - A jQuery Primer for Sharepoint

Traversing Up:Initial Selector

$("a[id$='NavLinkViewAll']").parent();

<DIV class=ms-quicklaunchheader>   <A accessKey=3 id=ctl00_PlaceHolderLeftNavBar_idNavLinkViewAll href="/Intranet/JQueryLib/_layouts/viewlsts.aspx">     View All Site Content   </A> </DIV>

Page 53: SEF 2012 - A jQuery Primer for Sharepoint

Traversing Up:Finding Specific Ancestors

<DIV class=ms-quicklaunchheader>   <A accessKey=3 id=ctl00_PlaceHolderLeftNavBar_idNavLinkViewAll href="/Intranet/JQueryLib/_layouts/viewlsts.aspx">     View All Site Content   </A> </DIV>

$("a[id$='NavLinkViewAll']").parent();

Page 54: SEF 2012 - A jQuery Primer for Sharepoint

Traversal Example from SPServices

Page 55: SEF 2012 - A jQuery Primer for Sharepoint

Traversal Example from SPServices

<select name="ctl00$m$g_e845e690_00da_428f_afbd_fbe804787763$ctl00$ctl04$ctl07$ctl00$ctl00$ctl04$ctl00$ctl00$SelectResult" title="City selected values" id="ctl00_m_g_e845e690_00da_428f_afbd_fbe804787763_ctl00_ctl04_ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_SelectResult" style="width: 162px;" onkeydown="GipHandleHScroll(event)" ondblclick="GipRemoveSelectedItems(ctl00_m_g_e845e690_00da_428f_afbd_fbe804787763_ctl00_ctl04_ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_MultiLookupPicker_m); return false" onchange="GipSelectResultItems(ctl00_m_g_e845e690_00da_428f_afbd_fbe804787763_ctl00_ctl04_ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_MultiLookupPicker_m);" size="20" multiple="">

<select name="ctl00$m$g_e845e690_00da_428f_afbd_fbe804787763$ctl00$ctl04$ctl07$ctl00$ctl00$ctl04$ctl00$ctl00$SelectCandidate" title="City possible values" id="ctl00_m_g_e845e690_00da_428f_afbd_fbe804787763_ctl00_ctl04_ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_SelectCandidate" style="width: 162px;" onkeydown="GipHandleHScroll(event)" ondblclick="GipAddSelectedItems(ctl00_m_g_e845e690_00da_428f_afbd_fbe804787763_ctl00_ctl04_ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_MultiLookupPicker_m); return false" onchange="GipSelectCandidateItems(ctl00_m_g_e845e690_00da_428f_afbd_fbe804787763_ctl00_ctl04_ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_MultiLookupPicker_m);" size="350" multiple="">

Page 56: SEF 2012 - A jQuery Primer for Sharepoint

Traversal Example from SPServices

var possibleValues = $("select[ID$='SelectCandidate'][Title^='" + opt.multiSelectColumn + " ']");var selectedValues = possibleValues.closest("span").find("select[ID$='SelectResult'][Title^='" + opt.multiSelectColumn + " ']");

SelectCandidate SelectResult

Page 57: SEF 2012 - A jQuery Primer for Sharepoint

MANIPULATION

Page 58: SEF 2012 - A jQuery Primer for Sharepoint

• Once you’ve gotten the right element(s), you can:– Manipulate their attributes or

properties– Change their contents– Move them in the DOM

Manipulation

Page 59: SEF 2012 - A jQuery Primer for Sharepoint

Manipulation:Adding Text

<div id="helloDiv" class="ms-bold">   Hello, world! </div>

$("#helloDiv").append(" And you're welcome to it!");

<div id="helloDiv" class="ms-bold">   Hello, world! And you're welcome to it!</div>

Page 60: SEF 2012 - A jQuery Primer for Sharepoint

Manipulation:Adding CSS Classes

<div id="helloDiv" class="ms-bold">   Hello, world! </div>

$("#helloDiv").addClass("my-class");

<div id="helloDiv" class="ms-bold my-class">   Hello, world! </div>

Page 61: SEF 2012 - A jQuery Primer for Sharepoint

Manipulation:Wrapping Elements

<div id="helloDiv" class="ms-bold">   Hello, world! </div>

$("#helloDiv") .wrap("<a href='http://cnn.com'></a>");

<a href="http://cnn.com"> <div id="helloDiv" class="ms-bold">

  Hello, world! </div></a>

Page 62: SEF 2012 - A jQuery Primer for Sharepoint

Manipulation:Inserting Elements

<div id="helloDiv" class="ms-bold">   Hello, world! </div>

$("#helloDiv") .before("<div>In the beginning...</div>");

<div>In the beginning...</div><div id="helloDiv" class="ms-bold">   Hello, world! </div>

Page 63: SEF 2012 - A jQuery Primer for Sharepoint

Manipulation:Changing CSS

<div id="helloDiv" class="ms-bold">   Hello, world! </div>

$("#helloDiv") .css("background-color", "fuchsia");

$("h3.ms-WPTitle a").css({ border: "5px black solid", color: "red"});

Page 64: SEF 2012 - A jQuery Primer for Sharepoint

EVENTS

Page 65: SEF 2012 - A jQuery Primer for Sharepoint

• jQuery’s events enable you to work with all of the standard JavaScript events

• These methods are used to register behaviors to take effect when the user interacts with the browser, and to further manipulate those registered behaviors.

Events

Page 66: SEF 2012 - A jQuery Primer for Sharepoint

jQuery Events

$('.article').click(function(){ // do something});

$('.article').mouseover(function(){ // do something});

Page 67: SEF 2012 - A jQuery Primer for Sharepoint

jQuery Events for Web Part Titles

$("h3.ms-WPTitle").click(function() { alert("Go directly to the list!");});

$("h3.ms-WPTitle").mouseover(function() { $(this).css("background-color", "fuchsia");});

Page 68: SEF 2012 - A jQuery Primer for Sharepoint

EFFECTS

Page 69: SEF 2012 - A jQuery Primer for Sharepoint

Effects

• jQuery gives you a set of effects you can use to change the elements in the page

• Effects can be:– Visual: Change how the user sees

existing elements with animations– Manipulative: Change where and how

elements are shown by moving them around in the DOM

Page 70: SEF 2012 - A jQuery Primer for Sharepoint

$('.article').hide();$('.article').slideUp();$('.article').after("<em>Hello!</em>");$('.article').css("color", "red");

jQuery Effects Examples

Page 71: SEF 2012 - A jQuery Primer for Sharepoint

Putting It Together: Example

Change what happens when you click on a Web Part Title

// Remove the links on the Web Part Titles$("h3.ms-WPTitle").find("nobr").unwrap("<a></a>");

// Add click behavior that toggles the visibility// of the Web Part$("h3.ms-WPTitle").click(function() { $(this).closest("table").closest("tr").next().toggle();});

Page 72: SEF 2012 - A jQuery Primer for Sharepoint

Putting It Together: Example

This example shows part of SPArrangeChoices from SPServices.

// Collect all of the choices$(thisFormField).find("tr").each(function() { columnOptions.push($(this).html());});

out = "<TR>";// Add all of the options to the out stringfor(i=0; i < columnOptions.length; i++) { out += columnOptions[i]; // If we've already got perRow columnOptions in the row, close off the row if((i+1) % opt.perRow === 0) { out += "</TR><TR>"; }}out += "</TR>";

// Remove the existing rows...$(thisFormField).find("tr").remove();// ...and append the out string$(thisFormField).find("table").append(out);

Page 73: SEF 2012 - A jQuery Primer for Sharepoint

$('.article').tabs();$('input').autocomplete();$('#infoBox').dialog();

…and many more

jQueryUI Takes Effects Further

Page 74: SEF 2012 - A jQuery Primer for Sharepoint

• If you want to do something sophisticated, look for an existing plugin

• Due diligence is up to you– some of the plugins aren’t written very well

• Beware of "plugin sprawl"

jQuery Plugins Abound!

Page 75: SEF 2012 - A jQuery Primer for Sharepoint

• JavaScript Compressorator – Minifies script files using multiple methods http://compressorrater.thruhere.net/

• JSLint – Checks your script against accepted standards http://jslint.com/ "Warning: JSLint will hurt your feelings."

More Useful Tools

Page 76: SEF 2012 - A jQuery Primer for Sharepoint

Contact InformationeMail [email protected]

Blog http://sympmarc.comSPServices http://spservices.codeplex.com

SPXSLT http://spxslt.codeplex.comeBook http://bit.ly/UnlockingDVWP

The Middle Tier Manifesto http://bit.ly/middletier