Uploaded by riekocraft

e4 jQuery

advertisement
IFT 458/598
JQUERY
Objects
JQuery is a fast and concised Javascript
library
created by John Resig in 2006
Moto: write less, do more
Objects
Built on top of Javascript, extending the
features without replacing them:
You can use a mixture of standard Javascript
and jQuery on the same page seamlessly
It provides features for manipulating the web
page with very good performance
It emphasizes interaction between Javascript
and HTML
JQuery has cross-browser support
Getting Started
Two ways to access it:
Download the latest version available from
www.jquery.com and reference it in your html file: <script
src="jquery.js"></script>
Access it directly from a content delivery network (CDN):
<script src=“http://code.jquery.com/jquery-3.5.1.min.js"></script>.
Getting Started
jquerydemo.html
<html><head><script src="jquery.js"></script>
<script>
$(document).ready(function()
{
alert("Hello!! Welcome to JQuery Session");
});
</script>
</head></html>
Waiting for the doc to be ready
Due to the code being placed within the element, the browser
would try to run it before the document has finished loading
all of the necessary elements.
To avoid this problem, jQuery provides a method named
ready that can be applied to the document.
Waiting for the doc to be ready
The outer lines of code below ensure that any code within
them runs only after the document is ready for changes to
be made to its elements:
$(document).ready(function() {
// code
});
The ready method allows you to define a function that will
be run once the elements of the document have been loaded.
Using the ready method
When using the ready method, you can provide what is called an
anonymous function or a previously defined function name.
The code below uses an anonymous function.
$(document).ready(function() {
$(".about-me").addClass("special");
});
Using the ready method
To perform the same task by providing a defined function, you could
instead use the following code:
function makeSpecial() {
$(".about-me").addClass("special");
}
$(document).ready(makeSpecial);
 Here, a typical JavaScript function is defined, which uses the
jQuery code to perform the same task. The function is then called
by using the function name in the ready method.
The main difference between the two approaches is that an anonymous
function is most often used when the function code is not reusable, while
a defined function is used when the function will be reused at a later time.
Selecting element in the doc
The $() function (called jQuery wrapper) is used to select one
or more HTML elements in the document using jQuery.
It returns a collection of elements that match the specified
selection.
It is the $ symbol that signifies to the browser that we’re
working with the jQuery library
$() is actually an alias for the full function name, jQuery().
$(“li a”); OR jQuery(“li a”);
Selecting element in the doc
The $ symbol simply invokes the jQuery library selector
functionality
A jQuery Selector is a function which makes use of
expressions to find out matching elements from a DOM
based on the given criteria.
Once an element is selected then we can perform various
operations on that selected element.
jQuery Selectors
Query selectors start with the $() factory function.
jQuery uses CSS selector syntax and also has a
number of extended selectors that can be passed to the
$() function.
jQuery Selectors
The $() makes use of the below 3 building blocks:
Element Selector:
Elements selection takes the form of $(‘T’) where
‘T’ stands for the element tag name
ID Selector
This takes the form $(‘#id’) where ID equal to id
Class Selector
This takes the form $(‘.myclass’) where class
equal to myclass
jQuery Selector: Element
Consider the code below
<html>
<head><script src="jquery.js"></script>
<script>
$(document).ready(function()
{
$("button").click(function()
{
$("p").hide();
});
//alert("Hello!! Welcome to JQuery Session");
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph</p>
<p id="test">This is another paragraph</p>
<button>Hide Paragraph</button>
</body>
</html>
jQuery Selector: ID
<html>
<head><script src="jquery.js"></script>
<script>
$(document).ready(function()
{
$("#button1").click(function()
{
$("#first").hide();
});
$("#button2").click(function()
{
$("#second").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph</p>
<p id="test">This is another paragraph</p>
<button id="button1">Hide First Paragraph</button>
<button id="button2">Hide Second Paragraph</button>
</body>
</html>
jQuery Selector: class
<html>
<head><script src="jquery.js"></script>
<script type=“text/javascript”>
function highlight() {
$(‘p.mark’).toggleClass(“highlight”);
}
</script>
<style type=“text/css”>
p.mark { font-weight: normal;}
p.highlight { background-color: lightgray;}
</style>
</head>
<body>
<div>
<p class=“mark”>This is paragraph 1</p>
<p>This is paragraph 2</p>
<p class=“mark”>This is paragraph 3</p>
<p>This is paragraph 4</p>
</div>
<input type=“button” value=“Highlight” onclick=“highlight()“ />
</body>
</html>
jQuery Selectors
Syntax
$("*")
$(this)
$("p.intro")
$("p:first")
$("ul li:first")
$(“p:not(.cool)")
$(“p[class]”)
Description
jQuery Selectors
Syntax
Description
$("*")
Selects all elements
$(this)
Selects the current HTML element
$("p.intro")
Selects all <p> elements with class="intro"
$("p:first")
Selects the first <p> element
$("ul li:first")
Selects the first <li> element of the first <ul>
$(“p:not(.cool)") select all <p> elements that do not have a
class of cool.
$(“p[class]”)
select all <p> elements that have a class
attribute.
Putting all together
<html>
<head><link href=“styles.css” rel=“stylesheet”>
<script src="jquery.js” type="text/javascript"></script>
<script src=“myScript.js” type="text/javascript"></script>
</head>
<body>
<h1>My Site</h1>
<div class=“main”>
Welcome to my site! Obviously, this site is all about me! I probably should think
about others, but right now I am simply talking about me. </div>
<div class=“about-me”>
<h2>About Me</h2>
I enjoy writing HTML, CSS, and jQuery. I also picked up a love of flying kites when
a friend of my told me to &quote;Go fly a kite! &quote; I did, and it has been a
hobby ever since. </div>
</body>
</html>
Putting all together
myScript.js
$(document).ready(function() {
$(".about-me").addClass("special");
});
styles.css
.special { font-style:italic; }
Event Handling
Events are a fundamental aspect of creating
dynamic and responsive scripts.
Typically, an event occurs when a user performs
some type of action such as a mouse click, key
press, or form submission.
For the most common events, jQuery has shorthand
functions to make it easy to react to a user event
Event Handling
Some events can also be triggered by calling them
programmatically, which can be helpful when you
need to perform a task automatically.
The jQuery library offers a number of features that
make handling events an easier task than when
using JavaScript
Waiting for the doc to be ready
jQuery offers you the ready() function so that you can be sure that all the
elements in the document are loaded before running jQuery code on them.
ready() vs. load()
The ready() method allows you to begin running your script as soon as
all of the elements have been loaded, but it does not wait for images or
other media to finish loading:
$(document).ready(function() {
// Code to execute when elements have loaded
});
Javascript uses the load event on the window object to determine
when all the elements have been completely loaded.
window.onload = function() {
// Code to execute when elements have loaded
}
When you need to wait for the load event, jQuery provides you its own
load method, which does the cross-browser work for you.
$(window).load(function () {
// Code to execute when elements and media have loaded
});
Basic Event Handling
Suppose you need to perform an action when the user
clicks an element.
jQuery provides the click() method to handle this event.
For example, if you had an element with an id of
change-size, you could use the following code:
$("#change-size").click(function() {
// Code to execute when element is clicked
});
Basic Event Handling
The click() method calls a function that will be run
when the event occurs. The code within the function
will then execute and react to the click event.
$(document).ready(function() {
$("#change-size").click(function() {
// Code to execute when element is clicked
});
});
The click() Example
<html>
<head>
<link href=“styles.css” rel=“stylesheet”>
<script src="jquery.js”
type="text/javascript"></script>
<script src=“myScript.js”
type="text/javascript"></script>
</head>
<body>
<div id=“change-size”>
This text is important! Click this text to
enlarge it if needed! </div>
<div>
<form action=“size-larger.html”>
<button id=“enlarge”>Enlarge
Text</button>
</form></div>
</body>
</html>
myScript.js
$(document).ready(function() {
$("#enlarge").click(function(event) {
event.preventDefault(); //this
prevent the default action
$("#changesize").addClass("large-font"); });
});
styles.css
.large-font {font-size:1.5em; }
Check & Change Check Box State
Check box input elements have a boolean value based on whether the
element is checked.
You access the value by getting the value of the checked attribute. If the
element is checked, then checked has a value such as true or "checked".
Otherwise, the value will be undefined or false.
you may be dealing with multiple check boxes at once, so the safest way
to see if the jQuery object represents an object that is checked is the .is()
method: $("#myCheckbox").is(":checked");
Check & Change Check Box State
To set the state of a jQuery object representing check boxes to checked,
you would simply set the checked attribute as follows:
$("#myCheckbox").attr("checked", true);
To set the state of check boxes to unchecked, You need to remove the
checked attribute using removeAttr():
$("#myCheckbox").removeAttr("checked");
if ($("#myCheckbox").is(":checked)) {
$("#myCheckbox").removeAttr("checked");
else { $("#myCheckbox").attr("checked"); }
Radio Buttons
Radio inputs are almost always used in groups. The value of
a radio input that a group represents is not boolean. Instead,
it is the value attribute of the currently selected element.
For example, the value of the following radio button group
is either "male" or "female":
<input id=“maleRB” type=“radio” name=“gender” value=“male”>
<label for=“maleRB” >Male</label>
<input id=“femaleRB” type=“radio” name=“gender” value=“female”>
<label for=“femaleRB” >Female</label>
Radio Buttons
To get the value of a radio input group in code, you first need
to access all the elements in the group, find out which one is
selected, and then get the value attribute from that object.
The following code gets the value of a radio input group that
is grouped by name="gender" in jQuery:
var genderGroup = $("input[name=gender]");
var checkedGender = genderGroup.filter(":checked");
var selectedGender = checkedGender.val();
Radio Buttons
Setting the checked value of individual radio inputs works the
same way as check boxes. To see if the jQuery object
represents a radio button that is checked, use the .is()
method. For example:
$("#maleRB").is(":checked");
To set the state of a jQuery object representing a radio button
to checked, you simply set the checked attribute as follows:
$("#maleRB").attr("checked", true);
Radio Buttons
To set the state of a jQuery object representing a radio button
to unchecked, you need to remove the checked attribute
using removeAttr(). For example:
$("#maleRB").removeAttr("checked");
if ($("#maleRB").is(":checked)){
$("#maleRB").removeAttr("checked");
else{ $("#maleRB").attr("checked"); }
var genderGroup = $("input[name=gender]");
var checkedGender = genderGroup.filter(":checked");
var selectedGender = checkedGender.val();
Download