faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the...

27

Click here to load reader

Transcript of faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the...

Page 1: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

JQueryJQuery Introduction

Like AJAX, JQuery is not a complete programming languageo It’s a JavaScript framework to make web development easier

JQuery was created to make routine JavaScript coding easiero Several tasks that previously required many lines of JavaScript have

been wrapped into single methods in JQueryo E.g. Event handlers; manipulating CSS, HTML, and DOM; AJAX calls;

animations; etc.

Basic Mechanics The JQuery libraries have to be ‘loaded’ before they can be used

o When making your own website, the libraries should be downloaded from JQuery.com

o When using GL (UMBC userpages), the libraries should be included from an external host

Including JQuery in a webpageInstalling yourself (server locally, installed files locally)<head><script src="path_to_downloaded_jquery_file.js"></script></head>Including externally hosted JQuery from Google or Microsoft<!-- Google --><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script></head><!-- Microsoft --><head><script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.0.min.js"></script></head>

1

Page 2: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

JQuery code itself can be included within the .html file or as a separate fileo All JQuery must reside within a <script> tag

JQuery itself can be placed within this tag or External JQuery files can be included using the tag’s ‘src' attribute

o External JQuery files must have the .js extensiono Note that including JQuery is exactly like including regular JavaScript

JQuery code/includes can be placed anywhere within a .html fileo Convention states that it should either be placed entirely before the

HTML part of the document or entirely after the HTML. JQuery revolves around retrieving or more elements of the webpage using

selectors and performing actions with themo A common example is to retrieve a specific button using JQuery then

attach an event to be performed when the button is clicked (See below)

Simple Click Handler using JQueryDON’T WORRY ABOUT THE SPECIFIC ELEMENTS OF THE CODE, WE’LL COVER THAT LATER

HTML Code

<button id="button_1">Click Me</button>

JavaScript/JQuery Code

$("#button_1").click(function(){    alert("Button Clicked”);});

JQuery statements are structured as $(selector).action()o This performs the action on all elements selected by the selector

The $(document).ready(function(){}); command should be the first command used in any JQuery applicationo All JQuery code should then be placed within the curly ‘{}’ braceso The parts of this command will be broken down later

For now, just know that it prevents any JavaScript/JQuery from running before the HTML document is fully loaded

This is the command that lets you place JQuery anywhere in a .html file.

2

Page 3: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

A complete JQuery example<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script><script>$(document).ready(function(){

$("#button_1").click(function(){    alert("Button Clicked"); });

$("#button_not_in_use").hide();});</script></head><body>

<button id="button_1">Click Me</button><button id="button_not_in_use">Will not appear</button>

</body>

Download, install in a JQuery directory and run. (http://faculty.cse.tamu.edu/slupoli/notes/JQuery/code/example.html )

UMBC only If web space not set up (no swe folder):https://wiki.umbc.edu/pages/viewpage.action?pageId=67994741 To view your work:swe.umbc.edu/~<USERNAME>/JQuery/example.html

3

Page 4: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Selectors Selectors are the first part of the JQuery statement format

o In order to change or add to an element in JQuery, it must first be selected

Selectors are denoted by a dollar sign followed by parenthesis containing the element to selecto E.g. $(document)

There are five main types of selectors in JQueryo Reserved Selectors

$(document) – grabs the HTML document itself as an element $(this) – used in event handlers to change the element that invoked

the event Note that these do not have quotation marks within the parentheses

o Universal Selector $(“*”) – grabs all elements

o Element Selector Will grab all elements with the matching HTML tag E.g. $(“button”) will select all <button> elements

o ID Selector Will grab all elements with the matching id value Prefixed with ‘#’ E.g. $(“#theId”) will grab all elements with an attribute id=“theId”

o Class selector Will grab all elements with the matching class Prefixed with ‘.’ E.G. $(“.theClass”) will grab all elements with an attribute

class=‘theClass’o even more detailed!!

https://www.w3schools.com/jquery/jquery_selectors.asp There are many, many other selectors that modify the ones above

for greater control over which elements are selected (first <p> element, every other <tr> element, the first <li> element contained within every <ul> element, etc.).

4

Page 5: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Actions Actions are the second part of the JQuery statement format Actions can either be one-time simple actions or an event to assign a

particular block of code too An example of a simple action is “display an alert when the document

finishes loading”o An example of an event is “every time a button is clicked, increase a

counter” Both are explained in more detail below

Simple Actions The action part of a JQuery statement can be a one-time command

o Examples: Hiding an element Fading an element out of view Retrieving the text in a <p> element Altering an element’s CSS

These actions either don’t require any parameters or require simple parameterso $(“button”).hide();o $(“p”).fadeOut(“slow”);o $(“#theParagraph”).text();o $(“.classOne”).addClass(“classTwo”);o $("td").css("border", "solid black 1px");

Animation actions have an optional callback function parametero Actions like slide, fade, and animate have this optional parametero If defined, this function will execute once the action has completedo The below example is a JQuery snippet that will execute the ‘slideUp’

action on all <p> elements, then hide them when finished.

Callback example$("p").slideUp("slow", function(){    $(this).hide();});

5

Page 6: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Create a simple HTML table as shown below and name it example1.html. Add JQuery to format the able with colors and italics. Hint: how to change colors was covered in the previous page. BTW: “favorite instructors” is a table header.

Answerb:

6

Page 7: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Events Actions The action part of a JQuery statement can also be an event handler

o Event handlers define a function that is executed every time a particular event occurs to an element

o Examples: Increasing a counter every time a button is clicked Changing the size of a <div> element when a spinner value is

updated Adding text typed into an input field to a JavaScript array

Almost every event has a corresponding JQuery methodo ‘onclick’ .click()o ‘onload’ .load()o ‘onchange’ .change()o Etc.

These methods take the function to execute when the event occurs as a parametero This function can include plain JavaScript, simple JQuery actions, or

even other JQuery events The below code gives an example of attaching a function to the $

(document).ready() event. o The function contains another event attached to $("#button_1").click()

which in turn contains a JavaScript alert. The $(document).ready() event also contains the simple action to hide an element with the attribute id=“#button_not_in_use”

Combining simple actions, events, and JavaScript$(document).ready(function(){ //JQuery event

$("#button_1").click(function(){ //JQuery event    alert("Button Clicked"); //Regular JavaScript in JQuery event function });

$("#button_not_in_use").hide(); //simple JQuery action});

7

Page 8: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Using the same table as before, and now the button, have the table format ONLY when the button is pressed. Name it example2.html.

(after click)

8

Page 9: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Working with HTML One of the main uses of JQuery is retrieving, editing, adding, and removing

HTML elements (and data) on a pageo As with other aspects of JQuery, the syntax is much more concise than

regular JavaScripto The power of JQuery is WHEN an action happens!!!o Otherwise the normal CSS formats the page

pic of 3 distinct files (HTML/PHP, CSS, JS Query(with CSS) )

JavaScript WITH the JQuery Code (or vise versa) if the event requires more … intrigue, adding JavaScript is no issue!! still within the <script> tags inside the ready function

JavaScript within JQuery<script>$(document).ready(function(){

var a = true;

Add the JavaScript and JQuery code to have the page revert to an “unformatted” table if the user were to click again. Name it example3.html

click click

Answerb:

9

Page 10: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Retrieving and Editing There are three main methods used to retrieve and change existing HTML

elements (Other methods do exist but are less common)o text() – Gets or sets strictly the text of the element

Does not pay attention to HTML formatting (<b>, <i>, <center>, etc).

Useful for <p>, <div>, and <span> elementso html() – Gets or sets the HTML of the element

Does pay attention to HTML formatting Useful for adding formatting to elements

o val() – Gets or sets the value of form field elements Very useful to get current values of text/number/dropdown input

fieldso Calling any of these methods without a parameter returns the requested

aspect of the elemento Supplying a string parameter to while calling these methods replaces the

requested aspect of the elements with the parameter

10

Page 11: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Retrieving and Editing HTML exampleHTML

<div id="div_1">This word is <b>bold</b></div><select id="sel_1">  <option value="one">One</option>  <option value="two" selected>Two</option></select>

JQuery$(document).ready(function(){

alert($("#div_1").text()); //Displays “This word is bold” alert($("#div_1").html()); //Displays “This word is <b>bold</b>”

//Changes HTML of the div to be “This word is <i>italic</i>” $("#div_1").html("This word is <i>italic</i>");

alert($("#sel_1").val()); //Displays “two”});

Using the JQuery “gathering” functions, create the HTML file example4.html that uses a textArea. Limit the character input in the textarea including an updated count as the user types.

Answerb:

11

Page 12: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Adding There are four main methods used to add HTML to a document

o append() – Adds content to the end of an element The content is still placed within the element

o prepend() – Adds content to the beginning of an element The content is still placed within the element

o after() – Adds content after the element The content is not placed within the element

o before() – Adds content before the element The content is not placed within the element

Adding HTML<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script><script>$(document).ready(function(){

$("#button_1").click(function(){    $("#div_1").append(" <b>some text</b>"); });

$("#button_2").click(function(){    $("#div_1").after("<br>some text"); });});</script></head><body>

<button id="button_1">Append</button><button id="button_2">Add After</button>

<div id="div_1">Text appended:</button>

</body>Initial After clicking “Append” After clicking “Add After”

(remember, not placed within the element)

12

Page 13: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Removing There are two main methods used to remove HTML from a document

o remove() – Removes the HTML element itself, including all child elements

The element ceases to exist on the page after this callo empty() – Only clears the innerHTML of the element

The element still exists but is entirely empty after this call Filters can be applied when removing for greater control over what is removed

o The filter is added as a parameter to the method callo The filter can be any JQuery selector

The filter can be made even more specific by adding more than one selectors in the string separated by a comma

o For example: $(“p”).remove(“.test”); removes all <p> elements with class ‘test’ $(“button”).remove(“#input”); removes all <button> elements with

the id ‘input’ $(“div”).remove(“.class1, #id2”); removes all <div> elements with

class ‘class1’ and id ‘id2’

13

Page 14: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Working with CSS CSS can be manipulated using JQuery just like HTML Classes can be added, removed, and toggled

o The style attribute can also be modified directly There are three methods for modifying CSS classes using JQuery

o addClass() – Adds one or more classes to the element Classes are separated by a space E.g. $(“div”).addClass(“test class2”) adds the classes ‘test’ and

‘class2’ to all <div> elementso removeClass() – Removes one or more classes from the element

Same syntax as addClass()o toggleClass() – For each class supplied, the class is added if the element

does not have it and removed if the element does have it Same syntax as addClass() and removeClass()

The css() method directly accesses or modifies the style attribute of an elemento If given only a CSS attribute as a parameter, it will return the value of

that attribute for the first matched element E.g. $(“div”).css(“color”); returns the color value for the first

<div> element foundo If given two parameters in the form “css(“[attr]”, “[val]”), it will set the

CSS attribute [attr] to the value [val] E.g. $(“div”).css(“height”, “200px”); will set the height of the

first <div> element found to be 200 pixelso If given a list of parameters in the form “css({“[attr]”: “[val]”, “[attr]”:

“[val]”, …}), it will set each CSS attribute [attr] to the corresponding value [val]

E.g. $(“div”).css({“height”: “200px”, “color”: “blue”}); will set the color of the first <div> element found to blue and the height of the same <div> to be 200 pixels

See https://www.w3schools.com/jquery/jquery_css_classes.asp for complete examples

14

Page 15: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Dimensions The dimensions of elements can be modified directly using JQuery These methods follow the same syntax as text() in HTML manipulation

o Supplying no parameters fetches the current valueo Supplying a parameter sets the valueso These values can be entered as integers and do not have to be converted

to string form The methods for altering dimensions in JQuery are:

o width()o height()o innerWidth()o innerHeight()o outerWidth()o outerHeight()

These methods modify the dimensions given by the below image

Image from w3school.com

15

Page 16: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Where to get help with JQuery jQuery.com

o use as an APIo but not as friendly to use

w3schoolso great learning toolo but not as much detail

16

Page 17: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Resources https://www.w3schools.com/jquery/default.asp (Tutorial with worked examples)

SolutionsSimple JQuery Table formatting

http://faculty.cse.tamu.edu/slupoli/notes/JQuery/code/favorites.html

http://userpages.umbc.edu/~slupoli/notes/JQuery/code/favorites.html

Click on, Click offhttp://faculty.cse.tamu.edu/slupoli/notes/JQuery/code/example3.html

http://userpages.umbc.edu/~slupoli/notes/JQuery/code/example3.html

17

Page 18: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/JQuery/JQuery Intro... · Web viewAdd the JavaScript and JQuery code to have the page revert to an “unformatted” table if

Limiting letters within a TextAreaHTML

1. <!DOCTYPE html>2. <html>3. <head>4. <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>5.   <meta charset="utf-8">6.   <title>JS Bin</title>7. <style type="text/css">8. textarea {9.   display:block;10.   margin:1em 0;11. }12. </style>13. </head>14. <body>15. <form>16. <label>Maximum 15 characters</label>17. <textarea id="textarea" maxlength="15"></textarea>18.   <span id="rchars">15</span> Character(s) Remaining19. </form>20. </body>21. </html>

JQuery/JavaScript1. var maxLength = 15;2. $('textarea').keyup(function() {3.   var textlen = maxLength - $(this).val().length;4.   $('#rchars').text(textlen);5. });

18