Get Your jQuery On - SharePoint Conference .ORG

Download Report

Transcript Get Your jQuery On - SharePoint Conference .ORG

Get Your jQuery On
Who Is Marc?
• Co-Founder and President of Sympraxis Consulting LLC, located in the
Boston suburb of Newton, MA, USA. Sympraxis focuses on enabling
collaboration throughout the enterprise using the SharePoint
application platform.
• Over 30 years of experience in technology professional services and
software development. In a wide-ranging career in consulting as well
as line manager positions, Marc has proven himself as a problem
solver and leader who can solve difficult technology problems for
organizations across a wide variety of industries and organization
sizes.
• Three-time awardee of the Microsoft MVP award for SharePoint
Server (2011, 2012, 2013).
Session Overview
• SharePoint’s pages and forms can seem somewhat oldfashioned to the Facebook generation. By using jQuery,
jQueryUI, and other scripting libraries such as SPServices, we
can make those pages more consistent with the type of user
experiences people are used to on the modern Web.
• In this session, Marc will cover some of the useful features of
jQuery and SPServices as well as some of the rich possibilities
available to you by demonstrating solution examples he has
built for his consulting clients.
• This demo-rich session is bound to change the way you think
about building your SharePoint applications.
Getting Started
What is jQuery?
is
Getting Started
• Add references to the jQuery library
• References can be in:
• Master page
• Page layout
• Individual aspx pages
• jQuery and other .js files can be stored in:
• Document Library
• _layouts folder
• Retrieved from a CDN
• Use “protocol-less” src and href
Script from CDNs
Referencing jQuery, jQueryUI, and SPServices from CDNs – Revisited
http://sympmarc.com/2013/02/07/referencing-jquery-jqueryui-and-spservices-from-cdns-revisited/
HTML Elements
Opening tag
Closing tag
Powered by <a href="http://office365.com">Office365</a>.
Attribute
Value
Element
Self-closing tag
<input id="my-cbox" class="foo bar" type="checkbox" checked />
Id
Class(es)
Attribute
Value
Property
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 look and feel
• The DOM is acted upon by any script in the page
• View Source is *not* the live DOM
What Can We Do With the DOM?
• Add or remove CSS classes
• Create new or remove existing HTML elements
• Change HTML element attributes
• Bind to events
• And so much more…
The DOM is HTML, which is XML,
which is data!
The Basic Idea of jQuery
Select something
$('.article').hide();
Do something!
Remember this from CSS?
jQuery’s Document Ready
$(document).ready(function() {
// do something
});
$(function() {
// do something
});
jQuery(function($) {
// do something
});
jQuery Documentation: Your Friend
• The jQuery documentation is used to be
arranged to help you
• What you need to know is was arranged
sequentially from top to bottom
jQuery Selectors
• Selectors are the most important
jQuery concept
• Selecting the right DOM object(s) is
half the battle
• Selectors return a jQuery object
containing a collection of DOM
objects: 1 to n matching elements
Selectors for SharePoint
$("div[id$='QuickLaunchNavigationManager']
li:first span.menu-item-text")
Selectors for SharePoint
$("td.ms-list-addnew a:eq(1)")
Useful jQuery Selector Tricks
• .NET Applications like SharePoint $("[id='foo']");
$("[id!='foo']");
generate some long and ugly
$("[id^='foo']");
markup and IDs
id="ctl00$ctl41$g_26ee1140_76aa_4ec0_88
c4_11e7e96480f4$ctl00$ctl02$ctl00$ctl01
$ctl00$ContentTypeChoice"
• These selector tricks really help
$("[id$='foo']");
$("[id*='foo']");
$("[id~='foo']");
// Equal to
// Not equal to
// Starts with
// Ends with
// Contains
// Contains word
$("[id|='foo']");
// Contains prefix
$("[id]");
// Has attribute
$("[id][class][style]"); // Has all
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 get/set property values, while .attr() gets/sets
attributes
• To retrieve and change DOM properties such as the
checked, selected, or disabled state of form elements,
use the .prop() method.
Example with SharePoint Attributes: Get
$("select[title='Region']").val();
$("select[title='Region'] option:selected").text();
Example with SharePoint Attributes: Set
$("select[title='Region']").val(5);
$("select[title='Region'] option:selected").text("boo");
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
Traversing Down:
Find an Element’s Specific Children
$("div[id$='QuickLaunchNavigationManager'] li:first")
.parent().find("li:eq(3) li:first .menu-item-text");
Traversal Example from SPServices
SelectCandidate
SelectResult
<select
<select
var
possibleValues =
name="ctl00$m$g_e845e690_00da_428f_afbd_fbe80
name="ctl00$m$g_e845e690_00da_428f_afbd_fbe8047
4787763$ctl00$ctl04$ctl07$ctl00$ctl00$ctl04$c
87763$ctl00$ctl04$ctl07$ctl00$ctl00$ctl04$ctl00
$("select[ID$='SelectCandidate'][Title^='"
+
tl00$ctl00$SelectCandidate" title="City
$ctl00$SelectResult" title="City selected
possible values"
opt.multiSelectColumn
+ " ']"); values"
id="ctl00_m_g_e845e690_00da_428f_afbd_fbe8047
id="ctl00_m_g_e845e690_00da_428f_afbd_fbe804787
var
selectedValues =
87763_ctl00_ctl04_ctl07_ctl00_ctl00_ctl04_ctl
763_ctl00_ctl04_ctl07_ctl00_ctl00_ctl04_ctl00_c
00_ctl00_SelectCandidate" style="width:
tl00_SelectResult" style="width: 162px;"
possibleValues.closest("span").find("select[ID$='SelectResult
162px;" onkeydown="GipHandleHScroll(event)"
onkeydown="GipHandleHScroll(event)"
ondblclick="GipAddSelectedItems(ctl00_m_g_e84
'][Title^='"
+ opt.multiSelectColumn
+ " ']");
ondblclick="GipRemoveSelectedItems(ctl00_m_g_e8
5e690_00da_428f_afbd_fbe804787763_ctl00_ctl04
_ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_MultiLoo
45e690_00da_428f_afbd_fbe804787763_ctl00_ctl04_
ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_MultiLookup
Manipulation
• Once you’ve gotten the right
element(s), you can:
• Manipulate their attributes
• Set properties
• Change their contents
(innerHTML)
Events
• jQuery’s events enable you
to work with all of the
standard JavaScript events
• Used to create behaviors
that take effect when the
user interacts with the
page in the browser, and
to further manipulate
those behaviors
jQuery Events
$('.article').click(function(){
// do something
});
$('.article').mouseover(function(){
// do something
});
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
jQuery Effects Examples
$('.article').hide();
$('.article').slideUp();
$('.article').fadeOut("slow");
$('.article').animate({
"font-size": "24px",
"background-color": "red"
}, 5000);
Putting It Together:
Toggling Web Part Visibility
var wpTitles = $("h2.ms-webpart-titleText");
// Remove the links on the Web Part Titles
wpTitles.find("nobr").unwrap("<a></a>");
// Show the pointer on mouseover
wpTitles.css("cursor", "pointer");
// Add click behavior that toggles the visibility
wpTitles.click(function() {
$(this).closest("div.ms-webpart-chrome")
.find("div:eq(1)")
.slideToggle();
});
Putting It Together:
Arranging Checkboxes
// Collect all of the choices
$(thisFormField).find("tr").each(function() {
columnOptions.push($(this).html());
});
out = "<TR>";
// Add all of the options to the out string
for(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);
SharePoint 2013 SOAP Call With SPServices
var thisPromise = $().SPServices({
operation: "GetListItems",
listName: "Cities"
});
thisPromise.done(function() {
$(thisPromise.responseXML).SPFilterNode("z:row").each(function() {
alert($(this).attr("ows_Title"));
});
});
http://spservices.codeplex.com
SOAP (asmx) Web Services are
deprecated in SharePoint 2013
SharePoint 2013 REST Call
$.ajax({
url: "/sites/marca/jquery/_api/web/lists/getbytitle('Cities')/items",
type: "GET",
headers: {
"ACCEPT": "application/json;odata=verbose"
},
success: function(data) {
var results = data.d.results;
for(i=0; i < data.d.results.length; i++) {
alert(i + data.d.results[i].Title);
}
}
});
How to: Complete basic operations using SharePoint 2013 REST endpoints
http://msdn.microsoft.com/en-us/library/jj164022.aspx
Understanding and Using the SharePoint 2013 REST Interface
http://msdn.microsoft.com/en-us/magazine/dn198245.aspx
SharePoint 2013 JSOM Call
var siteUrl = "/sites/marca/jQuery";
function onQuerySucceeded(sender, args) {
var clientContext = new SP.ClientContext(siteUrl);
var listItemInfo = '';
var oList = clientContext.get_web().get_lists().getByTitle('Cities');
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var camlQuery = new SP.CamlQuery();
var oListItem = listItemEnumerator.get_current();
camlQuery.set_viewXml('<View><Query></Query></View>');
alert(oListItem.get_item('Title').toString());
this.collListItem = oList.getItems(camlQuery);
}
}
clientContext.load(collListItem);
function onQueryFailed(sender, args) {
clientContext.executeQueryAsync(
);
alert('Request failed. ' +
Function.createDelegate(this, this.onQuerySucceeded),
args.get_message() + '\n' +
Function.createDelegate(this, this.onQueryFailed)
args.get_stackTrace());
}
How to: Complete basic operations using JavaScript library code in SharePoint 2013
http://msdn.microsoft.com/en-us/library/jj163201.aspx
jQueryUI Takes Effects Further
$(".article").tabs();
$("input").autocomplete();
$("#infoBox").dialog();
$("table.sortable").sortable();
…and many more
jQuery Plugins Abound!
• If you want to do something sophisticated,
look for an existing plugin
• Due diligence – some of the plugins aren’t
written very well
• Beware of “plugin sprawl”
More Useful Tools
• JSLint
• http://jslint.com/
• Checks your script against accepted standards
• “Warning: JSLint will hurt your feelings.”
• JSHint
• http://jshint.com/
• Like JSLint, but a little more forgiving
• More jQuery aware.
• JavaScript Compressorator
• http://compressorrater.thruhere.net/
• Minifies script files using multiple methods
Questions?
Contact Information
Email [email protected]
Blog http://sympmarc.com
SPServices http://spservices.codeplex.com
SPXSLT http://spxslt.codeplex.com
eBook http://bit.ly/UnlockingDVWP
The Middle Tier Manifesto http://bit.ly/middletier