SlideShare a Scribd company logo
Introducing jQuery Part 2
                                                                                                   Dan Wellman




Introducing jQuery Part 2
Welcome to Part 2 of the jQuery introductory series. In Part 1 we looked at some of the most foundational
aspects of the library including how basic element selection is carried out and how jQuery methods can be
used on the fundamental jQuery objects created following element selection.

In this part of the tutorial we’re going to look at how events are handled within the jQuery framework and
how we can detect and react to them in our own web applications and the methods available to you to
build an effective event solution.

The main Event
A whole component of the jQuery library is dedicated to the detection and reaction of standard browser
events which are likely to occur frequently (during every visit to our page) when visitors view our pages. We
can even define our own custom events that have never been seen or heard of before and add code
routines to handle these as well. Events are a key foundational part of any web application and allow you to
define and react to interactions between your site and your visitors.

One event that is used almost every time the jQuery library is engaged is the ready event. This can be used
in either the full $(document).ready(function(){}); or the shorthand $(function(){}); formats, and
will execute the code within its curly braces when the document is ready, which is typically once the page
has finished loading (except on pages with a lot of images, where the DOM may be ready before all of the
images have finished loading). It’s an extremely useful construct and something I have used in every single
one of my jQuery implementations.

First of all, let’s look at a brief example of how a basic, standard event can be handled using the jQuery
library. In a blank page in your text editor, start off with the following very basic page:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
“http://www.w3.org/TR/html4/strict.dtd”>
<html lang=“en”>
 <head>
 <title>jQuery Event Example</title>
 <script type=“text/javascript” src=“jquery/jquery-1.2.1.min.js”></script>
 </head>
 <body>
 <button id=“button1”>Click Me!</button>
 </body>
</html>

Now add the document ready and the click event handlers in their own <script> tag in the <head> of
the page:

<script type=“text/javascript”>
 $(function(){
 $(“#button1”).click(function() {
 alert(“You clicked “ + $(this).attr(“id”));
 });
 });
</script>




                                  Copyright © 2008 DMXzone.com All Rights Reserved
                                          To get more go to DMXzone.com
                                                   Page 1 of 6
Introducing jQuery Part 2
                                                                                                   Dan Wellman




The .click() method, known as an Event Helper, is attached directly to the jQuery object representing the
element from the DOM with an id of button1. It contains an anonymous function which in this example
simply alerts a message containing the button’s id attribute.

A wide range of different events can be handled in this way, and it is a perfect system for reacting to events
which are only triggered by small number of elements. To extend the example slightly, add the following
code to the existing <script> tag, ensuring that it is within the outer anonymous function executed when
the page is ready:

$(“#button1”).keypress(function() {
 alert(“You used the keyboard to interact with “ + $(this).attr(“id”));
});

This time we bind our anonymous function to the keypress event using the .keypress() method. For
information, the keypress event is a combination of both keydown and keyup events on the same key. With
the button focused (we could add an event handler for this too!), pressing a key on the keyboard will
produce the alert.

At this stage, we don’t know which button was used to interact with the button, but an important feature of
the event model created by jQuery is that the anonymous function is automatically passed an event object
which contains various details about the event. We can examine this object to find out which key was
pressed. Alter the function so that it appears as follows:

$(“#button1”).keypress(function(e) {
 var code = e.which;
 var key = String.fromCharCode(code);
 alert(“You used the + key + “ key to interact with “ + $(this).attr(“id”));
});

The which property of the event object contains the Unicode representation of the key that was used on the
button. The standard JavaScript flavour String.fromCharCode() method translates the Unicode into a
letter representing the key that was pressed. Not all of the keyboard keys are represented in this way; some
don’t work at all and others, like the space bar or enter key for example, don’t have a string equivalent, so if
these keys are used the key variable, and the space it is added to the alert, will be empty.

The event object can also contain other properties depending on the event it represents; click events, for
example, contain the .pageX and .pageY properties so that the position of the cursor on the page when the
click occurs can be determined. We could easily code to handle either the space bar or enter key being
pressed using the following conditional if statement instead of the key variable declaration:

 if (code == “32”) {
 var key = “space”;
 } else if (code == “13”) {
 var key = “enter”;
 } else {
 var key = String.fromCharCode(code);
 }

One thing to note at this stage is known as the default browser action; some events trigger a default browser
action that is common across browsers; clicking a link for example, will navigate the user to a new page. The
default browser action is fine in most situations, although there may be times when we wish to cancel it.



                                  Copyright © 2008 DMXzone.com All Rights Reserved
                                          To get more go to DMXzone.com
                                                   Page 2 of 6
Introducing jQuery Part 2
                                                                                                     Dan Wellman




You may have noticed that when you use the enter key to interact with the button in our example, it
generates both the keydown and click alert messages. This is because the default browser action when
using the enter key to press a button is to simulate a click event.

To cancel the default browser action, all we need to do is add return false; before the final closing
bracket of the keydown anonymous function. Once this has been done, the enter key will only generate one
alert message in our example.

Additional Event Handling Methods
Our example code is fine in the context it is currently in, although if we had twenty buttons on the page
instead of just one, it would not be very efficient to add an Event helper for each button. In this situation, we
could use the jQuery .bind() method instead to share an event handler between elements. Add some
more buttons to the page, ten or so should do. Once that has been done, remove the existing Event Helper
methods and replace them with the following code:

 $(“button”).bind(“click”, function() {
 alert(“You clicked “ + $(this).attr(“id”));
 });

The .bind() method takes a minimum of two arguments, the first is the event to bind to the selected
elements and the second argument in this example is the anonymous function to be executed when the
bound event is detected. Sometimes it is not possible to use an anonymous function when binding events, in
these situations the .bind() method can easily be extended so that the function is defined elsewhere are
called using an argument. Data can be passed to the function using the optional second argument of the
method, and the function call then becomes the third argument.

The .one() method is almost exactly the same as the .bind() method, except for the fact that the .one()
method will only respond to the bound event once. Other than that, it is used in exactly the same way and
can be used with the same arguments as .bind().

If you want to remove a bound event handler, all you need to do is called the .unbind() method. It can be
used to unbind all event listeners for a matched element, or using one of its optional arguments, a specific
event can be unbound.

Custom Events
The .bind() method can also be useful when working with custom events that you yourself have defined.
Using the .bind() method in conjunction with the .trigger() or .triggerHandler() methods ensures
that your custom events are listened for and reacted to in the same way as standard events. Let’s create a
new onTenClicks event that will be triggered after ten clicks of any button on our example page. Alter your
code so that it appears as follows:

 $(“button”).bind(“onTenClicks”, function(e){
 alert(“Ten clicks detected!”);
 });
 var clicks = 1;
 $(“button”).bind(“click”, function(){
 if (clicks < 10) {
 clicks++;
 } else {
 $(“button”).triggerHandler(“onTenClicks”);
 }
});
                                   Copyright © 2008 DMXzone.com All Rights Reserved
                                           To get more go to DMXzone.com
                                                    Page 3 of 6
Introducing jQuery Part 2
                                                                                                Dan Wellman




We use a simple control variable to count the number of click events that occur, which is handled in the
normal way using the second .bind() method. On each click event, the clicks variable is incremented by
one. When the control variable reaches 10, we use the .triggerHandler() method to trigger our custom
ontenClicks event, which then generates the alert.

Interaction Helpers
As well as the Event Helpers we looked at earlier, another extremely useful feature of the events component
of jQuery are the Interaction Helpers; there are two of them at present - the .hover() method and the
.toggle() method. Both interaction Helpers specify two functions to be executed; the .hover() method
allows you to define anonymous functions to be executed on mouseover and mouseout events, so both
related events can be wrapped up in one method. The .toggle() method simply allows two functions to
be executed on alternative click events, so clicking on something once will execute the first function,
clicking the same element a second time will then trigger the second function.

Let’s have a look at how the .hover() method can be used in place of CSS roll-overs. Create the following
new page in your text editor:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
“http://www.w3.org/TR/html4/strict.dtd”>
<html lang=“en”>
 <head>
 <title>jQuery Event Example</title>
 <script type=“text/javascript” src=“jquery/jquery-1.2.1.min.js”></script>
 <script type=“text/javascript”>
 $(function(){

 });
 </script>
 <style>
 #faces {
 position:absolute;
 top:100px;
 left:100px;
 }
 #speeches {
 position:absolute;
 left:50px;
 }
 #speech1 {
 display:none;
 }
 #speech2 {
 position:absolute;
 left:220px;
 display:none;
 }
 </style>
 </head>
 <body>
 <div id=“speeches”>
 <img id=“speech1” src=“images/speech1.png”>
 <img id=“speech2” src=“images/speech2.png”>
 </div>
 <div id=“faces”>
                                 Copyright © 2008 DMXzone.com All Rights Reserved
                                         To get more go to DMXzone.com
                                                  Page 4 of 6
Introducing jQuery Part 2
                                                                                                 Dan Wellman




 <img id=“face1” src=“images/face1.png”>
 <img id=“face2” src=“images/face2.png”>
 </div>
 </body>
</html>

So we have a few images on the page, which have been positioned with some CSS. A couple of images
have also been hidden at this point. We also have the $(function(){}) handler ready to be filled with
code. The following methods will complete the example:

$(“#face1”).hover(
 function() {
 $(“#speech1”).css({display:”block”});
 },
 function() {
 $(“#speech1”).css({display:”none”});
 }
);

When you roll over the element with an id of ‘face1’, the first anonymous function within the .hover() method
is executed, showing the image that has an id of ‘speech1’. When the mouse rolls back off of the image, the
second method is executed, hiding the image once more. We can do the same for the second face as well:

$(“#face2”).hover(
 function() {
 $(“#speech2”).css({display:”block”});
 },
 function() {
 $(“#speech2”).css({display:”none”});
 }
);

Figure 1 below shows how the page should roughly look:




                                           Figure 1 – the Arguing Faces



                                 Copyright © 2008 DMXzone.com All Rights Reserved
                                         To get more go to DMXzone.com
                                                  Page 5 of 6
Introducing jQuery Part 2
                                                                                                  Dan Wellman




The .toggle() method I mentioned earlier is coded in exactly the same way; we could use this method
instead of the .hover() method in the previous example and it would be exactly the same except that the
speech bubbles would appear on clicks instead of hovers.

Summary
Events are the cornerstone of any web 2.0 application and allow you to react to different interactions that
take place between your visitors and your application. jQuery makes this task easier for you, and presents a
unified event model in which each browser works with events in the same way and has equal access to the
event object where it is needed.

We can set and remove event listeners with the .bind() and .unbind() methods, react to almost any
event with the Event Helpers, trigger events and custom events with .trigger() and .triggerHandler(),
and produce interesting hover and click functions with the .hover() and .toggle() methods.

This brings us to the end of part 2 of the introduction to jQuery series. Over the course of this part we have
looked in detail at the event component of the jQuery library and investigated how each of its methods can
be used. I hope to see you when this series continues with Part 3, when we will be looking in detail at the
stunning and ultra-useful CSS and Effects components of jQuery.




                                  Copyright © 2008 DMXzone.com All Rights Reserved
                                          To get more go to DMXzone.com
                                                   Page 6 of 6
Ad

More Related Content

What's hot (20)

Event handling in Java(part 2)
Event handling in Java(part 2)Event handling in Java(part 2)
Event handling in Java(part 2)
RAJITHARAMACHANDRAN1
 
Event handling in Java(part 1)
Event handling in Java(part 1)Event handling in Java(part 1)
Event handling in Java(part 1)
RAJITHARAMACHANDRAN1
 
DHTML - Events & Buttons
DHTML - Events  & ButtonsDHTML - Events  & Buttons
DHTML - Events & Buttons
Deep Patel
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandling
Arati Gadgil
 
Work flow
Work flowWork flow
Work flow
soulsama
 
Calculadora
CalculadoraCalculadora
Calculadora
guest6473b8
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handling
Amol Gaikwad
 
J Query Presentation of David
J Query Presentation of DavidJ Query Presentation of David
J Query Presentation of David
Arun David Johnson R
 
ちょっと優しい入力項目
ちょっと優しい入力項目ちょっと優しい入力項目
ちょっと優しい入力項目
shinya sakemoto
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
Payal Dungarwal
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
sotlsoc
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
jammiashok123
 
DotNetNuke Client API -DragDropAdminModules.pdf
DotNetNuke Client API -DragDropAdminModules.pdfDotNetNuke Client API -DragDropAdminModules.pdf
DotNetNuke Client API -DragDropAdminModules.pdf
arunagulla
 
Java Event Handling
Java Event HandlingJava Event Handling
Java Event Handling
Shraddha
 
Introducing jQuery
Introducing jQueryIntroducing jQuery
Introducing jQuery
Grzegorz Ziolkowski
 
03 page navigation and data binding in windows runtime apps
03   page navigation and data binding in windows runtime apps03   page navigation and data binding in windows runtime apps
03 page navigation and data binding in windows runtime apps
WindowsPhoneRocks
 
Android UI Reference
Android UI ReferenceAndroid UI Reference
Android UI Reference
GauntFace
 
Intro to Google TV
Intro to Google TVIntro to Google TV
Intro to Google TV
GauntFace
 
What the FUF?
What the FUF?What the FUF?
What the FUF?
An Doan
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
teach4uin
 
DHTML - Events & Buttons
DHTML - Events  & ButtonsDHTML - Events  & Buttons
DHTML - Events & Buttons
Deep Patel
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandling
Arati Gadgil
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handling
Amol Gaikwad
 
ちょっと優しい入力項目
ちょっと優しい入力項目ちょっと優しい入力項目
ちょっと優しい入力項目
shinya sakemoto
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
Payal Dungarwal
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
sotlsoc
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
jammiashok123
 
DotNetNuke Client API -DragDropAdminModules.pdf
DotNetNuke Client API -DragDropAdminModules.pdfDotNetNuke Client API -DragDropAdminModules.pdf
DotNetNuke Client API -DragDropAdminModules.pdf
arunagulla
 
Java Event Handling
Java Event HandlingJava Event Handling
Java Event Handling
Shraddha
 
03 page navigation and data binding in windows runtime apps
03   page navigation and data binding in windows runtime apps03   page navigation and data binding in windows runtime apps
03 page navigation and data binding in windows runtime apps
WindowsPhoneRocks
 
Android UI Reference
Android UI ReferenceAndroid UI Reference
Android UI Reference
GauntFace
 
Intro to Google TV
Intro to Google TVIntro to Google TV
Intro to Google TV
GauntFace
 
What the FUF?
What the FUF?What the FUF?
What the FUF?
An Doan
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
teach4uin
 

Similar to Introj Query Pt2 (20)

JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 
Javascript Browser Events.pdf
Javascript Browser Events.pdfJavascript Browser Events.pdf
Javascript Browser Events.pdf
ShubhamChaurasia88
 
Document_Object_Model_in_javaScript..................................ppt
Document_Object_Model_in_javaScript..................................pptDocument_Object_Model_in_javaScript..................................ppt
Document_Object_Model_in_javaScript..................................ppt
rahamatmandal2005
 
Javascript #8 : événements
Javascript #8 : événementsJavascript #8 : événements
Javascript #8 : événements
Jean Michel
 
Advanced Jquery
Advanced JqueryAdvanced Jquery
Advanced Jquery
Ahmed Elharouny
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
dmethvin
 
Unit3.pptx
Unit3.pptxUnit3.pptx
Unit3.pptx
AnamikaRai59
 
Web programming
Web programmingWeb programming
Web programming
Subha Selvam
 
5 .java script events
5 .java script   events5 .java script   events
5 .java script events
chauhankapil
 
types of events in JS
types of events in JS types of events in JS
types of events in JS
chauhankapil
 
Dojo1.0_Tutorials
Dojo1.0_TutorialsDojo1.0_Tutorials
Dojo1.0_Tutorials
tutorialsruby
 
Dojo1.0_Tutorials
Dojo1.0_TutorialsDojo1.0_Tutorials
Dojo1.0_Tutorials
tutorialsruby
 
Event
EventEvent
Event
mussawir20
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
udithaisur
 
Introduction to GUIs with guizero
Introduction to GUIs with guizeroIntroduction to GUIs with guizero
Introduction to GUIs with guizero
primeteacher32
 
Chap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptxChap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptx
TadeseBeyene
 
2310 b 05
2310 b 052310 b 05
2310 b 05
Krazy Koder
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
Lilia Sfaxi
 
How to Detect a Click Outside a React Component.pptx
How to Detect a Click Outside a React Component.pptxHow to Detect a Click Outside a React Component.pptx
How to Detect a Click Outside a React Component.pptx
BOSC Tech Labs
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
Ayesha Kanwal
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 
Document_Object_Model_in_javaScript..................................ppt
Document_Object_Model_in_javaScript..................................pptDocument_Object_Model_in_javaScript..................................ppt
Document_Object_Model_in_javaScript..................................ppt
rahamatmandal2005
 
Javascript #8 : événements
Javascript #8 : événementsJavascript #8 : événements
Javascript #8 : événements
Jean Michel
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
dmethvin
 
5 .java script events
5 .java script   events5 .java script   events
5 .java script events
chauhankapil
 
types of events in JS
types of events in JS types of events in JS
types of events in JS
chauhankapil
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
udithaisur
 
Introduction to GUIs with guizero
Introduction to GUIs with guizeroIntroduction to GUIs with guizero
Introduction to GUIs with guizero
primeteacher32
 
Chap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptxChap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptx
TadeseBeyene
 
How to Detect a Click Outside a React Component.pptx
How to Detect a Click Outside a React Component.pptxHow to Detect a Click Outside a React Component.pptx
How to Detect a Click Outside a React Component.pptx
BOSC Tech Labs
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
Ayesha Kanwal
 
Ad

Recently uploaded (20)

Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Does Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should KnowDoes Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should Know
Pornify CC
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Does Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should KnowDoes Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should Know
Pornify CC
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
Ad

Introj Query Pt2

  • 1. Introducing jQuery Part 2 Dan Wellman Introducing jQuery Part 2 Welcome to Part 2 of the jQuery introductory series. In Part 1 we looked at some of the most foundational aspects of the library including how basic element selection is carried out and how jQuery methods can be used on the fundamental jQuery objects created following element selection. In this part of the tutorial we’re going to look at how events are handled within the jQuery framework and how we can detect and react to them in our own web applications and the methods available to you to build an effective event solution. The main Event A whole component of the jQuery library is dedicated to the detection and reaction of standard browser events which are likely to occur frequently (during every visit to our page) when visitors view our pages. We can even define our own custom events that have never been seen or heard of before and add code routines to handle these as well. Events are a key foundational part of any web application and allow you to define and react to interactions between your site and your visitors. One event that is used almost every time the jQuery library is engaged is the ready event. This can be used in either the full $(document).ready(function(){}); or the shorthand $(function(){}); formats, and will execute the code within its curly braces when the document is ready, which is typically once the page has finished loading (except on pages with a lot of images, where the DOM may be ready before all of the images have finished loading). It’s an extremely useful construct and something I have used in every single one of my jQuery implementations. First of all, let’s look at a brief example of how a basic, standard event can be handled using the jQuery library. In a blank page in your text editor, start off with the following very basic page: <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”> <html lang=“en”> <head> <title>jQuery Event Example</title> <script type=“text/javascript” src=“jquery/jquery-1.2.1.min.js”></script> </head> <body> <button id=“button1”>Click Me!</button> </body> </html> Now add the document ready and the click event handlers in their own <script> tag in the <head> of the page: <script type=“text/javascript”> $(function(){ $(“#button1”).click(function() { alert(“You clicked “ + $(this).attr(“id”)); }); }); </script> Copyright © 2008 DMXzone.com All Rights Reserved To get more go to DMXzone.com Page 1 of 6
  • 2. Introducing jQuery Part 2 Dan Wellman The .click() method, known as an Event Helper, is attached directly to the jQuery object representing the element from the DOM with an id of button1. It contains an anonymous function which in this example simply alerts a message containing the button’s id attribute. A wide range of different events can be handled in this way, and it is a perfect system for reacting to events which are only triggered by small number of elements. To extend the example slightly, add the following code to the existing <script> tag, ensuring that it is within the outer anonymous function executed when the page is ready: $(“#button1”).keypress(function() { alert(“You used the keyboard to interact with “ + $(this).attr(“id”)); }); This time we bind our anonymous function to the keypress event using the .keypress() method. For information, the keypress event is a combination of both keydown and keyup events on the same key. With the button focused (we could add an event handler for this too!), pressing a key on the keyboard will produce the alert. At this stage, we don’t know which button was used to interact with the button, but an important feature of the event model created by jQuery is that the anonymous function is automatically passed an event object which contains various details about the event. We can examine this object to find out which key was pressed. Alter the function so that it appears as follows: $(“#button1”).keypress(function(e) { var code = e.which; var key = String.fromCharCode(code); alert(“You used the + key + “ key to interact with “ + $(this).attr(“id”)); }); The which property of the event object contains the Unicode representation of the key that was used on the button. The standard JavaScript flavour String.fromCharCode() method translates the Unicode into a letter representing the key that was pressed. Not all of the keyboard keys are represented in this way; some don’t work at all and others, like the space bar or enter key for example, don’t have a string equivalent, so if these keys are used the key variable, and the space it is added to the alert, will be empty. The event object can also contain other properties depending on the event it represents; click events, for example, contain the .pageX and .pageY properties so that the position of the cursor on the page when the click occurs can be determined. We could easily code to handle either the space bar or enter key being pressed using the following conditional if statement instead of the key variable declaration: if (code == “32”) { var key = “space”; } else if (code == “13”) { var key = “enter”; } else { var key = String.fromCharCode(code); } One thing to note at this stage is known as the default browser action; some events trigger a default browser action that is common across browsers; clicking a link for example, will navigate the user to a new page. The default browser action is fine in most situations, although there may be times when we wish to cancel it. Copyright © 2008 DMXzone.com All Rights Reserved To get more go to DMXzone.com Page 2 of 6
  • 3. Introducing jQuery Part 2 Dan Wellman You may have noticed that when you use the enter key to interact with the button in our example, it generates both the keydown and click alert messages. This is because the default browser action when using the enter key to press a button is to simulate a click event. To cancel the default browser action, all we need to do is add return false; before the final closing bracket of the keydown anonymous function. Once this has been done, the enter key will only generate one alert message in our example. Additional Event Handling Methods Our example code is fine in the context it is currently in, although if we had twenty buttons on the page instead of just one, it would not be very efficient to add an Event helper for each button. In this situation, we could use the jQuery .bind() method instead to share an event handler between elements. Add some more buttons to the page, ten or so should do. Once that has been done, remove the existing Event Helper methods and replace them with the following code: $(“button”).bind(“click”, function() { alert(“You clicked “ + $(this).attr(“id”)); }); The .bind() method takes a minimum of two arguments, the first is the event to bind to the selected elements and the second argument in this example is the anonymous function to be executed when the bound event is detected. Sometimes it is not possible to use an anonymous function when binding events, in these situations the .bind() method can easily be extended so that the function is defined elsewhere are called using an argument. Data can be passed to the function using the optional second argument of the method, and the function call then becomes the third argument. The .one() method is almost exactly the same as the .bind() method, except for the fact that the .one() method will only respond to the bound event once. Other than that, it is used in exactly the same way and can be used with the same arguments as .bind(). If you want to remove a bound event handler, all you need to do is called the .unbind() method. It can be used to unbind all event listeners for a matched element, or using one of its optional arguments, a specific event can be unbound. Custom Events The .bind() method can also be useful when working with custom events that you yourself have defined. Using the .bind() method in conjunction with the .trigger() or .triggerHandler() methods ensures that your custom events are listened for and reacted to in the same way as standard events. Let’s create a new onTenClicks event that will be triggered after ten clicks of any button on our example page. Alter your code so that it appears as follows: $(“button”).bind(“onTenClicks”, function(e){ alert(“Ten clicks detected!”); }); var clicks = 1; $(“button”).bind(“click”, function(){ if (clicks < 10) { clicks++; } else { $(“button”).triggerHandler(“onTenClicks”); } }); Copyright © 2008 DMXzone.com All Rights Reserved To get more go to DMXzone.com Page 3 of 6
  • 4. Introducing jQuery Part 2 Dan Wellman We use a simple control variable to count the number of click events that occur, which is handled in the normal way using the second .bind() method. On each click event, the clicks variable is incremented by one. When the control variable reaches 10, we use the .triggerHandler() method to trigger our custom ontenClicks event, which then generates the alert. Interaction Helpers As well as the Event Helpers we looked at earlier, another extremely useful feature of the events component of jQuery are the Interaction Helpers; there are two of them at present - the .hover() method and the .toggle() method. Both interaction Helpers specify two functions to be executed; the .hover() method allows you to define anonymous functions to be executed on mouseover and mouseout events, so both related events can be wrapped up in one method. The .toggle() method simply allows two functions to be executed on alternative click events, so clicking on something once will execute the first function, clicking the same element a second time will then trigger the second function. Let’s have a look at how the .hover() method can be used in place of CSS roll-overs. Create the following new page in your text editor: <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”> <html lang=“en”> <head> <title>jQuery Event Example</title> <script type=“text/javascript” src=“jquery/jquery-1.2.1.min.js”></script> <script type=“text/javascript”> $(function(){ }); </script> <style> #faces { position:absolute; top:100px; left:100px; } #speeches { position:absolute; left:50px; } #speech1 { display:none; } #speech2 { position:absolute; left:220px; display:none; } </style> </head> <body> <div id=“speeches”> <img id=“speech1” src=“images/speech1.png”> <img id=“speech2” src=“images/speech2.png”> </div> <div id=“faces”> Copyright © 2008 DMXzone.com All Rights Reserved To get more go to DMXzone.com Page 4 of 6
  • 5. Introducing jQuery Part 2 Dan Wellman <img id=“face1” src=“images/face1.png”> <img id=“face2” src=“images/face2.png”> </div> </body> </html> So we have a few images on the page, which have been positioned with some CSS. A couple of images have also been hidden at this point. We also have the $(function(){}) handler ready to be filled with code. The following methods will complete the example: $(“#face1”).hover( function() { $(“#speech1”).css({display:”block”}); }, function() { $(“#speech1”).css({display:”none”}); } ); When you roll over the element with an id of ‘face1’, the first anonymous function within the .hover() method is executed, showing the image that has an id of ‘speech1’. When the mouse rolls back off of the image, the second method is executed, hiding the image once more. We can do the same for the second face as well: $(“#face2”).hover( function() { $(“#speech2”).css({display:”block”}); }, function() { $(“#speech2”).css({display:”none”}); } ); Figure 1 below shows how the page should roughly look: Figure 1 – the Arguing Faces Copyright © 2008 DMXzone.com All Rights Reserved To get more go to DMXzone.com Page 5 of 6
  • 6. Introducing jQuery Part 2 Dan Wellman The .toggle() method I mentioned earlier is coded in exactly the same way; we could use this method instead of the .hover() method in the previous example and it would be exactly the same except that the speech bubbles would appear on clicks instead of hovers. Summary Events are the cornerstone of any web 2.0 application and allow you to react to different interactions that take place between your visitors and your application. jQuery makes this task easier for you, and presents a unified event model in which each browser works with events in the same way and has equal access to the event object where it is needed. We can set and remove event listeners with the .bind() and .unbind() methods, react to almost any event with the Event Helpers, trigger events and custom events with .trigger() and .triggerHandler(), and produce interesting hover and click functions with the .hover() and .toggle() methods. This brings us to the end of part 2 of the introduction to jQuery series. Over the course of this part we have looked in detail at the event component of the jQuery library and investigated how each of its methods can be used. I hope to see you when this series continues with Part 3, when we will be looking in detail at the stunning and ultra-useful CSS and Effects components of jQuery. Copyright © 2008 DMXzone.com All Rights Reserved To get more go to DMXzone.com Page 6 of 6
  翻译: