jQuery jQuery CS 380: Web Programming CS 380 1 Downloading and - - PowerPoint PPT Presentation

jquery jquery
SMART_READER_LITE
LIVE PREVIEW

jQuery jQuery CS 380: Web Programming CS 380 1 Downloading and - - PowerPoint PPT Presentation

jQuery jQuery CS 380: Web Programming CS 380 1 Downloading and using jQuery UI <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script


slide-1
SLIDE 1

jQuery jQuery

CS 380: Web Programming

CS 380 1

slide-2
SLIDE 2

Downloading and using jQuery UI

  • r download it, extract its .js files to your project

folder

documentation available on the jQuery UI API

page

the CSS is optional and only needed for widgets

at the end

CS 380 2 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js" type="text/javascript"></script> <!-- If you want the default ui widget stylings --> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css" />

slide-3
SLIDE 3

Looping over the DOM Looping over the DOM

Using the DOM Using jQuery

var elems = document.querySelectorAll("li"); for (var i = 0; i < elems.length; i++) { var e = elems[i]; // do stuff with e } $("li").each(function(idx, e) { // do stuff with e });

CS 380 3

slide-4
SLIDE 4

Inside the jQuery each loop

return false to exit the loop early e is a plain old DOM object

We can upgrade it again using $ if we want

$("li").each(function(idx, e) { e = $(e); // do stuff with e });

$("li").each(function(idx, e) { // do stuff with e });

CS 380 4

slide-5
SLIDE 5

Modifying DOM nodes

HTML attributes DOM fields title .title id .id class .className style="prop: value" .style.prop = value

CS 380 5

slide-6
SLIDE 6

Getting/Setting CSS classes Getting/Setting CSS classes

6

JS DOM's className property corresponds to

HTML class attribute

somewhat clunky when dealing with multiple space-

separated classes as one big string

className is just a string, not an array like we would

want

CS 380

function highlightField() { // turn text yellow and make it bigger var elem = document.getElementById("id"); if (!elem.className) { elem.className = "highlight"; } else if (elem.className.indexOf("invalid") < 0) { elem.className += " highlight"; } }

slide-7
SLIDE 7

Getting/setting CSS classes in jQuery

addClass, removeClass, hasClass, toggleClass ma

nipulate CSS classes

similar to existing className DOM property, but

don't have to manually split by spaces

function highlightField() { // turn text yellow and make it bigger if (!$("#myid").hasClass("invalid")) { $("#myid").addClass("highlight"); } }

CS 380 7

slide-8
SLIDE 8

Adjusting styles with the DOM

Property Description style lets you set any CSS style property for an element

<button id="clickme">Color Me</button> window.onload = function() { document.getElementById("clickme").onclick = changeColor; }; function changeColor() { var clickMe = document.getElementById("clickme"); clickMe.style.color = "red"; }

CS 380 8

slide-9
SLIDE 9

Problems with reading/changing styles

style property lets you set any CSS

style for an element

problem: you cannot (usually) read

existing styles with it

<button id="clickme">Click Me</button> window.onload = function() { document.getElementById("#clickme").onclick = biggerFont; }; function biggerFont() { var size = parseInt(document.getElementById("#clickme").style.fontSize); size += 4; document.getElementById("#clickMe").style.fontSize = s ize + "pt"; }

CS 380 9

slide-10
SLIDE 10

Accessing styles in jQuery

css function of the jQuery object allows

reading pre-existing styles

gives us the familiar font-size syntax instead

  • f fontSize

css(property) gets the property

value, css(property, value) sets the property value

function biggerFont() { // turn text yellow and make it bigger var size = parseInt($("#clickme").css("font-size")); $("#clickme").css("font-size", size + 4 + "pt"); }

CS 380 10

slide-11
SLIDE 11

Exercise Exercise

Find something with CSS and

changing styles

Write it with DOM and jQuery

CS 380 11

slide-12
SLIDE 12

jQuery method behavior

Getters typically operate only on the first of

the jQuery object's selected elements.

Setters typically operate on all of the

selected DOM elements.

<ul> <li style="font-size: 10px">10px font size</li> <li style="font-size: 20px">20px font size</li> <li style="font-size: 30px">30px font size</li> </ul> $("li").css("font-size"); // returns '10px' $("li").css("font-size", "15px"); // sets all selected elements to ‘15px' <ul> <li style="font-size: 15px">10px font size</li> <li style="font-size: 15px">20px font size</li> <li style="font-size: 15px">30px font size</li> </ul>

CS 380 12

slide-13
SLIDE 13

jQuery method parameters

getter syntax: setter syntax: multi-setter syntax: modifier syntax:

CS 380 13

$("#myid").css(propertyName); $("#myid").css(propertyName, value); $("#myid").css({ 'propertyName1': value1, 'propertyName2': value2, ... }); $("#myid").css(propertyName, function(idx, oldValue) { return newValue; });

slide-14
SLIDE 14

jQuery method returns

method return type $("#myid"); jQuery object $("#myid").children(); jQuery object $("#myid").css("margin-left"); String $("#myid").css("margin-left", "10px"); jQuery object $("#myid").addClass("special"); jQuery object

CS 380 14

slide-15
SLIDE 15

More node manipulation with jQuery

jQuery method functionality .hide() toggle CSS display: none on .show() toggle CSS display: none off .empty() remove everything inside the element, innerHTML = "" .html() get/set the innerHTML without escaping html tags .text() get/set the innerHTML, HTML escapes the text first .val() get/set the value of a form input, select, textarea, ... .height() get/set the height in pixels, returns a Number .width() get/set the width in pixels, return a Number

CS 380 15

slide-16
SLIDE 16

Creating new nodes Creating new nodes

name description document.createElement("tag") creates and returns a new empty DOM node representing an element of that type document.createTextNode("text") creates and returns a text node containing given text

CS 380 16

// create a new <h2> node var newHeading = document.createElement("h2"); newHeading.innerHTML = "This is a heading"; newHeading.style.color = "green";

slide-17
SLIDE 17

Modifying the DOM tree

name description appendChild(node) places given node at end of this node's child list insertBefore(new, old) places the given new node in this node's child list just before old child removeChild(node) removes given node from this node's child list replaceChild(new, old) replaces given child with new node

CS 380 17

var p = document.createElement("p"); p.innerHTML = "A paragraph!"; document.getElementById("myid").appendChild(p);

slide-18
SLIDE 18

Removing a node from the page

CS 380 18

var bullets = document.getElementsByTagName("li"); for (var i = 0; i < bullets.length; i++) { if (bullets[i].innerHTML.indexOf("child") >= 0) { bullets[i].parentNode.removeChild(bullets[i]); } }

slide-19
SLIDE 19

jQuery manipulation methods

http://api.jquery.com/category/manipul

ation/

CS 380 19

slide-20
SLIDE 20

Create nodes in jQuery

The $ function to the rescue again

CS 380 20

var newElement = $("<div>"); $("#myid").append(newElement);

The previous example becomes with jQuery

$("li:contains('child')").remove();

slide-21
SLIDE 21

Creating complex nodes in jQuery

The terrible way, this is no better than

innerHTML hacking

The bad way, decent jQuery, but we can

do better

The good way

CS 380 21

$("<p id='myid' class='special'>My paragraph is awesome!</p>") $("<p>") .attr("id", "myid") .addClass("special") .text("My paragraph is awesome!"); $("<p>", { "id": "myid", "class": "special", "text": "My paragraph is awesome!" });

slide-22
SLIDE 22

jQuery $ function signatures

Responding to the page ready event

$(function);

Identifying elements

$("selector", [context]);

Upgrading DOM

elements=$(elements);

Creating new elements

$("<html>", [properties]);

CS 380 22

slide-23
SLIDE 23

Practice: Codeacademy Practice: Codeacademy

http://www.codecademy.com/courses/w eb-beginner-en- GfjC6/0?curriculum_id=50a3fad8c7a77 0b5fd0007a1#!/exercises/0

CS 380 23

slide-24
SLIDE 24

jQuery Visual Effects jQuery Visual Effects

CS 380 24

slide-25
SLIDE 25

Visual Effects Visual Effects

CS 380 25

slide-26
SLIDE 26

Visual effects Visual effects

Getting attention

Highlight effect Scale effect Pulsate effect Shake effect

CS 380 26

slide-27
SLIDE 27

Applying effects to an element

the effect will begin to animate on screen

(asynchronously) the moment you call it

One method is used behind the scenes to do most of

the work, animate()

CS 380 27

element.effect(); // for some effects element.effect(effectName); // for most effects $("#sidebar").slideUp(); // No need to loop over selected elements, as usual $("#results > button").effect("pulsate");

slide-28
SLIDE 28

Effect options

CS 380 28

element.effect(effectName, {

  • ption: value,
  • ption: value,

... }); $("#myid").effect("explode", { "pieces": 25 });

slide-29
SLIDE 29

Effects chaining

Effects can be chained like any other jQuery

methods

Effects are queued, meaning that they will wait until

the previous effects finish

CS 380 29

$('#demo_chaining') .effect('pulsate') .effect('highlight') .effect('explode');

slide-30
SLIDE 30

Effect duration

You can specify how long an effect takes

with the duration option

Almost all effects support this option Can be one of slow, normal, fast or any

number in milliseconds

CS 380 30

$('#myid').effect('puff', {}, duration)

slide-31
SLIDE 31

Custom effects - animate()

You can animate any numeric property you

want

You can also animate these

color background-color

CS 380 31

$('#myid').animate(properties, [duration]); $('#myid') .animate({ 'font-size': '80px', 'color': 'green' }, 1000);

slide-32
SLIDE 32

Custom effects easing

Your animations don't have to progress

linearly

There are many other options

slide easeInSin

CS 380 32

$('#myid') .animate(properties, [duration], [easing]); $('#myid') .animate({ 'font-size': '80px', 'color': 'green' }, 1000, 'easeOutBounce');

slide-33
SLIDE 33

Better Custom Effects* - toggleClass()

* if you don't need easing or special options use the toggleClass method with its

  • ptional duration parameter

CS 380 33

.special { font-size: 50px; color: red; } $('#myid').toggleClass('special', 3000);

slide-34
SLIDE 34

Adding delay()

CS 380 34

$('#myid') .effect('pulsate') .delay(1000) .slideUp() .delay(3000) .show('fast');

slide-35
SLIDE 35

Effect complete event

All effects can take a fourth optional callback

parameter that is called when the animation ends

the callback can use the this keyword as usual to

address the element the effect was attached to

CS 380 35

$("#myid").effect('puff', [options], [duration], [function]); $('#myid').effect('clip', {}, 'default', function() { alert('finished'); });

slide-36
SLIDE 36

Drag and drop

jQuery UI provides several methods for creating drag-and-drop functionality:

Sortable : a list of items that can be

reordered

Draggable : an element that can be

dragged

Dropable : elements on which

a Draggable can be dropped

CS 380 36

slide-37
SLIDE 37

Sortable

specifies a list (ul, ol) as being able to be

dragged into any order

with some stylings you can get rid of the

list look and sort any grouping of elements

implemented internally using Draggables

and Droppables

to make a list un-sortable again,

call .sortable('destroy') on the sortable element

CS 380 37

$('#myid ul').sortable([options]);

slide-38
SLIDE 38

Sortable Sortable

CS 380 38

slide-39
SLIDE 39

Sortable demo

CS 380 39

<ol id="simpsons"> <li>Homer</li> <li>Marge</li> <li>Bart</li> <li>Lisa</li> <li>Maggie</li> </ol> $(function() { $("#simpsons").sortable(); });

slide-40
SLIDE 40

Sortable list events

event description change when any list item hovers over a new position while dragging update when a list item is dropped into a new position (more useful)

CS 380 40

$(function() { $("simpsons").sortable({ 'update': function(event, ui) { // Do stuff here } }); });

slide-41
SLIDE 41

Sortable list events example

CS 380 41

$(function() { $("#simpsons").sortable({ 'update': listUpdate }); }); function listUpdate(event, ui) { // can do anything I want here; effects, //an Ajax request, etc. ui.item.effect('shake'); }

slide-42
SLIDE 42

Sortable "methods"

jQuery plugins, like jQuery UI have an odd

syntax for methods

sortable methods

destroy disable enable

  • ption

refresh cancel

CS 380 42

$('#my_list').sortable('methodName', [arguments]); // Some examples $('#my_list').sortable('destroy'); $('#my_list').sortable('option', 'cursor', 'pointer');

slide-43
SLIDE 43

Draggable

specifies an element as being able to

be dragged

CS 380 43

$('#myid').draggable([options]);

slide-44
SLIDE 44

Draggable

CS 380 44

slide-45
SLIDE 45

Draggable example

CS 380 45

<div id="draggabledemo1">Draggable demo 1. Default options. </div> <div id="draggabledemo2">Draggable demo 2. {'grid': [40,40], 'revert': true} </div> $('#draggabledemo1').draggable(); $('#draggabledemo2').draggable({ 'revert': true, 'grid': [40, 40] });

slide-46
SLIDE 46

Droppable

specifies an element as being able to

receive draggables

CS 380 46

$('#myid').droppable([options]);

slide-47
SLIDE 47

Droppable

CS 380 47

slide-48
SLIDE 48

Drag/drop shopping demo

CS 380 48

<img id="shirt" src="images/shirt.png" alt="shirt" /> <img id="cup" src="images/cup.png" alt="cup" /> <div id="droptarget"></div> $('#shirt').draggable(); $('#cup').draggable(); $('#droptarget').droppable({ 'drop': productDrop }); function productDrop(event, ui) { alert("You dropped " + ui.item.attr('id')); }

slide-49
SLIDE 49

Auto-completing text fields

Scriptaculous offers ways to make a text box that auto-completes based on prefix strings :

Local Autocompleter Ajax Autocompleter: The autocompleter will make

AJAX calls to the given URL providing a term parameter with the current value of the input field

CS 380 49

var data = ["foo", "food", "foobar", "fooly", "cake"]; $('#my_text_input').autocompleter({ 'source': data }); $('#my_text_input').autocompleter({ 'source': 'http://foo.com/webservice.php' });

slide-50
SLIDE 50

Using a local autocompleter

pass the choices as an array of strings You can also pass an array of objects

with label and value fields

the widget injects a ul elements full of choices as you

type

use the appendTo option to specify where the list is

inserted

CS 380 50

var data = ["foo", "food", "foobar", "foolish", "foiled", "cake"]; $('#myid').autocompleter({ 'source': data });

var data = [ {'label': 'Track and Field', 'value': 'track'}, {'label': 'Gymnastics', 'value': 'gymnastics'}, ... ];

slide-51
SLIDE 51

Local autocompleter demo

CS 380 51

<input id="bands70s" size="40" type="text" /> <div id="bandlistarea"></div> $('#bands70s').autocomplete({ 'source': data, 'appendTo': '#bandlistarea' });

slide-52
SLIDE 52

Using an AJAX autocompleter

when you have too many choices to hold them all in an array,

you can instead fetch subsets of choices from a server using AJAX

instead of passing choices as an array, pass a URL from which

to fetch them

the AJAX call is made with a term parameter the choices are sent back from the server as a JSON array of strings

  • r array of objects with label and valuefields

CS 380 52

$('#my_input').autocomplete({ 'source': 'http://foo.com/webservice.php' }); if (!isset($_GET['term'])) { header('HTTP/1.1 400 Invalid Request – No term parameter provided'); die('No term parameter provided.'); } $term = $_GET['term']; $results = getCompleterResults($term); // an array() return value print json_encode($results);

slide-53
SLIDE 53

accordion widget

your HTML should be pairs of headers with

anchors and containers

make the parent of these pairs

an accordion

CS 380 53

<div class="accordion"> <h1><a href="#">Section 1</a></h1> <div>Section 1 Content</div> ... </div> $(function() { $( "#accordion" ).accordion(); });

slide-54
SLIDE 54

tabs widget

your HTML should be a list of link to

element on your page

the href attributes should match ids of

elements on the page

CS 380 54

<div class="tabs"> <ul> <li><a href="#tab1">Tab 1</a></li> <li><a href="#tab2">Tab 2</a></li> ... </ul> <div id="tab1">Tab 1 Content</div> <div id="tab2">Tab 2 Content</div> ... </div>

$(function() { $( "#tabs" ).tabs(); });

slide-55
SLIDE 55

jQuery UI theming

jQuery UI uses classes gratuitously so that

we can style our widgets however we want

there are two kinds of classes used

framework classes which exist for all widgets widget specific classes

CS 380 55

kind classes Layout Helpers .ui-helper-hidden, .ui-helper- reset, .ui-helper-clearfix Widget Containers .ui-widget, .ui-widget-header, .ui- widget-content Interaction States .ui-state-default, .ui-state- hover, .ui-state-focus, .ui-state- active