SlideShare a Scribd company logo
1 of 26
JavaScript Libraries
Web Application Development
BIT-UCSC-Semester 3 (New Syllabus)
Daminda Herath
B.Sc(Col), MBCS, M.Sc(Col), MCSSL, MIEEE
Introduction to JavaScript libraries
•A JavaScript library is a collection of code that you use when you
want to get access to additional functionality or make life easier.
•JQuery is a JavaScript library.
•jQuery also makes cross-browser development easier.
jQuery fundamentals
• jQuery is simply JavaScript that you add to your web page to make writing JavaScript easier.
• jQuery is a lightweight, "write less, do more", JavaScript library.
• jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish,
and wraps them into methods that you can call with a single line of code.
•jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.
•The jQuery library contains the following features:
HTML/DOM manipulation, CSS manipulation, HTML event methods, Effects and animations,
AJAX, Utilities
jQuery fundamentals
• Installing jQuery
•There are two ways to use jQuery, either downloaded locally or on a Content Delivery
Network (CDN). The local copy is just that, a file that sits within your document root on
your server’s hard drive. A CDN-hosted version means that the jQuery file sits on
someone else’s server and you just reference it in your code.
•Adding local jQuery to a page
<script type=”text/javascript” src=”jquery-1.8.1-min.js”></script>
•Adding CDN jQuery to a page
<script type=“text/javascript” src=” http://ajax.aspnetcdn.com/ajax/jQuery/jquery-
1.8.1.min.js”></script>
jQuery fundamentals
• jQuery ready() Function
jQuery has a function called ready() that waits for the page to be,
well, ready. Not quite everything is available (for example, some
images still may be loading), but the HTML elements are ready to be
worked with when the ready() function is called.
<!doctype html>
<html>
<head>
<title>jQuery</title>
<script type=“text/javascript” src=“jquery-1.8.1.min.js”>
</script>
</head>
<body>
<h1>Adding jQuery</h1>
<script type=”text/javascript”>
$(document).ready(function() {
alert(“hi”);
});
</script>
</body>
</html>
jQuery fundamentals
•Selecting Elements with jQuery
The preceding section explains how to select the document object. It also provides a great
deal of how jQuery works. When you use the code $(document), you use something called
a selector. Most of what you’ll do in jQuery happens through selectors.
For instance, you’ll frequently select a piece of a web page and then have jQuery perform
an action on that piece of the page. That action could be anything from adding text,
changing HTML, changing CSS or, well
The basic flow for JavaScript programming with jQuery is this:
1. Select an element on the web page (or the entire page itself).
2. Do something interesting with that element.
jQuery fundamentals
•jQuery selectors up close
There are three primary or basic selectors in jQuery.
Three selectors:
✦ By class
✦ By ID
✦ By element
jQuery fundamentals
<p id=”bookTitle”>My Book</p>
You could access that with jQuery like this:
$(“#bookTitle”)
<p class=”titleClass”>This is some text</p>
The jQuery selector looks like this:
$(“.titleClass”)
The following selector selects all <div> elements on the entire page:
$(“div”)
Working with HTML Using jQuery
jQuery append() Method
The append() method inserts specified content at the end of the
selected elements.
$("#lis").append("<li>Angulas</li>");
Working with HTML Using jQuery
Reading attributes
Reading an attribute with jQuery means using the attr() function.
alert($(“#exLink”).attr(“href”));
Changing attributes
You can also set the value of an attribute using the attr() function
$(“#exLink”).attr(“href”, “http://www.w3c.org”);
$(“#theImage”).attr(“src”,”Desert.jpg”);
Working with HTML Using jQuery
Changing CSS
You can also change the styling information on a page, either by
setting the styles directly or by changing the CSS class applied to an
element. Class is just another attribute on an element, so changing
CSS means using the attr() function again.
$(“#theImage”).attr(“class”,”borderClass”);
Working with HTML Using jQuery
Adding a Class
You could use the jQuery function for adding a class, called addClass(). The
addClass() function doesn’t interfere with any other classes that are already applied to
an element; it just adds another class to it.
$(“#theImage”).addClass(“borderClass”);
Removing a class
A companion to the addClass() function, called removeClass, takes theclass away
from an element. Like addClass(), removeClass() doesn’t affect other classes that are
on the element; it removes only the specified class.
$(“#theImage”).removeClass(“borderClass”);
<!doctype html>
<html><head>
<title>jQuery</title>
<script type=”text/javascript”src=”1.8.1.min.js”>
</script>
</head>
<body>
<h1>Adding HTML</h1>
<ul id=”theList”>
<li>Here’s 1</li>
<li>Here’s 2</li>
</ul>
<script type=”text/javascript”>
$(document).ready(function() {
$(“#theList”).append(“<li>Here’s 3</li>”);
});</script></body>
</html>
<!doctype html>
<html>
<head>
<title>jQuery</title>
<script type=”text/javascript” src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.1.min.js”>
</script>
</head>
<body>
<h1>Attributes</h1>
<a id=”exLink” class=”link” href=”http://www.example.com”>Web site</a>
<script type=”text/javascript”>
$(document).ready(function() {
alert($(“#exLink”).attr(“href”));
});
</script>
</body>
</html>
<!doctype html><html>
<head><title>jQuery</title>
<script type="text/javascript" src="jquery-1.8.1.min.js">
</script></head>
<body>
<h1>Changing CSS</h1>
<img id="exImage" src="document.png" alt="Document" />
<style type="text/css">
.borderClass{ border:1px solid green;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#exImage").attr("class","borderClass");
});
</script>
</body>
</html>
<!doctype html>
<html><head><title>jQuery</title>
<script type="text/javascript" src="jquery-1.8.1.min.js">
</script></head><body>
<h1>Adding CSS</h1>
<img id="exImage" src="document.png" alt="Document" class="borderClass" />
<style type="text/css">
.borderClass{ border:1px solid green; }
.bo{ border:1px dashed red; }
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#exImage").addClass("bo");
});
</script>
</body></html>
</html>
<!doctype html>
<html><head><title>jQuery</title>
<script type="text/javascript" src="jquery-1.8.1.min.js">
</script></head><body>
<h1>Removing CSS</h1>
<img id="exImage" src="document.png" alt="Document" class="borderClass" />
<style type="text/css">
.borderClass{ border:1px solid green; }
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#exImage").removeClass("borderClass");
});
</script>
</body>
</html>
Working with Events and Event Listeners
When it comes to web programming, events are the things that happen in a web page. For
example, a user might move the mouse over a button, click a button, or submit a form.
Understanding Events
In general, there are four types of events that you’ll be concerned about:
✦ Form events: Includes things like selecting a check box or submitting the form itself. Reacting
to form events is one of the most common things that JavaScript programmers do.
✦ Mouse events: This can be anything from a mouse click to mouse movements on the page.
That’s right; you can actually track where the mouse is on a page and react to it.
✦ Keyboard events: Things that happen through the keyboard, like a
key press, are considered keyboard events.
✦ Page events: Things like the page loading or unloading are
considered page events. You’ll be happy to know that you’ve already
been reacting to the page load event through the jQuery ready()
function.
Working with Forms
Adding a Submit Handler
jQuery includes a function that automatically watches for a form to be submitted.
$(document).ready(function() {
$("form").submit(function() {
alert("You submitted the form");
return false;
});
});
Working with Forms
The code begins with the ready() function, which you’ve seen before.
Next up, you select the form by selecting all <form> elements on the
page.
Next up, the submit() function is called and another function is created
within it. The function’s main task is to display an alert, which you saw.
The second line within the function, return false, is interesting for forms.
When you use return false in a form submit event, you essentially
prevent the form from submitting to the server. Therefore, you’d only
want to do this for specific reasons, like when the form isn’t valid such
as when the user hasn’t filled out all the required fields.
Working with Forms
When you add return false, you’re preventing the default action.Because the default action of the
form is to submit to the server, adding return false prevents that default action from occurring.
Another way to prevent the default action is with the jQuery preventDefault() function.
You use preventDefault in certain circumstances where return false doesn’t do what you want.
Changing the JavaScript from the receding
$(document).ready(function() {
$(“form”).submit(function(event) {
alert(“You submitted the form”);
event.preventDefault();
return false;
});});
Working with Forms
Checking for blank fields
You can change the JavaScript to make sure that the field has been filled in. Recall that the ID of the Name field
is “username”. jQuery can select that pretty easily, and then it’s a matter of getting the value for the field. For
that, you can use jQuery’s val() function. Finally, all you need to do is put the whole thing in an if statement to
make sure the value isn’t empty.
$(document).ready(function() {
$("form").submit(function(event) {
if ($("#username").val() == "") {
alert("Name cant be blank");
event.preventDefault();
return false;
} });
});
Keyboard events
you react to keyboard events. Things like watching when a certain key is pressed, or more
generically, just counting the number of times the keys are pressed, can all be done with
JavaScript.
Counting characters
$(document).ready(function() {
var maxCharacters = 50;
$("#message").on("keyup",function() {
var currentVal = $("#message").val().length;
var totalRemaining = maxCharacters - currentVal;
$("#remaining").text(totalRemaining);
}); });
Keyboard events
This JavaScript first sets a variable with the maximum number of characters allowed, 50.
Then the element with the ID of “message” is selected. A event handler is attached to
the selected element. The event handler is attached with the on() function, which is a
generic event handler. The event handlers you’ve seen so far are all so common that the
folks at jQuery created specific functions to handle them. So things like submit(), click(),
and hover() all have their own events.
However, all other events are attached using the on() function. The first argument to the
on() function is the name of the event to watch for. In this case, you want to watch for
the “keyup” event to know when a key is pressed and then released.

More Related Content

What's hot

GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4Heather Rock
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginnersIsfand yar Khan
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelpauldix
 
Html events with javascript
Html events with javascriptHtml events with javascript
Html events with javascriptYounusS2
 
Mvc & java script
Mvc & java scriptMvc & java script
Mvc & java scriptEyal Vardi
 
Js events
Js eventsJs events
Js eventsgvbmail
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajaxbaygross
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuerySiva Arunachalam
 
MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2Naji El Kotob
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects WebStackAcademy
 

What's hot (19)

GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginners
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
Ajax3
Ajax3Ajax3
Ajax3
 
jQuery Behaviours
jQuery BehavioursjQuery Behaviours
jQuery Behaviours
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Client Web
Client WebClient Web
Client Web
 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
 
Html events with javascript
Html events with javascriptHtml events with javascript
Html events with javascript
 
JavaScript
JavaScriptJavaScript
JavaScript
 
jQuery Introduction
jQuery IntroductionjQuery Introduction
jQuery Introduction
 
Learn css3
Learn css3Learn css3
Learn css3
 
Mvc & java script
Mvc & java scriptMvc & java script
Mvc & java script
 
Js events
Js eventsJs events
Js events
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuery
 
MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
 

Viewers also liked

learning-economy-white-paper.original
learning-economy-white-paper.originallearning-economy-white-paper.original
learning-economy-white-paper.originalHarry Peirce
 
SAGE Streetsigns.pptx (1)
SAGE Streetsigns.pptx (1)SAGE Streetsigns.pptx (1)
SAGE Streetsigns.pptx (1)Damien Herndon
 
UNESCO%20Green%20Academies%20e-book%20compressed%20version
UNESCO%20Green%20Academies%20e-book%20compressed%20versionUNESCO%20Green%20Academies%20e-book%20compressed%20version
UNESCO%20Green%20Academies%20e-book%20compressed%20versionKathleen Kardos
 
Chapter18 International Finance Management
Chapter18 International Finance ManagementChapter18 International Finance Management
Chapter18 International Finance ManagementPiyush Gaur
 
Nicky Hekster (IBM) - Watson for Health
Nicky Hekster (IBM) - Watson for HealthNicky Hekster (IBM) - Watson for Health
Nicky Hekster (IBM) - Watson for HealthAlmereDataCapital
 
Aptitude Finance Architect Brochure
Aptitude Finance Architect BrochureAptitude Finance Architect Brochure
Aptitude Finance Architect BrochureAptitude Software
 
IFRS 9 conference presentation - Philip Lewis
IFRS 9 conference presentation - Philip LewisIFRS 9 conference presentation - Philip Lewis
IFRS 9 conference presentation - Philip LewisAptitude Software
 
Craniopharyngioma - What is the best approach
Craniopharyngioma - What is the best approach Craniopharyngioma - What is the best approach
Craniopharyngioma - What is the best approach Murali Chand Nallamothu
 
Nexx consultants - IFRS 9 offering
Nexx consultants - IFRS 9 offeringNexx consultants - IFRS 9 offering
Nexx consultants - IFRS 9 offeringSohail Farooq
 
Multinational Capital Budgeting
Multinational Capital BudgetingMultinational Capital Budgeting
Multinational Capital BudgetingJunaid Mirza
 

Viewers also liked (16)

learning-economy-white-paper.original
learning-economy-white-paper.originallearning-economy-white-paper.original
learning-economy-white-paper.original
 
SAGE Streetsigns.pptx (1)
SAGE Streetsigns.pptx (1)SAGE Streetsigns.pptx (1)
SAGE Streetsigns.pptx (1)
 
UNESCO%20Green%20Academies%20e-book%20compressed%20version
UNESCO%20Green%20Academies%20e-book%20compressed%20versionUNESCO%20Green%20Academies%20e-book%20compressed%20version
UNESCO%20Green%20Academies%20e-book%20compressed%20version
 
Chapter18 International Finance Management
Chapter18 International Finance ManagementChapter18 International Finance Management
Chapter18 International Finance Management
 
March classes 2016
March  classes 2016  March  classes 2016
March classes 2016
 
Nicky Hekster (IBM) - Watson for Health
Nicky Hekster (IBM) - Watson for HealthNicky Hekster (IBM) - Watson for Health
Nicky Hekster (IBM) - Watson for Health
 
Chapter16
Chapter16Chapter16
Chapter16
 
White paper on BCBS Guidelines for IFRS 9
White paper on BCBS Guidelines for IFRS 9White paper on BCBS Guidelines for IFRS 9
White paper on BCBS Guidelines for IFRS 9
 
Dec. 2016 classes
Dec. 2016 classes   Dec. 2016 classes
Dec. 2016 classes
 
Aptitude Finance Architect Brochure
Aptitude Finance Architect BrochureAptitude Finance Architect Brochure
Aptitude Finance Architect Brochure
 
IFRS 9 conference presentation - Philip Lewis
IFRS 9 conference presentation - Philip LewisIFRS 9 conference presentation - Philip Lewis
IFRS 9 conference presentation - Philip Lewis
 
Craniopharyngioma - What is the best approach
Craniopharyngioma - What is the best approach Craniopharyngioma - What is the best approach
Craniopharyngioma - What is the best approach
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Nexx consultants - IFRS 9 offering
Nexx consultants - IFRS 9 offeringNexx consultants - IFRS 9 offering
Nexx consultants - IFRS 9 offering
 
Multinational Capital Budgeting
Multinational Capital BudgetingMultinational Capital Budgeting
Multinational Capital Budgeting
 
20160619 つくば横の会スライド tks
20160619 つくば横の会スライド tks20160619 つくば横の会スライド tks
20160619 つくば横の会スライド tks
 

Similar to JavaScript Libraries (20)

J query
J queryJ query
J query
 
jQuery for web development
jQuery for web developmentjQuery for web development
jQuery for web development
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
jQuery
jQueryjQuery
jQuery
 
jQuery
jQueryjQuery
jQuery
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
Unit3.pptx
Unit3.pptxUnit3.pptx
Unit3.pptx
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Jquery
JqueryJquery
Jquery
 
Jqueryppt (1)
Jqueryppt (1)Jqueryppt (1)
Jqueryppt (1)
 
jQuery
jQueryjQuery
jQuery
 
J query training
J query trainingJ query training
J query training
 
Lesson 202 02 oct13-1800-ay
Lesson 202 02 oct13-1800-ayLesson 202 02 oct13-1800-ay
Lesson 202 02 oct13-1800-ay
 
JQuery_and_Ajax.pptx
JQuery_and_Ajax.pptxJQuery_and_Ajax.pptx
JQuery_and_Ajax.pptx
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQuery
 
Jquery library
Jquery libraryJquery library
Jquery library
 

More from Daminda Herath

More from Daminda Herath (10)

Data mining
Data miningData mining
Data mining
 
Data mining
Data miningData mining
Data mining
 
Web mining
Web miningWeb mining
Web mining
 
Web content mining
Web content miningWeb content mining
Web content mining
 
Personal Web Usage Mining
Personal Web Usage MiningPersonal Web Usage Mining
Personal Web Usage Mining
 
XML
XMLXML
XML
 
Social Aspect of the Internet
Social Aspect of the InternetSocial Aspect of the Internet
Social Aspect of the Internet
 
Personal web usage mining
Personal web usage miningPersonal web usage mining
Personal web usage mining
 
Web Content Mining
Web Content MiningWeb Content Mining
Web Content Mining
 
1. Overview of Distributed Systems
1. Overview of Distributed Systems1. Overview of Distributed Systems
1. Overview of Distributed Systems
 

JavaScript Libraries

  • 1. JavaScript Libraries Web Application Development BIT-UCSC-Semester 3 (New Syllabus) Daminda Herath B.Sc(Col), MBCS, M.Sc(Col), MCSSL, MIEEE
  • 2. Introduction to JavaScript libraries •A JavaScript library is a collection of code that you use when you want to get access to additional functionality or make life easier. •JQuery is a JavaScript library. •jQuery also makes cross-browser development easier.
  • 3. jQuery fundamentals • jQuery is simply JavaScript that you add to your web page to make writing JavaScript easier. • jQuery is a lightweight, "write less, do more", JavaScript library. • jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code. •jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation. •The jQuery library contains the following features: HTML/DOM manipulation, CSS manipulation, HTML event methods, Effects and animations, AJAX, Utilities
  • 4. jQuery fundamentals • Installing jQuery •There are two ways to use jQuery, either downloaded locally or on a Content Delivery Network (CDN). The local copy is just that, a file that sits within your document root on your server’s hard drive. A CDN-hosted version means that the jQuery file sits on someone else’s server and you just reference it in your code. •Adding local jQuery to a page <script type=”text/javascript” src=”jquery-1.8.1-min.js”></script> •Adding CDN jQuery to a page <script type=“text/javascript” src=” http://ajax.aspnetcdn.com/ajax/jQuery/jquery- 1.8.1.min.js”></script>
  • 5. jQuery fundamentals • jQuery ready() Function jQuery has a function called ready() that waits for the page to be, well, ready. Not quite everything is available (for example, some images still may be loading), but the HTML elements are ready to be worked with when the ready() function is called.
  • 6. <!doctype html> <html> <head> <title>jQuery</title> <script type=“text/javascript” src=“jquery-1.8.1.min.js”> </script> </head> <body> <h1>Adding jQuery</h1> <script type=”text/javascript”> $(document).ready(function() { alert(“hi”); }); </script> </body> </html>
  • 7. jQuery fundamentals •Selecting Elements with jQuery The preceding section explains how to select the document object. It also provides a great deal of how jQuery works. When you use the code $(document), you use something called a selector. Most of what you’ll do in jQuery happens through selectors. For instance, you’ll frequently select a piece of a web page and then have jQuery perform an action on that piece of the page. That action could be anything from adding text, changing HTML, changing CSS or, well The basic flow for JavaScript programming with jQuery is this: 1. Select an element on the web page (or the entire page itself). 2. Do something interesting with that element.
  • 8. jQuery fundamentals •jQuery selectors up close There are three primary or basic selectors in jQuery. Three selectors: ✦ By class ✦ By ID ✦ By element
  • 9. jQuery fundamentals <p id=”bookTitle”>My Book</p> You could access that with jQuery like this: $(“#bookTitle”) <p class=”titleClass”>This is some text</p> The jQuery selector looks like this: $(“.titleClass”) The following selector selects all <div> elements on the entire page: $(“div”)
  • 10. Working with HTML Using jQuery jQuery append() Method The append() method inserts specified content at the end of the selected elements. $("#lis").append("<li>Angulas</li>");
  • 11. Working with HTML Using jQuery Reading attributes Reading an attribute with jQuery means using the attr() function. alert($(“#exLink”).attr(“href”)); Changing attributes You can also set the value of an attribute using the attr() function $(“#exLink”).attr(“href”, “http://www.w3c.org”); $(“#theImage”).attr(“src”,”Desert.jpg”);
  • 12. Working with HTML Using jQuery Changing CSS You can also change the styling information on a page, either by setting the styles directly or by changing the CSS class applied to an element. Class is just another attribute on an element, so changing CSS means using the attr() function again. $(“#theImage”).attr(“class”,”borderClass”);
  • 13. Working with HTML Using jQuery Adding a Class You could use the jQuery function for adding a class, called addClass(). The addClass() function doesn’t interfere with any other classes that are already applied to an element; it just adds another class to it. $(“#theImage”).addClass(“borderClass”); Removing a class A companion to the addClass() function, called removeClass, takes theclass away from an element. Like addClass(), removeClass() doesn’t affect other classes that are on the element; it removes only the specified class. $(“#theImage”).removeClass(“borderClass”);
  • 14. <!doctype html> <html><head> <title>jQuery</title> <script type=”text/javascript”src=”1.8.1.min.js”> </script> </head> <body> <h1>Adding HTML</h1> <ul id=”theList”> <li>Here’s 1</li> <li>Here’s 2</li> </ul> <script type=”text/javascript”> $(document).ready(function() { $(“#theList”).append(“<li>Here’s 3</li>”); });</script></body> </html>
  • 15. <!doctype html> <html> <head> <title>jQuery</title> <script type=”text/javascript” src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.1.min.js”> </script> </head> <body> <h1>Attributes</h1> <a id=”exLink” class=”link” href=”http://www.example.com”>Web site</a> <script type=”text/javascript”> $(document).ready(function() { alert($(“#exLink”).attr(“href”)); }); </script> </body> </html>
  • 16. <!doctype html><html> <head><title>jQuery</title> <script type="text/javascript" src="jquery-1.8.1.min.js"> </script></head> <body> <h1>Changing CSS</h1> <img id="exImage" src="document.png" alt="Document" /> <style type="text/css"> .borderClass{ border:1px solid green; } </style> <script type="text/javascript"> $(document).ready(function(){ $("#exImage").attr("class","borderClass"); }); </script> </body> </html>
  • 17. <!doctype html> <html><head><title>jQuery</title> <script type="text/javascript" src="jquery-1.8.1.min.js"> </script></head><body> <h1>Adding CSS</h1> <img id="exImage" src="document.png" alt="Document" class="borderClass" /> <style type="text/css"> .borderClass{ border:1px solid green; } .bo{ border:1px dashed red; } </style> <script type="text/javascript"> $(document).ready(function(){ $("#exImage").addClass("bo"); }); </script> </body></html> </html>
  • 18. <!doctype html> <html><head><title>jQuery</title> <script type="text/javascript" src="jquery-1.8.1.min.js"> </script></head><body> <h1>Removing CSS</h1> <img id="exImage" src="document.png" alt="Document" class="borderClass" /> <style type="text/css"> .borderClass{ border:1px solid green; } </style> <script type="text/javascript"> $(document).ready(function(){ $("#exImage").removeClass("borderClass"); }); </script> </body> </html>
  • 19. Working with Events and Event Listeners When it comes to web programming, events are the things that happen in a web page. For example, a user might move the mouse over a button, click a button, or submit a form. Understanding Events In general, there are four types of events that you’ll be concerned about: ✦ Form events: Includes things like selecting a check box or submitting the form itself. Reacting to form events is one of the most common things that JavaScript programmers do. ✦ Mouse events: This can be anything from a mouse click to mouse movements on the page. That’s right; you can actually track where the mouse is on a page and react to it.
  • 20. ✦ Keyboard events: Things that happen through the keyboard, like a key press, are considered keyboard events. ✦ Page events: Things like the page loading or unloading are considered page events. You’ll be happy to know that you’ve already been reacting to the page load event through the jQuery ready() function.
  • 21. Working with Forms Adding a Submit Handler jQuery includes a function that automatically watches for a form to be submitted. $(document).ready(function() { $("form").submit(function() { alert("You submitted the form"); return false; }); });
  • 22. Working with Forms The code begins with the ready() function, which you’ve seen before. Next up, you select the form by selecting all <form> elements on the page. Next up, the submit() function is called and another function is created within it. The function’s main task is to display an alert, which you saw. The second line within the function, return false, is interesting for forms. When you use return false in a form submit event, you essentially prevent the form from submitting to the server. Therefore, you’d only want to do this for specific reasons, like when the form isn’t valid such as when the user hasn’t filled out all the required fields.
  • 23. Working with Forms When you add return false, you’re preventing the default action.Because the default action of the form is to submit to the server, adding return false prevents that default action from occurring. Another way to prevent the default action is with the jQuery preventDefault() function. You use preventDefault in certain circumstances where return false doesn’t do what you want. Changing the JavaScript from the receding $(document).ready(function() { $(“form”).submit(function(event) { alert(“You submitted the form”); event.preventDefault(); return false; });});
  • 24. Working with Forms Checking for blank fields You can change the JavaScript to make sure that the field has been filled in. Recall that the ID of the Name field is “username”. jQuery can select that pretty easily, and then it’s a matter of getting the value for the field. For that, you can use jQuery’s val() function. Finally, all you need to do is put the whole thing in an if statement to make sure the value isn’t empty. $(document).ready(function() { $("form").submit(function(event) { if ($("#username").val() == "") { alert("Name cant be blank"); event.preventDefault(); return false; } }); });
  • 25. Keyboard events you react to keyboard events. Things like watching when a certain key is pressed, or more generically, just counting the number of times the keys are pressed, can all be done with JavaScript. Counting characters $(document).ready(function() { var maxCharacters = 50; $("#message").on("keyup",function() { var currentVal = $("#message").val().length; var totalRemaining = maxCharacters - currentVal; $("#remaining").text(totalRemaining); }); });
  • 26. Keyboard events This JavaScript first sets a variable with the maximum number of characters allowed, 50. Then the element with the ID of “message” is selected. A event handler is attached to the selected element. The event handler is attached with the on() function, which is a generic event handler. The event handlers you’ve seen so far are all so common that the folks at jQuery created specific functions to handle them. So things like submit(), click(), and hover() all have their own events. However, all other events are attached using the on() function. The first argument to the on() function is the name of the event to watch for. In this case, you want to watch for the “keyup” event to know when a key is pressed and then released.