Fun with jQuery
A quick start to this powerful JavaScript Library Paul Litwin [email protected]
jQuery
What is it?
A JavaScript library
Why use it?
When you wish some programmatically manipulate your client-side HTML pages Makes it easy to interact with HTML pages Reduces the pain involved when scripting pages Does not matter what (if any) server-side technology you are using
Key Parts of jQuery
jQuery parts
jQuery function: $() or jQuery() jQuery selector goes inside of parens to create wrapped set jQuery methods are things you can do with your wrapped set jQuery events are how you hook your code up jQuery document ready handler is the master event to use to run code as the page loads
Calling jQuery
Three requirements
1. Load jQuery library using a <script> tag 2. Decide how to call your code
Using document ready executes after page loads; e.g.,
$(document).ready(function() { your-code });
Using event handler setup from your document ready function, e.g.,
$(selector).click( your-code);
3. Create your code
$(selector).do something
A Simple Example
Selectors
$(html-element-class)
Example: $(div)
$(#id)
Example: $(#txtFirstName)
$(.css-class)
Example: $(.divQuestion)
Various and sundry modifiers
Example: $(#divQuestion #answer) Example: $('div.question1 > input:checkbox:checked')
Selector Modifiers
Attribute modifier
$(selector[attribute=value]) only selects an element if it has the attribute set to value Example: $(input*type=text+)
Selecting by position
$(selector:position) match elements by position in wrapped set. E.g., :first, :last, :odd, :even, :eq(n)
CSS/Custom filter selector modifiers
:input, :button, :checked, :radio, :disabled, :enabled, :contains(x), :has(selector), :header, :not(selector)
More Selector Examples
$('#section1a .question1 input.q1')
Input controls of class q1 following any element of class question1 following element with id of section1a
$('#RecommendTx input[type=radio]')
Input elements of type radio following element with id of RecommendTx
$('div.question1 > input:checkbox:checked')
Selected checkbox controls immediately following a div tag of class question1
$('#section1a .q1:checked')
Elements of class q1 that are checked following an element of class section1a
$('#section1a .q3:checked, #section1a .q3a:checked')
Elements of class q3 following element with id of section1a that are checked OR elements of class q3a that are checked following element with id of section1a
$('input:hidden[name="HistologyForm.ViewerStartTime"]')
Hidden input control with name = HistologyForm.ViewerStartTime
NOTE: There are almost always multiple ways to select same wrapped set
Document Ready Event
$(document).ready(function () { // call all my // jQuery/JavaScript // code from here });
Events
Setting up event handlers
There are a number of ways to do it
On/Off (subsumes bind/unbind & live/die)
$(selector).on(event, handler); $(selector).off(event, handler);
Shortcuts
$(selector).click(handler) $(selector).blur(handler) $(selector).hover(handlerIn, handlerOut)
Methods
Once youve triggered your code (using an event) and selected your wrapped set (using a selector), its time to do something You can use the standard JavaScript DOM methods, but jQuery has some helpful methods
jQuery Methods
.toggle() toggles visibility; optionally using an animation and optional callback when animation is done
$("#q1").toggle(); $(#q1).toggle(true);
Equivalent to $(#q1).show();
$(#q1).toggle(false);
Equivalent to $(#q1).hide();
$(#q1).toggle(slow); $(#q1).toggle(slow, function() ,-);
jQuery Methods
.attr(attribute) determines value of attribute
var bChecked = $(ctl).attr('checked')
.attr(attribute, value) sets value of attribute
$(ctl).attr('checked', false); $('#txtIMBreslow').attr('value', '');
jQuery Methods
.val() gets value of first element in wrapped set .val(value) sets value of all elements in wrapped set
jQuery Methods
.html() gets html contents of first element in wrapped set .html(htmlString) sets html of all elements in wrapped set
jQuery Methods
.css(attribute, value) gets/sets css attribute .addClass(className) adds class name to class attribute of wrapped set .removeClass(className) removes class name to class attribute of wrapped set .toggleClass(className) adds (if not there)/removes (if there) class name to class attribute of wrapped set
What Might I do with jQuery?
For me, I have broken it down to 4 basic classes things I do with jQuery
1. Work on a control passed in to an event handler 2. Work on wrapped set 3. Test for state of wrapped set and do some work on related set of controls 4. Same as #3 but within a loop
Example using this
$('input[name="q0Answer"]').click(q0AnswerClick);
function q0AnswerClick() { var ctl = this; $(".surveyEnd").toggle(false); $("#q1").toggle(false); $("#q2").toggle(false); switch (this.value) { case "1": $("#q1").toggle(true); break; case "2": $("#q2").toggle(true); break; }
Another Example
function toggleMyChildren(ctl, bChecked) { var ctlRoot = $(ctl).parent();
// Toggle display $(ctlRoot).children('div').toggle(bChecked); $(ctlRoot).children('div').children().toggle(bChecked); }
Looping
$('div.question1 > input:checkbox:checked'). each(toggleChildrenUponLoad);
Debugging jQuery
Use browsers debugger (usually F12)
Dont bother with VS debugger But do add IntelliSense links in your .js files
Debugging tips
Check your selector: are you using . when you mean # or vice-versa? Are you treating a wrapped set as if its only one value?
You may need to use .first() or [0]
Writing Solid jQuery Code
You can usually simplify your job by
Creating a good style sheet with good CSS classes Thoughtfully assigning styles and IDs to your elements Designing a good containership model for your elements
Tools & Resources
Jquery.com jsfiddle.net http://codylindley.com/jqueryselectors/ jsperf.com