Download presentation
Presentation is loading. Please wait.
1
Session II Chapter 8 – Fast Start with jQuery
JavaScript & jQuery Session II Chapter 8 – Fast Start with jQuery Master a Skill / Learn for Life
2
Class Outline Introduction to jQuery jQuery Frameworks
Document Object Model (DOM) jQuery Basic Selectors jQuery Calling Methods jQuery Advanced Selectors Traversing Looping & Chaining jQuery Methods Filtering HTML CSS Miscellaneous jQuery Anonymous Functions Events Using Events the jQuery Way More jQuery Event Concepts Advance Event Management W3CSchool Exercises Examples List Application FAQ Application Image Swap Application Image Rollover Application Student Exercises List Application Button 8-2 - Image Rollovers 8-3 - Book List Application 12/29/2018 Copyright © Carl M. Burnett
3
JavaScript Frameworks
Programming Library Includes: support programs, compilers, code libraries, tool sets, and application programming interfaces (APIs) inversion of control default behavior extensibility non-modifiable framework code jQuery Midori MooTools Webix AngularJS Comparisons of JavaScript Frameworks 12/29/2018 Copyright © Carl M. Burnett
4
Intro to jQuery jQuery Files you need for jQuery applications
The two jQuery libraries Files you need for jQuery applications jQuery (the core library) jQuery UI (User Interface) The jQuery JavaScript file The jQuery UI JavaScript file The jQuery UI stylesheet What jQuery offers Two ways to include the jQuery files Dozens of functions that make it easier to add JavaScript features to your web pages Functions that are tested for cross-browser compatibility Use a Content Delivery Network (CDN) like Google, Microsoft, or jQuery. Download and deploy on your web server. jQuery 12/29/2018 Copyright © Carl M. Burnett
5
Including jQuery files on your Web Site
Download jQuery to your website from jQuery Site Include jQuery 3.1.1 <!-- include the jQuery and jQuery UI JavaScript files --> <script src="jquery min.js"></script> <script src="jquery-ui.js"></script> Include slim version of jQuery 3.1.1 <!-- include the jQuery Slim Version --> <script src="jquery slim.min.js"></script> Include jQuery UI Stylesheet <!-- include the jQuery UI stylesheet --> <link rel="stylesheet" href="jquery.ui.all.css"> 12/29/2018 Copyright © Carl M. Burnett
6
How to include the jQuery files from a CDN
Include jQuery from Content Deilivery Network (CDN) <!-- include the jQuery and jQuery UI JavaScript files --> <script src=" </script> Note - The href and src attributes should be coded on a single line. 12/29/2018 Copyright © Carl M. Burnett
7
SRI checking with the jQuery CDN
Subresource Integrity Checking (SRI) SRI is a new W3C specification that allows web developers to ensure that resources hosted on third-party servers have not been tampered with. Subresource Integrity different to HTTPS Check out SRI on caniuse.com to see specific browser version support information.
8
The Document Object Model (DOM) for a Web Page
Objects Properties Methods Inheritance Data Encapsulation HTML <html> </html> Head <head> </head> Body <body> </body> Title <title> </title> section <section> </section> h1 <h1> </h1> ul <ul> </ul> p <p> </p> Text li <li> </li> What is important to understand is the Document Object Model. But first let review what makes up an object. In Chapter 1 we covered what a object is and what characteristics a object possess. 1. Object posses properties. These can be such things as size, color, and shape. 2. Object posses methods. These can be move, pour, open and close. 3. Objects can inherit properties, method and data from a parent object. 4. And objects can encapsulated data by using metadata. With this understanding about the characteristics about an object we can apply this same understanding to the objects that make up a web page. In this case, the overarching parent object of a web page is the HTML declaration. This object is created with the html opening and closing tags. The tags create the HTML object and all object oriented characteristics of the HTML object can be changed based on triggering events. In order for these characteristics to be changed on the client side, a scripting language must be used. In the case, the standard is JavaScript and this language is interpreted through the JavaScript interpreter engine that is part of all browsers. The next object in the web page document object model is the head. This object is created by the head opening and closing tags. It can inherit any characteristics from its parent object, the HTML object. The next object is the body. This object is created by the body opening and closing tags. It can inherit any characteristics from its parent object, the HTML object. A child object of the Head object is the Title object. This object is created by the title opening and closing tags. It can inherit any characteristics from its parent object, the Head object. The next object is the new HTML5 document object called a section. This object is created by the section opening and closing tags. It can inherit any characteristics from its parent object, the body object. The next objects can be many objects to define the content of body or section or any other object container. These objects inlcude the h1 object, the ul object and the p object. These objects are created by the h1, ul, and p opening and closing tags. That can inherit any characteristics from its parent object, the body object. The last objects are the li objects that are created with the li tags. They can inherit any characteristics from its parent object, the ul object. Each of these object can contain data and for the h1 object, the ul li objects and p object all contain textual data that can be changed with the JavaScript language. 12/29/2018 Copyright © Carl M. Burnett
9
Basic jQuery Selectors
A Element selector that selects HTML elements. $("h1") An id selector selects HTML elements with a id attribute. $("#accordion") A class selector selects HTML element with a class attribute. $(".fadein") 12/29/2018 Copyright © Carl M. Burnett
10
jQuery Syntax for Calling a Method
Basic Syntax for Calling a jQuery Method: $(selector).methodName(parameters) A jQuery method() to be performed on the element(s) A (selector) to "query (or find)" HTML elements A $ sign to define/access jQuery
11
Examples that call jQuery methods
How to get the value from a text box var gallons = $("#gallons").val(); How to set the value for an input element $("#gallons").val(""); How to set the text in an element $("# _address_error").text(“ address is required"); How to set the text for the next sibling with object chaining $("#last_name").next().text("Last name is required"); How to submit a form $("#join_list").submit(); How to move the focus to a form control or link $("# _address").focus();
12
Advanced jQuery Selectors
Descendent Selectors - $('#navBar a') Child Selectors - $('body > p') Adjacent Sibling Selectors - $('h2 + div') Attribute Selectors - $('img[alt]')
13
jQuery Traversing Parent Child Descendant Adjacent <div>
<ul> <li> <b> <span> Parent Child Descendant Adjacent
14
jQuery Traversing Selector Description add()
Adds elements to the set of matched elements addBack() Adds the previous set of elements to the current set children() Returns all direct children of the selected element closest() Returns the first ancestor of the selected element contents() Returns all direct children of the selected element (including text and comment nodes) each() Executes a function for each matched element end() Ends the most recent filtering operation in the current chain, and return the set of matched elements to its previous state find() Returns descendant elements of the selected element
15
jQuery Traversing Selectors
Description is() Checks the set of matched elements against a selector/element/jQuery object, and return true if at least one of these elements matches the given arguments map() Passes each element in the matched set through a function, producing a new jQuery object containing the return values next() Returns the next sibling element of the selected element nextAll() Returns all next sibling elements of the selected element nextUntil() Returns all next sibling elements between two given arguments offsetParent() Returns the first positioned parent element parent() Returns the direct parent element of the selected element parents() Returns all ancestor elements of the selected element
16
jQuery Traversing Selectors
Description parentsUntil() Returns all ancestor elements between two given arguments prev() Returns the previous sibling element of the selected element prevAll() Returns all previous sibling elements of the selected element prevUntil() Returns all previous sibling elements between two given arguments siblings() Returns all sibling elements of the selected element slice() Reduces the set of matched elements to a subset specified by a range of indices
17
jQuery Looping & Chaining
Automatic Loops - $('#slideshow img').hide(); Chaining Functions $('#popUp').width(300).height(300); $('#popUp').width(300).height(300).text('Hi!').fadeIn(1000); $('#popUp').width(300) height(300) text('Message') .fadeIn(1000);
18
jQuery Methods HTML – Manipulating HTML Content
CSS – Manipulating CSS Styling Filtering – Filtering content Miscellaneous Methods
19
jQuery HTML Methods Method Description addClass()
Adds one or more class names to selected elements after() Inserts content after selected elements append() Inserts content at the end of selected elements appendTo() Inserts HTML elements at the end of selected elements attr() Sets or returns attributes/values of selected elements before() Inserts content before selected elements clone() Makes a copy of selected elements css() Sets or returns one or more style properties for selected elements detach() Removes selected elements (keeps data and events)
20
jQuery HTML Methods Method Description empty()
Removes all child nodes and content from selected elements hasClass() Checks if any of the selected elements have a specified class name height() Sets or returns the height of selected elements html() Sets or returns the content of selected elements innerHeight() Returns the height of an element (includes padding, but not border) innerWidth() Returns the width of an element (includes padding, but not border) insertAfter() Inserts HTML elements after selected elements insertBefore() Inserts HTML elements before selected elements offset() Sets or returns the offset coordinates for selected elements (relative to the document)
21
jQuery HTML Methods Method Description offsetParent()
Returns the first positioned parent element outerHeight() Returns the height of an element (includes padding and border) outerWidth() Returns the width of an element (includes padding and border) position() Returns the position (relative to the parent element) of an element prepend() Inserts content at the beginning of selected elements prependTo() Inserts HTML elements at the beginning of selected elements prop() Sets or returns properties/values of selected elements remove() Removes the selected elements (including data and events) removeAttr() Removes one or more attributes from selected elements
22
jQuery HTML Methods Method Description removeClass()
Removes one or more classes from selected elements removeProp() Removes a property set by the prop() method replaceAll() Replaces selected elements with new HTML elements replaceWith() Replaces selected elements with new content scrollLeft() Sets or returns the horizontal scrollbar position of selected elements scrollTop() Sets or returns the vertical scrollbar position of selected elements text() Sets or returns the text content of selected elements toggleClass() Toggles between adding/removing one or more classes from selected elements unwrap() Removes the parent element of the selected elements
23
jQuery HTML Methods for Manipulating Content
Description val() Sets or returns the value attribute of the selected elements (for form elements) width() Sets or returns the width of selected elements wrap() Wraps HTML element(s) around each selected element wrapAll() Wraps HTML element(s) around all selected elements wrapInner() Wraps HTML element(s) around the content of each selected element
24
jQuery CSS Methods Return a CSS Property – Set a CSS Property
css("propertyname"); $("p").css("background-color"); Set a CSS Property css("propertyname","value"); $("p").css("background-color", "yellow"); Set Multiple CSS Properties css({"propertyname":"value","propertyname":"value",...}); $("p").css({"background-color": "yellow", "font-size": "200%"});
25
JavaScript Object Literal
Beginning of Object Separates property from value { 'background-color' , '#FF0000', 'border' , '2px solid #FE0037' } Separate on property/value pair from the next pair Property Value End of Object JavaScript treats the object literal as a single block of information—just as an array is a list of values.
26
Using JavaScript Object Literal
How to use an object literal with the css() function $('#highlightedDiv').css({ 'background-color' : '#FF0000', 'border' : '2px solid #FE0037' });
27
jQuery CSS Methods Method Description addClass()
Adds one or more classes to the selected elements removeClass() Removes one or more classes from the selected elements toggleClass() Toggles between adding/removing classes from the selected elements
28
jQuery Filtering Methods
Description eq() Returns an element with a specific index number of the selected elements filter() Reduce the set of matched elements to those that match the selector or pass the function's test even() Selects each element with an even index number (like: 0, 2, 4, etc.). odd() Selects each element with an odd index number (like: 1, 3, 5, etc.). first() Returns the first element of the selected elements last() Returns the last element of the selected elements not() Remove elements from the set of matched elements has() Returns all elements that have one or more elements inside of them
29
jQuery Filtering Methods
Description :contains() locates elements that contain specific text :hidden() locates elements that are hidden :visible() locates elements that are visible on the page
30
jQuery Miscellaneous Methods
Description data() Attaches data to, or gets data from, selected elements each() Execute a function for each matched element get() Get the DOM elements matched by the selector index() Search for a given element from among the matched elements $.noConflict() Release jQuery's control of the $ variable $.param() Create a serialized representation of an array or object (can be used as URL query string for AJAX requests) removeData() Removes a previously-stored piece of data size() Deprecated in version 1.8. Return the number of DOM elements matched by the jQuery selector toArray() Retrieve all the DOM elements contained in the jQuery set, as an array
31
jQuery Anonymous Functions
Each() Function A function containing the steps that you want performed on each selected element. Used to loop through elements Unlike functions you name - you don’t give it a name. Each Function’s Basic Structure $('selector').each(function() { // code goes in here }); Anonymous Function’s Basic Structure function() { //code goes here }
32
jQuery Anonymous Functions
Start of each() function Anonymous function $('selector').each(function() { // your code goes in here }); Beginning of anonymous function End of statement End of anonymous function End of each function Anonymous Function Example $('img').each(function() { alert('I found an image'); });
33
jQuery this and $(this)
Used when using the each() function Accessing or setting attributes of each element e.g. - find the URL for each external link. To access the current element through each loop - a special keyword called “this”. “this” keyword refers to whatever element is calling the anonymous function. First time through the loop, “this” refers to the first element in the jQuery selection Second time through the loop, “this” refers to the second element.
34
jQuery this and $(this)
<div id="bibliography"> <h3>Web pages referenced in this article</h3> <ul id="bibList"> </ul> </div> The $(this) keyword lets you access the current element each time through the loop. $('a[href^= { var extLink = $(this).attr('href'); }); $('a[href^=" list of all links pointing outside your site using the “a” attribute selector Appending a new list item to the <ul> tag $('a[href^= { var extLink = $(this).attr('href'); $('#bibList').append('<li>' + extLink + '</li>'); }); $('a[href^=" Add each() function to loop through selection $('a[href^=" { }); Add an anonymous function:
35
The JavaScript DOM Event Cycle
Page Loaded Event Occurs Script Executes DOM Modified Page Updated 12/29/2018 Copyright © Carl M. Burnett
36
jQuery Events Examples: moving a mouse over an element
selecting a radio button clicking on an element
37
jQuery Mouse Events Method Example Description click() Click Event
Attaches/Triggers the click event dblclick() Double Click Event Attaches/Triggers the double click event mousedown() Mouse Down Event Attaches/Triggers the mousedown event mouseenter() Mouse Enter Event Attaches/Triggers the mouseenter event mouseleave() Mouse Leave Event Attaches/Triggers the mouseleave event mousemove() Attaches/Triggers the mousemove event mouseout() Attaches/Triggers the mouseout event mouseover() Hover Event Attaches/Triggers the mouseover event
38
jQuery Mouse Events Method Example Description Mouse Up Event
Attaches/Triggers the mouseup event On Multiple Event
39
jQuery Window Events Method Description resize()
Attaches/Triggers the resize event scroll() Attaches/Triggers the scroll event
40
jQuery Form Events Method Example Description blur()
Attaches/Triggers the blur event change() Attaches/Triggers the change event focus() Focus Blur Attaches/Triggers the focus event focusin() Attaches an event handler to the focusin event focusout() Attaches an event handler to the focusout event submit() Attaches/Triggers the submit event
41
jQuery Keyboard Events
Method Description keypress() Attaches/Triggers the keypress event keyup() Attaches/Triggers the keyup event keydown() Attaches/Triggers the keydown event
42
Other jQuery Events Method Description die()
Removed in version 1.9. Removes all event handlers added with the live() method error() Removed in version 3.0. Attaches/Triggers the error event event.currentTarget The current DOM element within the event bubbling phase event.data Contains the optional data passed to an event method when the current executing handler is bound event.delegateTarget Returns the element where the currently-called jQuery event handler was attached event.isDefaultPrevented() Returns whether event.preventDefault() was called for the event object
43
Other jQuery Events Method Description
event.isImmediatePropagationStopped() Returns whether event.stopImmediatePropagation() was called for the event object event.delegateTarget Returns the element where the currently-called jQuery event handler was attached event.isDefaultPrevented() Returns whether event.preventDefault() was called for the event object event.isPropagationStopped() Returns whether event.stopPropagation() was called for the event object event.namespace Returns the namespace specified when the event was triggered
44
Other jQuery Events Method Description event.pageX
Returns the mouse position relative to the left edge of the document event.pageY Returns the mouse position relative to the top edge of the document event.preventDefault() Prevents the default action of the event event.relatedTarget Returns which element being entered or exited on mouse movement. event.result Contains the last/previous value returned by an event handler triggered by the specified event event.stopImmediatePropagation() Prevents other event handlers from being called event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event
45
Other jQuery Events Method Description event.target
Returns which DOM element triggered the event event.timeStamp Returns the number of milliseconds since January 1, 1970, when the event is triggered event.type Returns which event type was triggered event.which Returns which keyboard key or mouse button was pressed for the event hover() Attaches two event handlers to the hover event off() Removes event handlers attached with the on() method on() Attaches event handlers to elements one() Adds one or more event handlers to selected elements. This handler can only be triggered once per element
46
Other jQuery Events Method Description $.proxy()
Takes an existing function and returns a new one with a particular context ready() Specifies a function to execute when the DOM is fully loaded select() Attaches/Triggers the select event trigger() Triggers all events bound to the selected elements triggerHandler() Triggers all functions bound to a specified event for the selected elements
47
jQuery Syntax For Event Methods
$("p").click(); $("p").click(function(){ // action goes here!! });
48
Anatomy of a jQuery Event Function
Selection Event Anonymous function Beginning of anonymous function $(“a").mouseover(function(){ // your action code goes here }); End of statement End of anonymous function End of mouseover function
49
More jQuery Event Concepts
Waiting for the HTML to Load An Alternative to $(DOCUMENT).READY() Mousing Over and Off an Element Stopping an Event’s Normal Behavior Removing Events
50
Shorthand Ready Function
$(document).ready(function() { // all of your JavaScript goes in here. }); // end of ready() function $(function() { // do something on document ready });
51
Mousing Over and Off an Element
52
Event Properties Property Description pageX
The distance (in pixels) of the mouse pointer from the left edge of the browser window. pageY The distance (in pixels) of the mouse pointer from the top edge of the browser window. screenX The distance (in pixels) of the mouse pointer from the left edge of the monitor. screenY The distance (in pixels) of the mouse pointer from the top edge of the monitor. shiftKey Is true if the shift key is down when the event occurs. which Use with the keypress event to determine the numeric code for the key that was pressed (see tip, next). target The object that was the “target” of the event—for example, for a click event, the element that was clicked. data A jQuery object used with the on() function to pass data to an event handling function (page 167).
53
Stopping an Event’s Normal Behavior
$('#menu').click(function(evt){ // clever javascript goes here evt.preventDefault(); // don't follow the link }); $('#menu').click(function(evt){ // clever javascript goes here return false; // don't follow the link });
54
Stopping an Event in Its Tracks
$('#theLink').click(function(evt) { // do something evt.stopPropagation(); // stop event from continuing });
55
Removing Events $('a').mouseover(function() {
alert('You moved the mouse over me!’); }); $('#disable').click(function() { $('a').off('mouseover'); 6
56
Advanced Event Management
Other Ways to Use the on() Function Delegating Events with on() How Event Delegation Affects the $(THIS) Object
57
The on() Function $('#selector').on('click', selector, myData, functionName); var linkVar = { message:'Hello from a link’}; var pVar = { message:'Hello from a paragraph'}; function showMessage(evt) { alert(evt.data.message); } $('a').on('mouseover',linkVar,showMessage); $('p').on('click',pVar,showMessage);
58
Other Ways to Use the on() Function
$(document).on('click keypress', function() { $('#lightbox').hide(); }); // end on
59
Delegating Events with on()
$('#selector').on('click', selector, myData, functionName); Element in HTML $('li').on('click', function() { $(this).css('text-decoration': 'line-through'); }); // end on Element in Dynamically Included in HTML $(‘ul').on('click’, ‘li’,function() { $(this).css('text-decoration': 'line-through'); }); // end on
60
W3CSchool Exercises Selectors Events Effects HTML Methods Traversing
61
W3CSchool – Selector Exercises
62
W3CSchool – Event Exercises
63
W3CSchool – Effects Exercises
Hide and Show Exercises 1, 2, 3, 4 Fade Exercises 1, 2, 3, 4 Slide Exercises 1, 2, 3, 4 Animate Exercises 1, 2, 3, 4
64
W3CSchool - HTML Methods Exercises
Get Exercises 1, 2, 3, 4 Set Exercise 1, 2, 3, 4, 5 Add Exercises 1, 2, 3, 4 Remove Exercises 1, 2, 3, 4 CSS Classes Exercises 1, 2, 3, 4 CSS Methods Exercises 1, 2, 3, 4 Dimensions Exercises 1, 2, 3, 4, 5
65
W3School – Traversing Exercises
W3School jQuery Selector Tester Ancestors Exercises 1, 2, 3, 4 Descendants Exercises 1, 2, 3, 4 Siblings Exercises 1, 2, 3, 4, 5, 6 Filtering Exercises 1, 2, 3, 4, 5, 6
66
jQuery Examples Email List Application FAQ Application
Image Swap Application Image Rollover Application
67
Student Exercises 8-1 - Email List Application Button on page 259
8-2 - Image Rollovers on page 259 8-3 - Book List Application on page 260 Create links to your Web4Students Webpage. Preview updated Web4Students Webpage. Post Chapter 8 Exercises and update Web4Students Webpage to Live site. 12/29/2018 Copyright © Carl M. Burnett
68
Class Review Introduction to jQuery jQuery Frameworks
Document Object Model (DOM) jQuery Basic Selectors jQuery Calling Methods jQuery Advanced Selectors Traversing Looping & Chaining jQuery Methods Filtering HTML CSS Miscellaneous jQuery Anonymous Functions Events Using Events the jQuery Way More jQuery Event Concepts Advance Event Management W3CSchool Exercises Examples List Application FAQ Application Image Swap Application Image Rollover Application Student Exercises List Application Button 8-2 - Image Rollovers 8-3 - Book List Application 12/29/2018 Copyright © Carl M. Burnett
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.