JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING...

36
JAVASCRIPT AND JQUERY : AN INTRODUCTION (WEB PROGRAMMING, X452.1) Professional Program: Data Administration and Management Instructor: Michael Kremer, Ph.D. Technology & Information Management Class 8

Transcript of JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING...

JAVASCRIPT AND JQUERY: AN INTRODUCTION

(WEB PROGRAMMING, X452.1)

Professional Program: Data Administration and Management

Instructor: Michael Kremer, Ph.D.Technology & Information Management

Class 8

AGENDA

20. Specific Events

21. Overview of jQuery

Specific Events

20.

20.1 DOCUMENT LOAD EVENTS

Web applications need notification from the web browser to tell

them when the document has been loaded and is ready to be

manipulated Load Event

Manipulating html elements in JS before loading is finished will

silently fail

Readystatechange

event different states:

303

20.1 DOCUMENT LOAD EVENTS

To improve loading a

page

DOMContentLoaded

event is fired when the

document has been

loaded, parsed and

any deferred scripts

have been executed

(but not images and

async scripts)

Despite its name, it is

not part of DOM

specification, but of

HTML5 spec

304

20.2 MOUSE/MOUSEWHEEL EVENTS

All mouse events

except

“mouseenter”

and

“mouseleave”

bubble

Click events on

links and Submit

buttons have

default actions

that can be

prevented

305

20.2 MOUSE/MOUSEWHEEL EVENTS

Basic Mouse Events

306

20.2 MOUSE/MOUSEWHEEL EVENTS

Mouse Events

Object passed to mouse event handlers has clientX and clientYproperties that specify the coordinates of the mouse pointer relative to the containing window

Keyboard modifier used in conjunction with mouse (shift ..) are detected to perform special actions (multi-select!)

Most browsers only fire click events for left button clicks

You should use mousedown and mouseup if you need to detect clicks of other mouse buttons

Mouse Wheel Events

New event name, simply named wheel

1-dimensional and 2-dimensional hardware differences

Object passed to a wheel event handler will have deltaX, deltaY, and deltaZ propertiesto specify rotation in three dimensions

307

20.2 MOUSE/MOUSEWHEEL EVENTS

Drag and Drop Events

Simple drag N drop within one web page

True drag N drop (DnD) defines drag source and drag target in

different applications

DnD is a complex

process:

DnD is always event

based (two events)

Any document element that has the HTML draggable attribute is

a drag source fires a dragstart event

dataTransfer.setData() to specify data

308

20.2 MOUSE/MOUSEWHEEL EVENTS

dataTransfer.effectAllowed to specify which of the “move”,

“copy”, and “link” transfer operations are supported

When a drop occurs, the dragend event is fired

Check dataTransfer.dropEffect for transfer operation(move, copy)

309

20.3 INPUT EVENTS

Three legacy events:

DOM Level 3 Events specification defines a more general input

event triggered whenever the user inputs text regardless of the

source, such as:

keypress and textinput events are triggered before the newly

input text is actually inserted cancellable

Browsers also implement an input event type that is fired after

text is inserted into an element not cancellable

310

20.4 KEYBOARD EVENTS

Keydown/keyup events are fired when a key is pressed/released

on the keyboard (modifier, function, and alphanumeric keys)

Event object associated with these events has a numeric

keyCode property that specifies which key was pressed:

Printable characters: keycode is Unicode encoding (Upper case letter)

Numeric characters: keycode contains actual number

Nonprinting characters: some other value

Keycode was not standardized in DOM Level 3, instead new key

property was designed string of keyname

Pressing a key on the keyboard generates following sequence:

311

Overview of jQuery

21.

21.1 INTRODUCTION TO JQUERY

Open-source JavaScript library that organizes many typical

operations into a simple and clear syntax

Also takes care of cross-browser incompatibility issues

jQuery makes it easy to:

find the elements of a document that you care about

manipulate those elements by adding content, editing HTML attributes

and CSS properties, defining event handlers, and performing animations

jQuery library is focused on queries

Typical query uses a CSS selector to identify a set of document

elements and returns an object that represents those elements

312

21.2 JQUERY BASICS

jQuery library defines a single global function named jQuery()

Global symbol $ as a shortcut

Value returned by this function represents a set of zero or more DOM elements and is known as a jQuery object

jQuery objects define many methods for operating on the sets of elements they represent

This is code that finds, highlights, and quickly displays all hidden <p> elements that have a class of “details”

Chaining multiple functions is very common( css().show())

Find all elements in the document with CSS class “clicktohide” and registers event handler on each one

Event handler is invoked when user clicks on the element (element slowly “slides up” and then disappears)

313

21.2 JQUERY BASICS

Obtaining and Referencing jQuery

jQuery library is free software and is downloadable from

http://jquery.com. Once you have the code, you can include it in

your web pages with

a <script> element

“min” in the filename above indicates that this is the minimized

version of the library, with unnecessary comments and

whitespace removed, and internal identifiers replaced with

shorter ones

Content distribution

network (CDN):

Use version 3

in this course

314

21.2 JQUERY BASICS

The jQuery Function

jQuery() or $ is heavily

overloaded:

Passing CSS Selector

Pass a CSS selector string to return a set of elements matching the CSS

selector string

jQuery supports most of the CSS3 selector syntax, plus some extensions

of its own

Optional second argument value defines the starting point (or points) for

the query and is often

called the context

315

21.2 JQUERY BASICS

Passing Element, Document, Window Object

Simply wraps passed object into a jQuery object:

Allows you to use jQuery methods to manipulate the element rather than using raw

DOM methods

Common to see $(document) or $(this)

Passing String of HTML

jQuery creates the HTML element or elements described by that text and

then returns a jQuery object representing those elements

jQuery does not automatically insert the newly created elements into the

document use jQuery methods (see later)

Cannot pass plain text CSS selector. Must include one html tag

Optional second argument:

Pass a Document object to specify the document with which the elements are to be

associated (important for iframes)

Pass an object as the second argument

for additional attributes

316

21.2 JQUERY BASICS

Passing a Function

Pass a function into it, the function is invoked when the document is

finished loading

jQuery triggers functions registered through $() when the

DOMContentLoaded event is fired or, in browsers that do not support that

event, when the load event is fired

Common to see jQuery programs

written as anonymous functions

defined within a call to jQuery() or $()

jQuery Namespace

jQuery library also uses the jQuery() function as its namespace

and defines a number of utility functions and properties under it:

317

21.2 JQUERY BASICS

jQuery Terminology

The jQuery Function: creates jQuery objects, registers handlers

to be invoked when the DOM is ready, and that also serves as

the jQuery namespace

jQuery Object: represents a set of document elements and can

also be called “jQuery result,” “jQuery set,” “wrapped set”

Selected Elements: Match elements returned in jQuery object

A jQuery Function: Function like jQuery.noConflict() that is

defined in the namespace of the jQuery function

318

21.2 JQUERY BASICS

jQuery Terminology(continued)

jQuery Method: Method of a jQuery object returned by the jQuery

function

Names like $.each refer to jQuery functions and names like .each(with a

period but without a dollar sign) refer to jQuery methods

Call jQuery function each() to invoke function f

once for each element of the array a:

Call jQuery() function to obtain a jQuery object

containing all <a> elements, then call the each()

method of that jQuery object to invoke the

function f once for each selected element

319

21.2 JQUERY BASICS

Querying using jQuery

Basically pass CSS selectors to $()

Returned object is jQuery object (=array-like): it has a length

property and numeric

properties from 0 to length-1

Alternatively, use size() method instead of the length property

and the get() method instead of indexing with square brackets

Besides length

three other

properties:

320

21.2 JQUERY BASICS

$() function is similar to the document method querySelectorAll(), however, there are good reasons to use jQuery’s implementation:

To loop over all elementsin a jQuery object, you can call the each() method instead of writing a for loop

Expects a callback function as its sole argument, and it invokes that callback function once for each element in the jQuery object (in document order)

Within the callback the this keyword refers to an Element object

each() also passes the index and the element as the first and second arguments to the callback

each() returns the jQuery object on which it is called, so that it can be used in method chains

321

21.2 JQUERY BASICS

Usually you do not need each since jQuery methods usually

iterate implicitly over the set of matched elements and operate

on them all

You typically only need to use each() if you need to manipulate

the matched elements in different ways

jQuery method map()

works much like the

Array.map() method

322

21.2 JQUERY BASICS

Another fundamental jQuery method is index()

This method expects an element as its argument and returns the index of

that element in the jQuery object, or –1 if it is not found

Final general-purpose jQuery method is is()

It takes a selector as its argument and returns true if at

least one of the selected elements also matches the specified selector

323

21.3 JQUERY GETTERS AND SETTERS

Most common operations on jQuery objects are those that get or

set the value of HTML attributes, CSS styles, element content, or

element geometry

General

information

about getters

and setters:

324

21.3 JQUERY GETTERS AND SETTERS

Getting/Setting HTML Attributes

attr() method is the jQuery getter/setter for HTML attributes

attr() handles browser

incompatibilities and

special cases

removeAttr() is a related function that completely removes an

attribute from all selected elements

Getting/Setting CSS Attributes

css() method is very much like the attr() method, but it works

with the CSS styles of an element

Returns the current (or

“computed”) style of the

element

325

21.3 JQUERY GETTERS AND SETTERS

Getting/Setting CSS Classes

Class attribute is interpreted as a space-separated list of CSS class names

Usually to add, remove, or test for the presence of a single name in the list rather than replacing one list of classes with another

addClass() and removeClass() add and remove classes from the selected elements

toggleClass() adds classes to elements that do not already have them and removes classes from those that do

hasClass() tests for the presence of a specified class

326

21.3 JQUERY GETTERS AND SETTERS

Getting/Setting HTML Form Values

val() is a method for setting andquerying the value attribute of HTML form elements

Also for querying and setting the selection state of checkboxes, radio buttons, and <select> elements

Getting/Setting Element Content

text() and html() methods query and set the plain-text or HTML content of an element or elements

When invoked with no arguments, text() returns the plain-text content of all descendant text nodes of all matched elements

Pass a function, which will beused to compute the new content string

327

21.3 JQUERY GETTERS AND SETTERS

Getting/Setting Element Data

jQuery defines a getter/setter method named data() that sets or

queries data associated with any document element or with the

Document or Window objects

Basis for jQuery’s event handler registration and effects queuing

mechanisms

Call data() method as a setter and pass an element name and a

value as the two arguments

Call data() method as a getter with no arguments, it returns an

object containing all name/value pairs associated with the first

element in the jQuery object

When you invoke data() with a single string argument, it returns

the value associated with that string for the first element

328

21.3 JQUERY GETTERS AND SETTERS

Getting/Setting Element Data

Use removeData() to remove data from an element or elements

If passing a string, it deletes any value associated with that

string for an element or elements

If calling removeData() with no arguments, it deletes all data for

selected element or elements

jQuery also defines utility

function forms of data() and removeData()

methods

329

21.4 ALTERING DOCUMENT STRUCTURE

Methods for making more complex changes to a document

Inserting and Replacing Elements

Each of the methods below takes an argument that specifies the

content that is to be inserted into the document

append(), prepend(), before(), after(), replaceWith()

Content can be: String of plain text or HTML, a jQuery object, an Element

or text Node, or a function that will be invoked to compute the value to be

inserted

These methods:

Are all invoked on target

elements and are passed

the content that is to be

inserted as an argument

Can be paired with another method that works the other way around:

invoked on the content and passed the target elements as the argument

330

21.4 ALTERING DOCUMENT STRUCTURE

Important things

to understand

about these

pairs of methods:

331

21.4 ALTERING DOCUMENT STRUCTURE

Copying Elements

If you insert elements that are already part of the document,

those elements will simply be moved, not copied, to new location

If you are inserting the elements in more than one place, jQuery

will make copies as needed

If you want to copy elements

to a new location instead of

moving them, you must first

make a copy with the clone()

method

clone() returns jQuery object,

need to insert using methods

above

332

21.4 ALTERING DOCUMENT STRUCTURE

Wrapping Elements

Another type of HTML insertion: Wrapping a new element (or

elements) around one or more elements

3 wrapping methods:

333

21.4 ALTERING DOCUMENT STRUCTURE

Deleting Elements

Methods for

deleting elements:

remove() method removes any event handlers and other data you may

have bound to the removed elements

detach() method works just like remove() but does not remove event

handlers and data

unwrap() method performs element removal in a way that is the opposite

of the wrap() or wrapAll() method: it removes the parent element of each

selected element without affecting the selected elements or their siblings

334