3. 3
Working with Timeouts and Intervals
Four methods exists which run your code
automatically based on time elements:
â setTimeout() method
âą Executes code ONE TIME ONLY after a specific
amount of time
â clearTimeout() method
âą Cancels setTimeout() before its code executes
â setInterval() method
âą Executes the same code continually after being called
only once
â clearInterval() method
âą Cancels thesetInterval() method call
4. 4
<form action="">
<input type="button" value=âStopâ onclick=âstopIt();" />
</form>
<script>
var objTimer = setTimeout("window.alert(âHi There')",10000);
function stopIt()
{
clearTimeout(objTimer);
}
</script>
setTimeout â one time only
CD
var variable = setTimeout("code", millisecondsToWait);
5. 5
<script>
$(document).ready(function(){
var begin=setInterval('changeBanner()',2000);
var curBanner="cycle1";
});
function changeBanner()
{
if (curBanner == "cycle2")
{
document.images[0].src = "v500tec.gif";
curBanner = "cycle1";
}
else {
document.images[0].src = "showroom.gif";
curBanner = "cycle2";
}
}
</script>
</head>
<body>
<p><img src="v500tec.gif" height="90px" width="700px"
alt="Banner images" /></p>
</body>
</html>
setInterval -continuous
CD
var variable = setInterval("code", millisecondsToRepeat);
7. Introduction
âą Animations and effects add interest to a web page
âą Make elements on a web page appear and
disappear
â With timers can make slideshows, carousels, etc.
âą Fun to create
â Primary goal is usability
âą make sure animations donât detract from that
7
8. Effects
8
Method Description
show() Display selected elements from upper left to lower right
hide() Hide selected elements from lower right to upper left
toggle() Hide or show selected elements
slideDown() Display selected elements with a sliding motion
slideUp() Hide selected elements with a sliding motion
slideToggle Display or Hide selected elements with a sliding motion
fadeIn() Display selected elements by fading them in to opaque
fadeout() Hide selected elements by fading them out to transparent
fadeToggle() Display or Hide selected elements by fading them in or out
fadeTo() Adjust the opacity property of the selected elements to the
opacity set by the second parameter.
NOTE: with this method, the duration parameter is required
CD
9. Effects
âą For all methods except fadeTo(), the primary parameter is the
duration parameter that determines how long the effect will take
â If duration is 5000, the element will be faded out over 5 seconds
â If duration is omitted, the effect occurs immediately â no animation
âą Basic syntax for all methods except fadeTo() is:
â methodName([duration], [callback function])
âą Basic syntax for fadeTo() is:
â methodName(duration, opacity [,callback function])
âą Duration: can be âfastâ, âslowâ or time in milliseconds
âą Opacity: 0 through 1
âą Callback function: called after the method finishes
9
10. Examples
<h1 id=âstartupâ>Temporarily Under Construction</h1>
//fades out after 5 seconds
$(â#startupâ).fadeOut(5000);
//fades out after 5 seconds and slides it back down
$(â#startupâ).fadeOut(5000).slideDown(1000);
10
11. Chaining
âą Allows us to run multiple jQuery methods (on the
same element) within a single statement
âą Attach one effect to another effect
â Each effect method returns the object it performed the effect on
â Browsers do not have to find the same element(s) more than once
âą To chain an action, you simply append the action to
the previous action
â Code a âdotâ operator after the first method, then code the next method
â Can split up the chain onto multiple lines
âą jQuery throws away extra whitespace and executes the split lines as one
long line of code
11
14. SlideShow
$(document).ready(function() {
// create an array of the slide images
var imageCache = new Array();
imageCache[0] = 'images/casting1.jpg';
imageCache[1] = 'images/casting2.jpg';
imageCache[2] = 'images/catchrelease.jpg';
imageCache[3] = 'images/fish.jpg';
imageCache[4] = 'images/fish.jpg';
var imageTitle = new Array();
imageTitle[0]='Casting on the Upper Kings';
imageTitle[1]='Casting on the Lower Kings';
imageTitle[2]='Catch and Release on the Big Horn';
imageTitle[3]='Catching on the South Fork';
imageTitle[4]='The Lures for Catching';
14
15. SlideShow
// start slide show
var imageCounter = 0;
var nextImage;
var timer = setInterval( function () {
$("#caption").fadeOut(1000);
$("#slide").fadeOut(1000,function() {
imageCounter = (imageCounter + 1) % imageCache.length;
nextImage = imageCache[imageCounter];
nextTitle = imageTitle[imageCounter];
$("#slide").attr("src", nextImage).fadeIn(1000);
$("#caption").text(nextTitle).fadeIn(1000);
}
);
},
3000);
})
15
CD
16. Custom effects - Animations
âą Animations are visual effects that convey the illusion
of motion
â Take a sequence of images, display them one at a
time, at a specific rate of time
âą When an animation runs
â the JE sets a timer for the duration of the animation
â the JE tells the browser to change the CSS property
as specified at that time
â The JE repeatedly executes the code in the timer until
the timer runs out or is stopped
â The visitor sees the illusion of movement
16
CD
17. Custom effects - Animations
âą The animate() function lets you animate any CSS
property that accepts numeric values
â Requires a very good understanding of CSS 3
âą Basic syntax:
animate({properties}[,duration][,callback function]);
Properties map: CSS that goes inside the curly braces
consists of name:value pairs (its CSS)
17
18. Callback functions
âą executed after the current effect is 100% finished
âą JavaScript statements are executed line by line
â with effects, the next line of code can be run even
though the effect is not finished
â Callbacks prevent this
âą Uses
â display captions after photo appears
â make an image stand out
18
20. Custom effects - Animations
âą When animate() function runs, it modifies the
selected element by changing their properties to the
ones in the properties map, over the specified
duration
â To specify properties, in the property map, use camel
casing instead of CSS hypenation
i.e. font-size would be fontSize
â To specify a non-numeric property, enclose the value
in quotes
â For numeric properties, pixels are assumed if omitted
â Cannot animate color
20
21. CSS properties that use numbers
âą borders, margins, padding
âą element-height, min-height,max-height
âą element-width, min-width,max-width
âą font-size
âą bottom, left,top, right
âą background
âą letter spacing, word spacing
âą text indent
âą line height
21
22. Examples
âą Assume this CSS for an H1 element with the ID of
âfaqsâ
#faqs {position: relative; left: -175px; font-size: 75%; opacity: .2}
//animate h1 with no callback
$(â#faqsâ).animate(
{fontSize: â275%â; opacity:1, left:0}, //properties map
//animate h1 with callback to fadein/out elements that follow
$(â#faqsâ).animate(
{fontSize: â275%â; opacity:1, left:0}, //properties map
2000,function(){
$(âfaqsâ).next().fadeIn(1000),fadeout(1000);
});
22
23. Queue Animations
âą When you have multiple animations (single or
chained), they are placed in a queue for that
element
â Each element gets its own queue
â FIFO order
â Easier stopping of an effect or animation
23
CD
25. Queue Animations
âą When chaining animations, callback functions may
not run as expected
â Callback function is designed to run AFTER
animation completes
â User double clicks element which has a callback
function
âą effect goes into queue two times
âą As soon as first effect finishes second one starts â
concurrent with and possibly before callback for first
has finished
25
27. Stopping Animations
âą Stops animation or effect before it finishes
â Useful for slideshows, advertisements
âą Syntax:
$(selector).stop([clearQueue][,jumpToEnd]);
â clearQueue indicates whether also the animation queue should
be cleared or not
âą default is false, only the active animation will be stopped
âą any queued animations will still be performed
â jumpToEnd indicates whether or not to complete the current
animation immediately
âą default is false
27
CD
28. Delaying Animations
âą Delays the start of the next animation in the queue
âą Syntax:
â (element).delay(duration);
âą Example
â $(â#p1â).delay(5000).fadeout(1000);
28
29. Easing
âą Easings determine how an animation is performed
â Can start slowly and pick up speed
âą Two easing types
â Linear â moves animation at uniform speed
â Swing â varies the speed
â Default is swing
âą Other easings exist
â Plug-ins
â jQuery UI
âą Must include script tag to UI CDN
29
30. Easing
âą Syntax for all effects except fadeTo()
â methodName([duration][,easing][,callback])
âą Syntax for fadeTo()
â methodName(duration,opacity,[,easing][,callback])
âą Syntax for basic animate
â animate({properties}[,duration][,easing][,callback])
30
CD
https://matthewlein.com/experiments/easing.html