A few highlights from Ullman's Modern JavaScript

advertisement
A few highlights from Ullman’s Modern JavaScript
Using ‘$’ as a name for a function.
Code excerpt from Modern JavaScript Chapter 7 demonstrating the use of the $ as non-descriptive name
for a function , which in this case, represents shortcut for the code on line 13.
// random.js #2
// This script generates six random numbers.
// This function acts as a shortcut for document.getElementById().
// It takes an id string as its lone argument.
// It returns an element reference (i.e., an object).
function $(id) {
'use strict';
if (typeof id != 'undefined') {
return document.getElementById(id);
}
} // End of $ function.
function setText(elementId, message) {
'use strict';
if ( (typeof elementId == 'string')
&& (typeof message == 'string') ) {
var output = $(elementId);
<--USING THE FUNCTION EXAMPLE
if (output.textContent !== undefined) {
output.textContent = message;
} else {
output.innerText = message;
}
} // End of main IF.
} // End of setText() function.
 Primary reason for using:
 Saves time..
 Examples:
 Datepicking, calendars, dynamic tables, photo displays.
 References:
 Official main site - Jquery.com:
 jQuery Blog (http://blog.jquery.com).
 Forum at http://forum.jquery.com and an
 alternative presentation of the jQuery documentation at
http://jqapi.com.
How to access Jquery code




First include the code:
 From a copy on your web server:
 <script src=”js/jquery-1.7.1.min.js”></script>
 Or from a CDN such as google
 <script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js”></script>
To interact with Jquery use:
All jQuery interactions go through the jQuery() function, which the framework shortens to just $().
Ensure the entire DOM has loaded
 selects the document object and waits for DOM to load and then calls the anonymous function
when the “ready” event is triggered by the document object
 Example 1
$(document).ready(function() {
// Do whatever.
}
 Example 2(shorter form)
$(function() {
// Do whatever.
});
How to Select Page Elements
 In order to add event handlers to a page element, manipulate the
DOM, fetch form values, and so on, you must get a reference to the
page elemen.
 In Jquery selections are made through the $() function.
 Example: $(document) selects the Web document itself
 To select other page elements, use CSS selectors in place of document:
 #something selects the element with an id value of something

Example: $(‘#output)
 .something selects every element with a class value of something
 Example: $(‘.title’)
 something selects every element of something type
 Example: $(‘p’)
 Recall that in straight JavaScript, you have used the getElementById()
and getElementsByTagName() methods.
Combining Rules
 These rules can be combined as well:
 $(‘img.landscape’) selects every image with a class of
landscape
 $(‘#loginForm input’) selects every input element found
within an element that has an id of loginForm
Using Jquery to Change the
Properties of an Element
 Get a reference to the element and then apply the
Jquery function to the element.
 Example 1: Use the attr() method to disable a submit
button
 $(‘#submitButtonId’).attr(‘disabled’, ‘disabled’);
 Note:
attr(attribute, new value)
 Example 2:
 $(‘#submitButtonId’).attr(‘disabled’, ‘disabled’).attr(‘value’, p
‘...Processing...’);
Using Jquery to Change the CSS Properties of an
Element
 Example 1: Add the emphasis class to a specific
blockquote
 $(‘#blockquoteID’).addClass(‘emphasis’);
 Example 2: Remove the emphasis class from all
paragraphs:
 $(‘p’).removeClass(‘emphasis’);
 The toggleClass() function can be used to toggle the
application of a class to a selection
 The css() function is used to change individual styles
To Change the Value of an Element
 Apply the val() function to the element to get the value
 To change the value, apply the val() function with a
parameter specifying the new value
 Example:
var comments = $(‘#comments’); // Get a reference.
var count = comments.val().length;
if (count > 100) { // Update the value:
comments.val(comments.val().slice(0,100));
}
 The html() and text() functions can also be used
Using JQuery to Add Content to the
DOM
 Examples:
1.
2.
3.
$(‘#selection’).remove();
$(‘#actualFormId’).before(‘<p>New paragraph.</p>’);
$(‘#destination’).before($(‘#selection’).clone(true));
$(‘#selection’).remove();
 Note: methods on() and off()
Using JQuery to Add Event
Handlers
 The syntactical form is:
 elementSelection.eventType(function.)
 Example 1:
$(‘img’).mouseover(function() {
// Do this!
});
 Example 2:
$(‘#someSelect’).change(function() {
alert( this.val());
});
Using JQuery to Apply Effects
 Methods show() and hide() and toggle()
 Example(s):
 $(‘#actualFormId’).hide();
 Others are: fadein() , fadeOut() and animate()
Using JQuery to Perform an AJAX
Request
 Make the request
ajax(options);
 Where:
var options = {
url: ‘http://www.example.com/somepage.php’,
type: ‘get’,
data: {username: u, userpass: p}, // example data..
dataType: ‘text’
};
$.
 Handle the response

success: function(response) {
// Do something with response.
}
Note that success means both ready state 4 and status okay
JQuery PlugIns
 Use JQuery plug-ins to quickly add complex
functionality
 There is a rich assortment of:
 Image display tools
 HTML tables
 To find, use:

jQuery User Interface http://jqueryui.com
 accordion, the autocomplete, a date picker, and tabs, plus new
effects like drag and drop, resizing, and sorting.
 theme builder tools
To use a plug-in
 To use code from the JQuery User Interfaces, include the plug-in with a script
tag.
<script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/ jqueryui.min.js”>
</script>
 This is in addition to the script tag that includes jQuery itself.
 To use a method from the plug-in call it on the selected element.
 Example: $(‘#dateInput’).datepicker();
The jQuery UI Autocomplete
widget
 Example 1:
$(‘#inputId’).autocomplete(
{
source: [‘Afghanistan’, ‘Albania’, ‘Algeria’]
}
);
 Example 2:
$(‘#inputId’).autocomplete({
source: ‘http://www.example.com/somepage.php’
});

See fully coded example from Chapter 7 folder: ‘country.html’,
etc.
PHP Notes
 The PHP function stripos() finds one string within
another.
 find substrings anywhere within the string
 case insensitive.
 returns the indexed position where the substring was
found, or false if not found.
the datataBleS plug-in
 Free and open-source: http://datatables.net
 Include with:
 <script src=”js/jquery.dataTables.min.js”></script>
 Code the HTML table and use the id attribute
 Set up a script block:
$(function() {
$(‘#countries’).dataTable();
});
YUI
 The Yahoo! User Interface (YUI) Library (http://yuilibrary.com)
 References:
 YUI Blog (http://yuiblog.com).
 jQuery - YUI 3 Rosetta Stone (www.jsrosettastone.com)
 Include with
 <script src=”http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js”></script>
 To use:
YUI().use(‘module’, function(Y) {
// Do stuff here.
});
or
YUI().use(‘module1’, ‘module2’, function(Y) {
// Do stuff here.
});
Notes of interest…
 QUnit (http://docs.jquery.com/QUnit), a jQuery-
compatible unit testing tool
Download