CS 3220 Web and Internet Programming ClientSide Java
CS 3220 Web and Internet Programming Client-Side Java. Script and j. Query Chengyu Sun California State University, Los Angeles
Client-Side Java. Script Example Event handler onclick n See Section 6. 1. 5. 2, HTML 5 Specification Embed Java. Script in HTML using the <script> tag n n n 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
Processing an HTML Document <html> <head><title>Java. Script Example</title></head> <body> <h 1>Java. Script Example</h 1> <p>Some content. </p> </body> </html> As a text file – very difficult As an object
Document Object Model (DOM) Representing documents as objects so they can be processed more easily by a programming language
DOM Representation document <html> <head> <title> “Java. Script Example” <body> <h 1> “Java. Script Example” Common terminology: parent, child, sibling, ancestor, descendant <p> “Some content. ”
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
Manipulate a Document Find Elements Modify Elements Create Elements
Find Elements document. get. Element. By. Id() document. get. Elements. By. Name() document. get. Elements. By. Tag. Name()
Modify Elements. . . HTMLElement properites and methods n IE w inner. HTML w inner. Text w insert. Adjacent. HTML() w insert. Adjacent. Text() n Netscape/Mozilla w inner. HTML n Element-specific
. . . Modify Elements node n n n set. Attribute(), remove. Attribute() append. Child(), remove. Child() insert. Before(), replace. Child()
Create Elements document n n create. Element() create. Text. Node()
Problems with Plain Client-Side Java. Script Verbose code for even simple tasks Browser compatibility issues
j. Query: Make Client-Side Java. Script Great Again Hide browser incompatibility Greatly simplify/improve DOM operations, event handling, and asynchronous request and response Usage statistics https: //trends. builtwith. com/javascript/j avascript-library
j. Query Example Usage j. Query wrapper Selectors Elements Events and event handling DOM Manipulation
j. Query Wrapper j. Query() or $() n 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='first. Name']" ) $( "#who" ) $( "#t 1" ) Selector
Basic Selectors By id n $(“#foo”) By tag name n $(“div”) By CSS class n $(“. foo”) By attribute n n $(“[name]”) $(“[name=‘joe’]”)
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]”)
What Can We Do With An Element Get and set n n Manipulate CSS html(), text() attr() prop() val() n n add. Class() remove. Class() toggle. Class() has. Class() Property tag. Name <input name=“username” value=“cysun” /> Attribute name val()
Typical Event and Event Handling in j. Query Event Handler $("#click"). click( function(){. . . }); Unobtrusive Java. Script: separate style, behavior, and structure. <button id="click“ onclick="display(); "> Click Me</button>
Other Events Mouse events n . click(). dbclick() n … n Keyboard events n . keyup(). keydown(). keypress() n … n n Form events n . change(). submit() n … n Browser events n . resize() n … Document events
Document Ready Event Triggered when the DOM hierarchy of the HTML document is fully constructed $( document ). ready( handler ) $( handler ) (not recommended)
DOM Manipulation Insertion n n Around (i. e. parent) Inside (i. e. children) w append() w… n Removal n n remove() … Replacement Outside (i. e. sibling) Example: $("#t 1"). append("<tr><td>John</td><td>Doe</td></tr>");
Example: Language Question What program languages do you know? + -
Attribute Selectors Exists n Contains word $(“[name]”) Value match n $(“[name=‘a’]”) Value not match n $(“[name!=‘a’]”) Prefix match n $(“[name|=‘a’]”) n ~= Contains substring n *= Starts with n ^= Ends with n $= All comparisons are case-sensitive.
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
Hierarchical Selectors Children n $(“parent > children”) Descendants n $(“ancestor descendants”) Next sibling n $(“prev + next”) Next siblings n $(“prev ~ siblings”) There is no parent or ancestor selector.
Filters Applied to selectors to further refine the selection Examples: $(“table: last”) $(“p: contains(‘hello’)”) $(“*: hidden”) $(“: hidden”)
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.
Child Filters http: //api. jquery. com/category/selector s/child-filter-selectors/ <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)”)
Other Filters Contains text n : contains(‘text’) Contains element n : has(selector) Has child n : parent Has no child n : empty No matching n : not(selector) State-based filters n n : focused : animated : hidden : visible
Example: Tic Tac O X X X O Count Place X and O alternately on the board Count the number of X’s and O’s on the board n n Using : contains() Using. each(function)
Access Selected Elements Individually. each(function) iterate through the selected elements n function(index, element) w w index: the index of the current 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)
About j. Query Object … $(selector) j. Query object A j. Query object may contain multiple HMTL elements, e. g. $(“td”) Most of j. Query object methods apply to each of the selected elements, e. g. n n $(“td”). click(function(){}) $(“tr”). append(“<td></td>”) . each(function) can be used to apply a user-defined function to each of the selected element
… About j. Query Object Distinguish between HTML elements and j. Query objects n n this in an event handler or. each(function) is an HTML element Wrapping $() around an HTML element turns it into a j. Query object (so we can use j. Query object methods like. click(), . append(), and so on)
Traversing From selected elements to more (or less) elements Examples: $(“#cell”). closest(“tr”) $(“#row”). find(“td[name=‘foo’]”) $(“div”). filter(“. foo”)
Tree Traversal Find children n . children() Find parent n . parent() Find descendants n . find() Find one or more siblings n n n Find Ancestors n . parents() n n . prev(). prev. All(). next. All(). siblings() Find closest ancestor n . closest() All methods take an optional selector argument.
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
Effects. hide(), . show(), . toggle() Sliding effects Fading effects Custom effects
Example: Taking Attendance Absence John 1 Jane 2 Tom Week 1 Week 2 Week 3
j. Query Tips Use CSS class to “label” certain elements to make selecting them easier (and the code more readable), e. g. $(“td. absence”) Most j. Query methods return the j. Query object itself so we can chain multiple method calls together, e. g. n n n $(this). remove. Class(“green”). add. Class(“red”) $(this). prev. All(). filter(“. absence”) $(“div”). append(“<p>first</p>”). append(“<p>s econd</p>”)
- Slides: 40