4A. Effects
With jQuery, we can add simple effects to our page easily. Effects can use the built-in settings, or provide a customized duration. We can also create custom animations of arbitrary CSS properties.
Here is our html file with 3 headings with h1, h2, and h3 tags, j4_events.html. We also have a style to set the background color of h2 element to salmon:
<html> <head> <meta charset="utf-8" /> <title>jQuery effects</title> </head> <body> <style type="text/css">h2 {background-color:salmon; }</style> <h1>h1 heading</h1> <h2>h2 heading</h2> <h3>h3 heading</h3> <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js""></script> <script type="text/javascript" src="jQuery_effects.js"></script> <script> </script> </body> </html>
Initial picture looks like this.
Our js file, jQuery_events.js:
$( document ).ready(function() { $('h1').click(function(){ $('h2').hide(1000); // milisecond }); });
When the user clicks h1 element, the text with h2 tag will disappear in 1000 milisecond due to the effect of the hide() method.
Note that during the hide(), the width, height, and opacity of h2 element have changed. Also the h3 element has moved up because the h2 element no longer taking a space.
This time, we'll make the h2 heading hide as soon as the html loaded. Then, if we click h1 heading, the h2 heading that was hidden will eventually show up.
$( document ).ready(function() { $('h2').hide() $('h1').click(function(){ $('h2').show(1000); }); });
From:
To:
With the following js, we can toggle the h2 heading between show and hide for a given period by clicking h1 heading:
$( document ).ready(function() { $('h2').hide() $('h1').click(function(){ $('h2').toggle(1000); }); });
We can make h2 heading disappear by reducing its height: slideUp():
$( document ).ready(function() { // $('h2').hide() $('h1').click(function(){ $('h2').slideUp(1000); }); });
The opposite will work the same way by using slideDown():
$( document ).ready(function() { $('h2').hide() $('h1').click(function(){ $('h2').slideDown(1000); }); });
We can toggle between slideUp() and slideDown() using slideToggle():
$( document ).ready(function() { $('h2').hide() $('h1').click(function(){ $('h2').slideToggle(1000); }); });
We can make h2 heading fade out by reducing its opacity: fadeOut():
$( document ).ready(function() { // $('h2').hide() $('h1').click(function(){ $('h2').fadeOut(1000); }); });
We can do the opposite using fadeIn():
$( document ).ready(function() { $('h2').hide() $('h1').click(function(){ $('h2').fadeIn(1000); }); });
fadeToggle() will work the similar way as it does for slideToggle.
We can delay the fadeToggle() by inserting delay(3000) which delays the toggle for 3 seconds:
$( document ).ready(function() { $('h1').click(function(){ $('h2').delay(3000).fadeToggle(1000); }); });
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization