Presentation is loading. Please wait.

Presentation is loading. Please wait.

CGS 3066: Web Programming and Design Fall 2019

Similar presentations


Presentation on theme: "CGS 3066: Web Programming and Design Fall 2019"— Presentation transcript:

1 CGS 3066: Web Programming and Design Fall 2019
jQuery

2 JavaScript libraries and Frameworks
JavaScript libraries are collections of prewritten code snippets that can be used (and reused) to perform common JavaScript functions. JavaScript frameworks are a full toolset that help shape and organize your website or web application compared to JavaScript libraries are a specialized tool for on-demand use Mostly used JavaScript Libraries: jQuery React JS D3 JS Mostly used JavaScript Frameworks: Angular Ember JS Vue

3 jQuery jQuery is an open source JavaScript library that provides a simple and easy to DOM traversal and manipulation, event handling, animations and AJAX interactions. Lightweight, “write less, do more” Features: HTML/DOM manipulation CSS manipulation HTML event methods Effects and animations AJAX Utilities

4 Why use jQuery Same as pure JavaScript but much simple to code.
Problem with JavaScript Older browsers do not support the latest methods for selecting elements. IE does not treat whitespace between elements as text nodes, while other browsers do. Uses a language familiar to front-end web developers: CSS selectors Much faster at selecting elements Can be much more accurate about which elements to select Lot less code than DOM Widely used

5 Common tasks for jQuery
Methods that allows simple way to do common task Loop through elements Add/remove elements from the DOM tree. Handle events Fade elements into/out of view Handle Ajax requests

6 Start coding with jQuery
Include jQuery library - Download the file and add source <head> <script src="jquery min.js"></script> </head> - Include directly from any CDN (Content Delivery Network) <script src=" Usually start from document ready function $(document).ready(function(){ // Your code here }); Reference:

7 window.onload window.onload = function() { // do stuff with the DOM }
We cannot use the DOM before the page has been rendered by the browser. jQuery gives us a more compatible way to do this. Javascript: window.onload = function() { // do stuff with the DOM } jQuery: $(document).ready(function() { // do stuff with the DOM }); OR $(function() { // do stuff with the DOM });

8 Selecting DOM nodes by JavaScript
Name Description getElementById returns array of descendents with the given tag, such as "div" getElementsByTagName returns array of descendants with the given tag, such as "div" getElementsByName returns array of descendents with the given name attribute (mostly useful for accessing form controls) querySelector * returns the first element that would be matched by the given CSS selector string querySelectorAll * returns an array of all elements that would be matched by the given CSS selector string

9 DOM Selection – JavaScript vs jQuery
JS method jQuery equivalent getElementById("id") $("#id") getElementsByTagName("tag") $("tag") getElementsByName("somename") $("[name='somename']") querySelector("selector") $("selector") querySelectorAll("selector")

10 jQuery Terminology the jQuery function
refers to the global jQuery object or the $ function depending on the context a jQuery object the object returned by the jQuery function that often represents a group of elements selected elements the DOM elements that you have selected for, most likely by some CSS selector passed to the jQuery function and possibly later filtered further

11 The jQuery object The $ function always (even for ID selectors) returns an array-like object called a jQuery object. The jQuery object wraps the originally selected DOM objects. You can access the actual DOM object by accessing the elements of the jQuery object. // false document.getElementById("id") == $("#myid"); document.querySelectorAll("p") == $("p"); // true document.getElementById("id") == $("#myid")[0]; document.getElementById("id") == $("#myid").get(0); document.querySelectorAll("p")[0] == $("p")[0];

12 Using $ as a wrapper $ adds extra functionality to DOM elements
passing an existing DOM object to $ will give it the jQuery upgrade // convert regular DOM objects to a jQuery object var elem = document.getElementById("myelem"); elem = $(elem); var elems = document.querySelectorAll(".special"); elems = $(elems);

13 DOM Tree Traversal <p id="foo">This is a paragraph of text with a <a href="/path/to/another/page.html">link</a>. </p> name(s) description firstChild, lastChild start/end of this node's list of children childNodes array of all this node's children nextSibling, previousSibling neighboring nodes with the same parent parentNode the element that contains this node

14 DOM Manipulation with jQuery
Method Description append(content) Inserts content to the end of element(s) which is specified by a selector. prepend(content) Insert content at the beginning of an element(s) specified by a selector. before(content) Inserts content (new or existing DOM elements) before an element(s) which is specified by a selector. after(content) Inserts content (new or existing DOM elements) after an element(s) which is specified by a selector. insertBefore( selector ) Insert all of the matched elements before another, specified, set of elements. insertAfter( selector ) Insert all of the matched elements after another, specified, set of elements. empty() Remove all child nodes from the set of matched elements. remove() Removes element(s) from DOM which is specified by selector. replaceAll(selector) Replace target element(s) with specified element. replaceWith( content ) Replaces all matched elements with the specified HTML or DOM elements. wrap(html) Wrap an HTML structure around each element which is specified by selector. Examples here:

15 Events handling – jQuery vs DOM
Category jQuery Method DOM Event Form events blur onblur change onchange focus onfocus select onselect submit onsubmit Keyboard events keydown onkeydown keypress onkeypress keyup onkeyup Document loading load onload ready unload onunload Examples here:

16 Events handling – jQuery vs DOM
Category jQuery Method DOM Event Mouse events click onclick mousedown onmousedown mouseenter onmouseenter mouseleave onmouseleave mousemove onmousemove mouseout onmouseout mouseover onmouseover Browser events error onerror() resize onresize scroll onscroll Document loading load onload ready unload onunload Examples here:

17 Finding Elements Elements are selected using CSS-style selectors, also offer extra selectors Basic Selectors * All elements Element All elements with that element name #id elements whose id attribute has the value specified .class elements whose class attribute has the value specified Selector1,selector2 Elements that match more than one selector Hierarchy Ancestor descendant An elements that is a descendant of another element (e.g. li) Parent > child An element that is a direct child of another element Previous+next Adjacent sibling selector only selects elements that are immediately follow by previous element Previous-siblings Sibling selector will select any elements that are a sibling of the previous elements

18 Finding Elements cont….
Basic Filters :not(selector) All elements except the one in the selector (e.g., div:not(‘#summary’)) :first jQ The first element from the selection :last jQ The last element from the selection :even jQ element with an even index number from the selection :odd jQ element with an odd index number from the selection :eq(index) jQ element with index # equal to one in the paramenter :gt(index) jQ element with index # greater to one in the paramenter :header jQ All <h1>--<h6> elements :animated jQ Elements that are currently being animated :focus jQ The elements that currently has focus

19 Cont.. Content filters : contains(‘text’) elements with specified text as a paramenter :empty elements that has no children :parents jQ elements that has children nodes Has(selector) jQ elements that contain at least one element that matches the selector (e.g., div:has(p)) Visibility Filters :hidden jQ all elements that are hidden :visible jQ all elements that consume space in the layout of the page (not selected if displayed:none/width:0) Child filters :nth-child(expr) not a zero based eg. ul li:nth-child(2) :first-child first child Last-child: last child Only-child: only child (eg div p:onlychild)

20 Attributes filters and form
[attribute] Elements that carry the specified attribute [attribute=‘value’] elements that carry the specified attribute with the specified value != (jQ not carry that attribute), ^= (begin with), *= (value apper somewhere), |= (equal to given string or starting with string and followed by a hyphen), ~= (value should be one of the value) Form (jQ) :input, :text, :password, :radio, :checkbox, :submit, :image, :reset, :button, :file, :selected, :enabled (all enabled form elements), :disabled (all disabled form elements), :checked (all checked radio buttons or checkboxes)

21 Examples- basic, get Single selector $(function() { var $listHTML = $('ul').html(); $('ul').append($listHTML);}); Multiple selector $(':header').addClass('headline'); $('li:lt(3)').hide().fadeIn(1500); $('li').on('click', function() { $(this).remove(); }); Get and Set Data Get information $(‘li’) If a jQuery selection holds more than one elements, if the method is used which get information form selected information then it will receive from only one element, .each() method can be used to get all elements var content = $(‘li’).html(); // only from the first element of the list item Set Elements $(‘li’).html(‘Updated’); //updates all elements

22 Looping, Chaining Chaining: $(‘li em’).addClass(‘seasonal’);
$(‘li.hot’).addClass(‘favorite’); Chaining: $('li[id!="one"]') .hide() .delay(500) .fadeIn(1400); // semi-colon indicates end of chaining - can be writen on separate lines


Download ppt "CGS 3066: Web Programming and Design Fall 2019"

Similar presentations


Ads by Google