1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)

Preview:

Citation preview

1

Using jQuery

JavaScript & jQuery the missing manual

(Second Edition)

2

Objectives

You will be able to Describe what jQuery is and what it

does. Use jQuery to hide browser

dependencies in JavaScript scripts. Use jQuery in JavaScripts to access

and modify the DOM.

3

jQuery

A JavaScript framework Extensive JavaScript script that provides a

more abstract DOM API for client scripts. Hides browser differences.

API works for all widely used browsers.

Open Source Developed and maintained by volunteers

http://jquery.com/

Has emerged as the preeminent JavaScript framework. Supported by Microsoft

4

jQuery

jQuery leverages the CSS selection syntax to identify DOM elements. Identify DOM elements for JavaScript

functions the same we we identify them to apply CSS styles.

Most web developers are familiar with CSS.

More powerful and more concise API.

5

Adding jQuery to an App

You can either Download jQuery and put a copy into

your virtual directory.http://docs.jquery.com/Downloading_jQuery#Download_jQuery

OR Reference one of several Content

Distribution Networks that support jQuery.

http://docs.jquery.com/Downloading_jQuery#CDN_Hosted_jQueryServer downloads jQuery from the CDN at run time.

6

The Microsoft CDN http://www.asp.net/ajaxlibrary/cdn.ashx

7

Using jQuery

As a demonstration of jQuery, we will modify the DOM positioning script from last class to use jQuery rather than the DOM API.

8

Using jQuery

Create a new empty ASPX website called DOM_Positioning_jQuery

Download to website folder final versions of DOM_Positioning website files from last class:

http://www.cse.usf.edu/~turnerr/Web_Application_Design/Downloads/DOM_Positioning_Final_Version/

animate.js drag_and_drop.js positioning.html

In Visual Studio, add files to website. Set positioning.html as start page. Build and run.

9

Initial Website

10

Download jQuery

http://docs.jquery.com/Downloading_jQuery

11

Download jQuery

Download current version Uncompressed to website folder. Add to website

12

Tell the Browser

Add <script> tag to head as first script immediately after the title.

<script language="javascript" type="text/javascript"

src="jquery-1.7.2.js" ></script>

Update the title <title>Positioning Elements with jQuery</title>

13

positioning.html

14

Using jQuery

We will modify the original JavaScript scripts to use jQuery In small steps.

Understand each step! Build and test after each step.

15

animate.js

Modify to use jQuery.

16

The jQuery $( )

$('#square') returns a jQuery object

An array of JavaScript DOM node objects All nodes with ID square. There is only one.

$('#square')[0] returns a reference to the first (and only) element of the array.

Effect is the same as forsq = document.getElementById("square");

17

The jQuery $( )

$( ) is a JavaScript function call Shorthand for jQuery( )

A function defined in jQuery.js

Everything we do with jQuery will have this form. The function returns a jQuery object. The object has properties and methods that we can use.

$( ) takes a parameter that is identical to a CSS selector.

If you know CSS, you already have a good start toward understanding jQuery!

18

Try it!

Click these buttons to test our change.

19

Replace All getElementById("square")

20

More Replacements

function updateHeading() {

//if (!document.getElementsByTagName) return;

//var headings = document.getElementsByTagName("h1");

var headings = $('h1');

var pageHeading = headings[0];

pageHeading.firstChild.nodeValue =

"Square text has been modified";

}

21

Adding Content with jQuery

The jQuery append() method adds its parameter value as the last child element of the selected element.

Let's use this jQuery method in function modifySquareText.

Comment out entire function and replace with this:

function modifySquareText() {

var new_text = document.form1.input_box.value;

$('#square').append(new_text);

document.form1.input_box.value = "";

updateHeading();

}

Try it!

22

Adding Content with jQuery

Enter some text.

Click Modify.

23

Modified Square

24

Getting User Input in jQuery

Select text input element. Use the jQuery val() method to get the

input.

Let's modify modifySquareText to use jQuery val() method rather than the DOM API.

function modifySquareText() {

$('#square').append($('#input_box').val());

document.form1.input_box.value = "";

updateHeading();

}

25

After Modify Clicked

Works the same.

End of Section

26

Using jQuery in drag_and_drop.js

The jQuery $( ) function returns a jQuery object.

Using the jQuery object to bind event handlers eliminates browser dependencies.

27

drag_and_drop.js

function Setup() {

$('#square').bind('mousedown', Start_Drag);

}

Try it!

28

Using a Anonymous Functions

The jQuery culture encourages the use of anonymous functions. Keep the namespace sparse. Avoid potential name conflicts.

If a function is only used in one place use the function definition rather than a function name.

29

An Anonymous Function

Try it!

(It works the same.)

30

function Start_Drag()

The argument passed to the event handler Start_Drag is now a jQuery object.

Its methods are the same for all browsers supported by jQuery. We can eliminate browser dependent

code.

31

function Start_Drag()

function Start_Drag(e) {

var mouse_x, mouse_y;

// Start dragging

// if (!e) var e = window.event;

// if (e.pageX) {

// mouse_x = e.pageX;

// mouse_y = e.pageY;

// } else if (e.clientX) {

// mouse_x = e.clientX;

// mouse_y = e.clientY;

// } else return;

mouse_x = e.pageX;

mouse_y = e.pageY;No browser dependency

32

css()

The jQuery css() method sets style attributes for jQuery objects.

33

function Start_Drag() Continued

//var sq = document.getElementById("square");

//sq.style.borderColor = "Red";

$('#square').css('borderColor', 'Red');

// Calculate object offsets from mouse position

dx = mouse_x - $('#square')[0].offsetLeft; dy = mouse_y - $('#square')[0].offsetTop;

// sq.onmousemove = Move;

// sq.onmouseup = Drop;

// sq.onmousedown = null;

$('#square').bind('mousemove', Move);

$('#square').bind('mouseup', Drop);

$('#square').unbind('mousedown');

}

function Move(e) {

var mouse_x, mouse_y;

// Track mouse movements

// if (!e) var e = window.event;

// if (e.pageX) {

// mouse_x = e.pageX;

// mouse_y = e.pageY;

// } else if (e.clientX) {

// mouse_x = e.clientX;

// mouse_y = e.clientY;

// } else return;

mouse_x = e.pageX;

mouse_y = e.pageY;

x = mouse_x - dx;

y = mouse_y - dy;

// var sq = document.getElementById("square");

// sq.style.left = x;

// sq.style.top = y;

$('#square').css('left', x);

$('#square').css('top', y); }

35

function Drop( )

function Drop() {

// var sq = document.getElementById("square");

// sq.style.borderColor = "black";

// sq.onmousemove = null;

// sq.onmouseup = null;

// sq.onmousedown = Start_Drag;

$('#square').css("borderColor", "black");

$('#square').unbind('mousemove');

$('#square').unbind('mouseup');

$('#square').bind('mousedown', Start_Drag);

}

Try it!

36

Internet Explorer 8

37

Chaining

Many jQuery functions return a reference to a jQuery object. Can be used to perform another

operation without doing a new selection.

38

Chaining css()

At the end of Move()

Instead of $('#square').css('left', x);

$('#square').css('top', y);

we can write $('#square').css('left', x)

.css('top', y);

39

Chaining bind()

At the end of Start_Drag() $('#square').bind('mousemove', Move)

.bind('mouseup', Drop)

.unbind('mousedown');

At the end of Drop() $('#square').unbind('mousemove')

.unbind('mouseup')

.bind('mousedown', Start_Drag);

40

Different Browsers

jQuery generally does a good job of hiding browser differences.

BUT Always check your app in multiple

browsers.

41

Chrome

42

Firefox

43

Safari

44

Summary

jQuery makes DOM manipulations easier by hiding browser differences.

More concise syntax than the DOM API.

Leverages knowledge of CSS selectors.

45

References

Documentation for the jQuery methods that we have used can be found in JavaScript & jQuery the missing manual and on the jQuery web site.

append page 139 http://api.jquery.com/append/

bind page 177-179 http://api.jquery.com/bind/

css page 143-146 http://api.jquery.com/css/

val page 261-262 http://api.jquery.com/css/