jQuery Slider Fade Image

Using jQueryUI Slider plugin to control changing the opacity of a photo. View a demo here.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>jQuery Slider Fade Image</title>
		<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?3.1.1/build/cssfonts/fonts-min.css&amp;3.1.1/build/cssreset/reset-min.css" />
		<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/base/jquery-ui.css" type="text/css" rel="Stylesheet" />
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
		<style type="text/css">
			body {
   				margin: 20px;
			}
		</style>
	</head>
	<body>
		<div id="photo">
			<img src="http://farm5.static.flickr.com/4060/4516224096_3d4dbb7ed1_o.jpg" alt="buddy glasses" width="500" height="375" />
		</div>
		<div id="slider"></div>
		<script type="text/javascript">
			/* <![CDATA[ */
			//create a jquery instance with a callback function to be called when the dom is ready 
			$(function(){
			 
				//set the slider width to that of the photo and some margin
				$('#slider').css({
					'width': $('#photo>img').width(),
					'margin-top': '10px',
				}).css;
				
				//create the slider
				$('#slider').slider({
					value:100,
					min:0,
					max:100
				});
				
				//every time the slider moves change the photo's opacity (in 0 seconds)
				$('#slider').bind('slide',function(){
					//divide slider's value by 100, because opacity can be 0 to 1
					$('#photo>img').fadeTo(0,$(this).slider('value')/100);
				});
				
			
			});
			/* ]]> */
		</script>
	</body>
</html>

Links:
- Google jQuery CDN

This entry was posted in Uncategorized. Bookmark the permalink.
  • Ms Bourgeois

    Dear Matt,

    This is awesome, thank you for showing the way. Do you know how I would place an image behind the, uh, “opacitated” image?