Top Banner
A jQuery Primer for SharePoint
73

SharePointfest Denver - A jQuery Primer for SharePoint

May 17, 2015

Download

Technology

Marc Anderson

These slides are from my session at SharePointFest Denver on 25 June 2012.


If you've been meaning to learn jQuery but haven't found the time, come to this introductory session where we'll cover all of the important basics of jQuery in a SharePoint context. By the end of the workshop, you'll be ready to start adding jQuery customizations to your SharePoint pages.



We'll cover Selectors, Traversing, Manipulation, Events and Effects as I cover in my article series at SharePoint Magazine.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: SharePointfest Denver -  A jQuery Primer for SharePoint

A jQuery Primer for SharePoint

Page 2: SharePointfest Denver -  A jQuery Primer for SharePoint

What is jQuery?

is

Page 3: SharePointfest Denver -  A jQuery Primer for SharePoint

GETTING STARTED

Page 4: SharePointfest Denver -  A jQuery Primer for SharePoint

Getting Started

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

Page 5: SharePointfest Denver -  A jQuery Primer for SharePoint

Referencing Script Libraries from CDNs

<!-- 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.7.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.1a/jquery.SPServices-0.7.1a.min.js"></script>More: http://sympmarc.com/2012/04/20/referencing-jquery-jqueryui-and-spservices-from-cdns/

Page 6: SharePointfest Denver -  A jQuery Primer for SharePoint

SharePoint Web Technology

• HTML– Hypertext Markup Language– Content and structure

• CSS– Cascading Style Sheets– Presentation and style

• JavaScript and jQuery– Interactive behavior

Page 7: SharePointfest Denver -  A jQuery Primer for SharePoint

HTML Elements

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

Opening tag Closing tag

Attribute Value

Page 8: SharePointfest Denver -  A jQuery Primer for SharePoint

INTRO TO CSS

Page 9: SharePointfest Denver -  A jQuery Primer for SharePoint

Intro to CSS:Why does CSS matter?

• 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

Page 10: SharePointfest Denver -  A jQuery Primer for SharePoint

CSS Styles

.article { color: red;}

Select HTML element(s)

Modify them!

Page 11: SharePointfest Denver -  A jQuery Primer for SharePoint

CSS Element Selectors

<p>

Paragraph of

text.

</p>

p {

color: red;

}

Paragraph of text.

Page 12: SharePointfest Denver -  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: SharePointfest Denver -  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: SharePointfest Denver -  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: SharePointfest Denver -  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: SharePointfest Denver -  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: SharePointfest Denver -  A jQuery Primer for SharePoint

My CSS "Best" Practices

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

Page 18: SharePointfest Denver -  A jQuery Primer for SharePoint

DOCUMENT OBJECT MODEL (DOM)

Page 19: SharePointfest Denver -  A jQuery Primer for SharePoint

What is the Document Object Model (DOM)?

• 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 the look and feel

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

Page 20: SharePointfest Denver -  A jQuery Primer for SharePoint

What Can We Do With the DOM?

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

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

Page 21: SharePointfest Denver -  A jQuery Primer for SharePoint

IMPORTANT TOOLS

Page 22: SharePointfest Denver -  A jQuery Primer for SharePoint

Internet Explorer Developer Tools (F12)

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

Page 23: SharePointfest Denver -  A jQuery Primer for SharePoint

The Firebug Add-On for Firefox

• Better for debugging and looking at Net traffic

Page 24: SharePointfest Denver -  A jQuery Primer for SharePoint

JQUERY BASICS

Page 25: SharePointfest Denver -  A jQuery Primer for SharePoint

The Basic Idea of jQuery

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

Select something

Do something!

Page 26: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery’s Document Ready

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

Page 27: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Documentation: Your Friend

• The jQuery documentation is arranged to help you

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

Page 28: SharePointfest Denver -  A jQuery Primer for SharePoint

SELECTORS

Page 29: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Selectors

• Selectors are the most important jQuery concept

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

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

Page 30: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Element Selectors

$("p")

<p>

Paragraph of

text.

</p>

Page 31: SharePointfest Denver -  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 paragraphs in the page

Page 32: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Class Selectors

$(".article")

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

Page 33: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery ID Selectors

$("#header")

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

Page 34: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Descendant Selectors

$("#header h1")

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

Page 35: SharePointfest Denver -  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: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Complex Selectors

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

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

Page 37: SharePointfest Denver -  A jQuery Primer for SharePoint

Selectors for SharePoint

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

Page 38: SharePointfest Denver -  A jQuery Primer for SharePoint

Selectors for SharePoint

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

$

("#ctl00_PlaceHolderLeftNavBar_idNavLinkViewAl

l")

Page 39: SharePointfest Denver -  A jQuery Primer for SharePoint

Selectors for SharePoint

<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']")

Page 40: SharePointfest Denver -  A jQuery Primer for SharePoint

Useful jQuery Selector Tricks

$("[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

• .NET Applications like SharePoint generate some long and ugly markup and IDs• These selector tricks really help

Page 41: SharePointfest Denver -  A jQuery Primer for SharePoint

ATTRIBUTES

Page 42: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Attributes

• 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

Page 43: SharePointfest Denver -  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 44: SharePointfest Denver -  A jQuery Primer for SharePoint

Example with SharePoint Attributes: Get

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

var thisKey = $

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

Page 45: SharePointfest Denver -  A jQuery Primer for SharePoint

Example with SharePoint Attributes: Set

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

$("a[id$='NavLinkViewAll']").attr("accessKey",

99);

Page 46: SharePointfest Denver -  A jQuery Primer for SharePoint

TRAVERSING

Page 47: SharePointfest Denver -  A jQuery Primer for SharePoint

Traversing

• 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

Page 48: SharePointfest Denver -  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 49: SharePointfest Denver -  A jQuery Primer for SharePoint

Traversing Down:Find an Element’s 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 50: SharePointfest Denver -  A jQuery Primer for SharePoint

Traversing Down:Find an Element’s 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 51: SharePointfest Denver -  A jQuery Primer for SharePoint

SharePoint Example of Traversing: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>

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

Page 52: SharePointfest Denver -  A jQuery Primer for SharePoint

SharePoint Example of Traversing:Finding Parent

<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 53: SharePointfest Denver -  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

<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 54: SharePointfest Denver -  A jQuery Primer for SharePoint

MANIPULATION

Page 55: SharePointfest Denver -  A jQuery Primer for SharePoint

Manipulation

• Once you’ve gotten the right element(s), you can manipulate their attributes or properties

• You can also change their contents

Page 56: SharePointfest Denver -  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 57: SharePointfest Denver -  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 58: SharePointfest Denver -  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 59: SharePointfest Denver -  A jQuery Primer for SharePoint

Manipulation:Inserting Elements

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

$("#helloDiv") .before("<div>This is a new div.</div>");

<div>This is a new div.</div><div id="helloDiv" class="ms-bold">   Hello, world! </div>

Page 60: SharePointfest Denver -  A jQuery Primer for SharePoint

Manipulation:Changing CSS

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

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

$("#helloDiv").css({ border: "1px black solid", color: "red"});

Page 61: SharePointfest Denver -  A jQuery Primer for SharePoint

EVENTS

Page 62: SharePointfest Denver -  A jQuery Primer for SharePoint

Events

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

Page 63: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Events

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

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

Page 64: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Events

$("h3.ms-WPTitle").click(function() { alert("You'll now be taken directly to the list.");});

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

Page 65: SharePointfest Denver -  A jQuery Primer for SharePoint

EFFECTS

Page 66: SharePointfest Denver -  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 67: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Effects Examples

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

Page 68: SharePointfest Denver -  A jQuery Primer for SharePoint

Putting It Together: Example

• This example changes 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 69: SharePointfest Denver -  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 rowif((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 70: SharePointfest Denver -  A jQuery Primer for SharePoint

jQueryUI Takes Effects Further

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

…and many more

Page 71: SharePointfest Denver -  A jQuery Primer for SharePoint

jQuery Plugins Abound!

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

• Do some due diligence – some of the plugins aren’t written very well

• Beware of “plugin sprawl”

Page 72: SharePointfest Denver -  A jQuery Primer for SharePoint

More Useful Tools

• 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.”

Page 73: SharePointfest Denver -  A jQuery Primer for SharePoint

Contact InformationeMail marc.anderson@sympraxisconsulting.

comBlog http://sympmarc.com

SPServices http://spservices.codeplex.com

SPXSLT http://spxslt.codeplex.com

USPJA Academy http://uspja.com

eBook http://bit.ly/UnlockingDVWP

The Middle Tier Manifesto

http://bit.ly/middletier