Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS3220 Web and Internet Programming Client-Side JavaScript and jQuery

Similar presentations


Presentation on theme: "CS3220 Web and Internet Programming Client-Side JavaScript and jQuery"— Presentation transcript:

1 CS3220 Web and Internet Programming Client-Side JavaScript and jQuery
Chengyu Sun California State University, Los Angeles

2 Client-Side JavaScript Example
Event handler onclick See Section , HTML 5 Specification Embed JavaScript in HTML using the <script> tag Link to external file or enclose code directly Can appear any number of times in both <head> and <body> HTML 5 no longer requires the type attribute Run inside a browser

3 Processing an HTML Document
<html> <head><title>JavaScript Example</title></head> <body> <h1>JavaScript Example</h1> <p>Some content.</p> </body> </html> As a text file – very difficult As an object

4 Document Object Model (DOM)
Representing documents as objects so they can be processed more easily by a programming language

5 DOM Representation Common terminology:
document <html> <head> <body> <title> <h1> <p> “JavaScript Example” “JavaScript Example” “Some content.” Common terminology: parent, child, sibling, ancestor, descendant

6 About DOM Browser is responsible for parsing HTML document and creating the corresponding DOM object Changes to the DOM object are reflected on the page display

7 Manipulate a Document Find Elements Modify Elements Create Elements

8 Find Elements document.getElementById() document.getElementsByName()
document.getElementsByTagName()

9 Modify Elements ... HTMLElement properites and methods IE
innerHTML innerText insertAdjacentHTML() insertAdjacentText() Netscape/Mozilla Element-specific

10 ... Modify Elements node setAttribute(), removeAttribute()
appendChild(), removeChild() insertBefore(), replaceChild()

11 Create Elements document createElement() createTextNode()

12 Problems with Plain Client-Side JavaScript
Verbose code for even simple tasks Browser compatibility issues

13 jQuery: Make Client-Side JavaScript Great Again
Hide browser incompatibility Greatly simplify/improve DOM operations, event handling, and asynchronous request and response Usage statistics -

14 jQuery Example Usage jQuery wrapper Selectors Elements
Events and event handling DOM Manipulation

15 jQuery Wrapper jQuery() or $()
Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. $( "input[name='firstName']" ) $( "#who" ) $( "#t1" ) Selector

16 Basic Selectors By id By tag name By CSS class By attribute $(“#foo”)
$(“div”) By CSS class $(“.foo”) By attribute $(“[name]”) $(“[name=‘joe’]”)

17 Combine Selectors Select all the <div> elements with CSS class foo and an attribute bar $(“div.foo[bar]”) Select all the <div> elements, and all the elements with CSS class foo, and all the elements with an attribute bar $(“div,.foo,[bar]”)

18 What Can We Do With An Element
Get and set html(), text() attr() prop() val() Manipulate CSS addClass() removeClass() toggleClass() hasClass() Property tagName <input name=“username” value=“cysun” /> Attribute name val()

19 Typical Event and Event Handling in jQuery
Event Handler $("#click").click( function(){ }); Unobtrusive JavaScript: separate style, behavior, and structure. <button id="click“ onclick="display();"> Click Me</button>

20 Other Events Mouse events Keyboard events Form events Browser events
.click() .dbclick() Keyboard events .keyup() .keydown() .keypress() Form events .change() .submit() Browser events .resize() Document events

21 Document Ready Event Triggered when the DOM hierarchy of the HTML document is fully constructed $( document ).ready( handler ) $().ready( handler ) (not recommended) $( handler )

22 DOM Manipulation Insertion Removal Replacement Around (i.e. parent)
Inside (i.e. children) append() Outside (i.e. sibling) Removal remove() Replacement Example: $("#t1").append("<tr><td>John</td><td>Doe</td></tr>");

23 Example: Language Question
What program languages do you know? + - -

24 Attribute Selectors Exists Value match Value not match Prefix match
$(“[name]”) Value match $(“[name=‘a’]”) Value not match $(“[name!=‘a’]”) Prefix match $(“[name|=‘a’]”) Contains word ~= Contains substring *= Starts with ^= Ends with $= All comparisons are case-sensitive.

25 Form Selectors :input – all input, textarea, select and button elements :button, :checkbox, :file, :image, :password, :radio, :reset, :submit, :text :checked for checkboxes and radio buttons :selected for <option> :enabled :disabled :focused

26 Hierarchical Selectors
Children $(“parent > children”) Descendants $(“ancestor descendants”) Next sibling $(“prev + next”) Next siblings $(“prev ~ siblings”) There is no parent or ancestor selector.

27 Filters Applied to selectors to further refine the selection Examples:
$(“table:last”) $(“p:contains(‘hello’)”) $(“*:hidden”) $(“:hidden”)

28 Index-Based Filters :first, :last, :even, :odd :eq(n) – nth elements
:gt(n) – all elements after the nth element :lt(n) – all elements before the nth elements Index starts from 0.

29 Child Filters <table> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><th>a</th><td>b</td><td>c</td></tr> </table> $(“td:first”) $(“td:eq(1)”) $(“td:first-child”) $(“td:first-of-type”) $(“td:nth-child(1)”) $(“td:nth-of-type(1)”)

30 Other Filters Contains text Contains element Has child Has no child
:has(selector) Has child :parent Has no child :empty No matching :not(selector) State-based filters :focused :animated :hidden :visible

31 Access Selected Elements
.each(function) iterate through the selected elements function(index, element) index: the index of the current element element: current element this: current element The difference between element, this, and $(this)?? .get(index) and .get() retrieve one or all of the selected elements (as an array)

32 Example: Tic Tac Place X and O alternately on the board
Count Place X and O alternately on the board Count the number of X’s and O’s on the board Using :contains() Using .each(function)

33 About jQuery Object … $(selector)  jQuery object
A jQuery object may contain multiple HMTL elements, e.g. $(“td”) Most of jQuery object methods apply to each of the selected elements, e.g. $(“td”).click(function(){}) $(“tr”).append(“<td></td>”) .each(function) can be used to apply a user-defined function to each of the selected element

34 … About jQuery Object Distinguish between HTML elements and jQuery objects this in an event handler or .each(function) is an HTML element Wrapping $() around an HTML element turns it into a jQuery object (so we can use jQuery object methods like .click(), .append(), and so on)

35 Traversing From selected elements to more (or less) elements Examples:
$(“#cell”).closest(“tr”) $(“#row”).find(“td[name=‘foo’]”) $(“div”).filter(“.foo”)

36 Tree Traversal Find one or more siblings Find children Find parent
Find descendants .find() Find Ancestors .parents() Find closest ancestor .closest() Find one or more siblings .prev() .prevAll() .next() .nextAll() .siblings() All methods take an optional selector argument.

37 Filtering “Filter” is part of selector; “filtering” applies to the selected elements .first(), .last() .eq(), .slice() .has(), not() .filter() – filter by selector, function, or elements

38 Effects .hide(), .show(), .toggle() Sliding effects Fading effects
Custom effects

39 Example: Taking Attendance
Absence Week 1 Week 2 Week 3 John 1 Jane 2 Tom

40 jQuery Tips Use CSS class to “label” certain elements to make selecting them easier (and the code more readable), e.g. $(“td.absence”) Most jQuery methods return the jQuery object itself so we can chain multiple method calls together, e.g. $(this).removeClass(“green”).addClass(“red”) $(this).prevAll().filter(“.absence”) $(“div”).append(“<p>first</p>”).append(“<p>second</p>”)


Download ppt "CS3220 Web and Internet Programming Client-Side JavaScript and jQuery"

Similar presentations


Ads by Google