jQuery Events and Effects
References
jQuery Events
JavaScript events are things that happen in the browser, which you can respond to with JavaScript code.
You respond to these events in JavaScript with event handlers.
And you can use jQuery event functions in your event handler code. The event handler code is most often in a function in the head section of your HTML page.
The jQuery event functions that are most frequently used are these:
- $(document).ready(function) - Tells the browser to call a particular function when the document is finished loading.
- $(selector).click(function) - Tells the browser to call a particular function when the user clicks in one of the selected elements.
- $(selector).dblclick(function) - Tells the browser to call a particular function when the user double-clicks in one of the selected elements.
- $(selector).focus(function) - Tells the browser to call a particular function when one of the selected elements receives the browser's focus.
- $(selector).mouseover(function) - Tells the browser to call a particular function when the user moves the mouse cursor over one of the selected elements.
- $(selector).on(events [,data], function) - Tells the browser to call a particular function when the given events occur for the selected element(s). The events argument is one or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". The event can optionally send some data to the function that handles the event processing.
Here is some sample code that shows how you could tell the browser to hide some paragraphs when the user clicks a "Click me" button. This is page jQueryHideParagraphs.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Hide Some Paragraphs</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<div id="mainDiv">
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</div>
</body>
</html>
And now here is some sample code that shows how to use the .on action function. This is page jQueryDataToEvent.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Sending Data to an Event Handler</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function greet( event )
{
alert( "Hello " + event.data.name + "!");
}
$( "#button1" ).on( "click", { name: "Fred" }, greet );
$( "#button2" ).on( "click", { name: "Addy" }, greet );
});
</script>
</head>
<body>
<div id="mainDiv">
<h2>Button Events</h2>
<button id="button1">Click me!</button>
<br>
<button id="button2">No, click me!</button>
</div>
</body>
</html>
Please note these points about the above code:
- The .on() action function is the preferred way of connecting an event to an element. It replaces some older action functions such as "click()", "dblclick()", "mouseover()", etc. The older event functions may still be used.
- The second argument to the .on() functions above is the data that will be sent to the event-handler function. These data in this example are in the form of an anonymous object, which is somewhat analogous to the anonymous functions that we have seen a lot in these jQuery e-handouts.
-
These anonymous objects have the form
{ name: "Addy" }where name: is the property, and "Fred" or "Addy" are the property values. - The data that are sent into the event-handler function become the .data property of the event parameter inside the function. The event parameter is the data object that got sent into the function.
jQuery Effects
"jQuery Effects" is a term that can be used to describe some of the jQuery functions which visibly affect HTML elements.
Some of the jQuery functions which cause HTML "effects" are these:
- $(selector).hide() - Hide selected elements
- $(selector).show() - Show selected elements
- $(selector).toggle() - Toggle selected elements between hide and show
- $(selector).slideDown() - Slide-down (show) selected elements
- $(selector).slideUp() - Slide-up (hide) selected elements
- $(selector).slideToggle() - Toggle slide-up and slide-down of selected elements
- $(selector).fadeIn() - Fade in (show) selected elements
- $(selector).fadeOut() - Fade out (hide) selected elements
- $(selector).fadeTo() - Fade out selected elements to a given opacity
- $(selector).animate() - Perform a custom animation (such as a width or height change) on selected elements
- $(selector).html() - Change the html content (the innerHTML property) of the selected element
Hide and Show
Here is a sample of both hide() and show() in a page. This is page jQueryShowAndHide.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Show and Hide</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>
<div id="mainDiv">
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</div>
</body>
</html>
Please note that the selectors that are being used in the above code to connect the "click" event functions to the buttons, are "id" selectors.
Toggle
The jQuery toggle() method toggles the visibility of HTML elements by using the show() or hide() methods.
Here is a sample of toggle() in action. This is page jQueryToggle.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Toggle</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//$(".startHidden").hide();
//$(".startShown").show();
$("button").click(function(){
$("p").toggle();
});
});
</script>
<style type="text/css">
#mainDiv { position: relative; height: 120px; }
.startHidden { display: none; position: absolute; left: 20px; top: 40px; }
.startShown { display: block; position: absolute; left: 20px; top: 80px; }
</style>
</head>
<body>
<div id="mainDiv">
<button>Toggle</button>
<p class="startHidden">This paragraph is hidden to start.</p>
<p class="startShown">This paragraph is displayed to start.</p>
</div>
</body>
</html>
SlideDown and SlideUp
The jQuery functions slideDown() and slideUp() can be used for some nice transition effects in your page.
Here is a very simple example of a slide-down and slide-up transition effect. This is page jQuerySlideStuff.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>jQuery SlideDown and SlideUp</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
$(".flip").mouseover(function(){
$(".panel").slideDown("slow");
});
$(".flip").mouseout(function(){
$(".panel").slideUp("slow");
});
});
/* ]]> */
</script>
<style type="text/css">
div.panel,p.flip
{
margin:0px;
padding:15px;
text-align:justify;
background:#e5eecc;
border:solid 1px #c3c3c3;
}
div.panel
{
height:380px;
display:none;
border-radius: 10px;
}
p {
margin: 1em 0;
}
#instructions
{
font-family: Arial, sans-serif;
font-size: 1.3em;
position: absolute;
top: 480px;
margin: 0 auto;
}
img {
position: absolute;
left: 200px;
top: 140px;
}
#mainDiv {
height: 420px;
}
</style>
</head>
<body>
<div id="mainDiv">
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus et metus sapien,
nec consectetur massa. Pellentesque imperdiet mi sed magna ullamcorper sed viverra
libero faucibus. Vivamus vel tellus eros. Vestibulum vulputate dictum erat vel
vestibulum. Nunc at leo enim, non suscipit sapien. Fusce a gravida sem. Mauris
mauris odio, pellentesque.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce pretium nisi
et diam pretium at fermentum sapien mollis. Sed ut dolor in felis fermentum ornare.
Suspendisse venenatis, odio in vehicula venenatis, neque sem luctus neque, vitae
interdum nunc mauris ut magna. Suspendisse ultrices ultricies pellentesque. Fusce
sed massa augue. Quisque.</p>
</div>
<img src="images/album-200020.jpg" class="flip" width="266" height="266" alt="" title="" />
<div id="instructions">
<p>
Move your mouse cursor over the image to see the slide-down effect.
</p>
<p>
Move your mouse cursor off the image to see the slide-up effect.
</p>
</div>
</div>
</body>
</html>
SlideToggle
The set of jQuery functions that have "slide" in their names is somewhat analogous to show(), hide(), and toggle(). The slideToggle() function works like toggle(), but using a slide-down and slide-up action.
Here is a sample of the slideToggle() function in action. This is page jQuerySlideToggle.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>SlideToggle</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideToggle("slow");
});
});
</script>
<style type="text/css">
div.panel
{
height: 400px;
display:none;
margin:0px;
padding:15px;
text-align:justify;
background:#e5eecc;
border:solid 1px #c3c3c3;
}
p.flip
{
margin:0px;
padding:5px;
text-align:center;
background:#e5eecc;
border:solid 1px #c3c3c3;
cursor: pointer;
}
</style>
</head>
<body>
<div id="mainDiv">
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus et metus sapien,
nec consectetur massa. Pellentesque imperdiet mi sed magna ullamcorper sed viverra
libero faucibus. Vivamus vel tellus eros. Vestibulum vulputate dictum erat vel
vestibulum. Nunc at leo enim, non suscipit sapien. Fusce a gravida sem. Mauris
mauris odio, pellentesque.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce pretium nisi
et diam pretium at fermentum sapien mollis. Sed ut dolor in felis fermentum ornare.
Suspendisse venenatis, odio in vehicula venenatis, neque sem luctus neque, vitae
interdum nunc mauris ut magna. Suspendisse ultrices ultricies pellentesque. Fusce
sed massa augue. Quisque.</p>
</div>
<p class="flip">Click to Slide the Panel</p>
</div>
</body>
</html>
Fade
There is a set of jQuery functions with "fade" in their names.
Here is a sample of how to fade a <div> tag that is positioned over another <div> tag. This is page jQueryHideDoorThree.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Hide Door Three</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("#doorThree").fadeTo("slow",0);
});
});
</script>
<style type="text/css">
#doorThree {background:#ADD;font-size:10em;width:300px;height:300px;position:absolute;
top:70px;z-index:2;text-align:center;}
#thePrize {background:blue;color:white;width:300px;height:300px;position:absolute;
top:70px;z-index:1;text-align:center;}
p {margin-top: 30px;}
#mainDiv {height: 350px;}
</style>
</head>
<body>
<div id="mainDiv">
<button>See What's Behind Door Number 3</button>
<div id="doorThree">
<p>3</p>
</div>
<div id="thePrize">
<h3>A Dream Vacation!</h3>
</div>
</div>
</body>
</html>
The next example is another demonstration of how you can send data into the event-handler functions.. It also shows how you can accomplish multiple jQuery actions in the same function. This is page multipleJQueryEvents.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Sending Data to an Event Handler</title>
<style type="text/css">
#angryDiv, #cuteDiv
{
width: 500px;
height: 300px;
position: absolute;
left: 50%;
top: 200px;
margin-left: -250px;
display: none;
}
#captionDiv
{
width: 500px;
height: 40px;
position: absolute;
left: 50%;
top: 540px;
margin-left: -250px;
display: none;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function announce( event )
{
$("#captionDiv").show();
var captionStr;
if (event.data.angryThing === true)
{
captionStr = event.data.name + " is angry!";
}
else
{
captionStr = event.data.name + " is happy.";
}
$("#captionDiv").html(captionStr);
}
function showImage( event )
{
if (event.data.angryThing === true)
{
$("#angryDiv").fadeTo(400,1);
}
else
{
$("#cuteDiv").fadeTo(400,1);
}
}
function hideImage( event )
{
$("#captionDiv").hide();
if (event.data.angryThing === true)
{
$("#angryDiv").fadeTo(400,0);
}
else
{
$("#cuteDiv").fadeTo(400,0);
}
}
$( "#button1" ).on( "mouseover", { angryThing: true }, showImage );
$( "#button2" ).on( "mouseover", { angryThing: false }, showImage );
$( "#button1" ).on( "mouseout", { angryThing: true }, hideImage );
$( "#button2" ).on( "mouseout", { angryThing: false }, hideImage );
$( "#button1" ).on( "click", { name: "George", angryThing: true }, announce );
$( "#button2" ).on( "click", { name: "Addy", angryThing: false }, announce );
});
</script>
</head>
<body>
<div id="mainDiv">
<h2>Sending Data to an Event Handler</h2>
<button id="button1">Angry Stuff</button>
<button id="button2">Cute Stuff</button>
</div>
<div id="angryDiv">
<img src="images/angryCatCrop.jpg" width="500" height="300" alt="Angry Cat" title="Angry Cat">
</div>
<div id="cuteDiv">
<img src="images/cuteCatCrop.jpg" width="500" height="300" alt="Cute Cat" title="Cute Cat">
</div>
<div id="captionDiv"></div>
</body>
</html>
Please note these points about the above code:
-
Several of the event-handling functions have this line of code in them:
if (event.data.angryThing === true)
which receives data from the jQuery event action functions.
-
The data that are sent into the event-handler functions become the .data property of the
event parameter inside the functions. The event parameter is the data object that got sent into
the functions.
- Several different <div> tags are being changed in some of the event-handling functions. This is a common situation.
Animate
The jQuery function animate() can be used to change many CSS properties and to give the effect of a tag's being animated.
There are four possible parameters in the animate() definition.
The first parameter, which is required, is {params}, and it is a list of CSS properties that you want to change.
The second parameter, which is optional, is duration, and it can take the values of "fast", "slow", "normal", or milliseconds.
Here is a sample of a simple jQuery animation. This is page jQueryAnimate.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>jQuery Animation</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left:"100px",fontSize:"3em",height:"+=100",width:"+=420"},"slow",
function(){$("#startDiv").css("background-color","red");});
});
});
/* ]]> */
</script>
<style type="text/css">
#startDiv
{
background-color: #98bf21;
height: 100px;
width: 200px;
padding: 20px;
position: relative;
}
#mainDiv
{
height: 400px;
}
</style>
</head>
<body>
<div id="mainDiv">
<button>Start Animation</button>
<br /><br />
<div id="startDiv">HELLO</div>
</div>
</body>
</html>
jQuery Callback
A callback function is executed after the current effect is 100% finished.
The reason why a callback function might be needed is that JavaScript statements are executed line by line, but with animations, the next line of code can be run even though the animation is not finished. This situation can create errors or at the very least, unwanted side-effects.
To prevent this error or unwanted side-effect, you can create a callback function. The callback function will not be called until after the effect is finished.
We haven't looked at this feature of jQuery functions up till now, but most of the jQuery functions have an optional parameter which is a callback function.
Here is a sample of an effect which is not quite completed when the next line of JavaScript code is executed. This is page jQueryEffectWithoutCallback.html:
Please note that the text which is being hidden is not completely hidden before the alert() text displays:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Callback UnDone</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
});
</script>
</head>
<body>
<div id="mainDiv">
<button>Hide</button>
<p>This is a paragraph with little content.</p>
</div>
</body>
</html>
Now here is a sample of the same effect but with a callback function which prevents the alert() from displaying until the text is completely hidden. This is page jQueryEffectWithCallback.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Callback Done</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000,function(){
alert("The paragraph is now hidden");
});
});
});
</script>
</head>
<body>
<div id="mainDiv">
<button>Hide</button>
<p>This is a paragraph with little content.</p>
</div>
</body>
</html>