jQuery fadeOut upon click

This programming snippet is from the themeforest.net video series “jQuery for beginners” which I watched and practiced spring 2009. I do not mean to steal from them, but just post how I performed their tutorials for my own later reference and perhaps save someone else the time of watching the videos.

I post these old code snippets for a few reasons. One is to demonstrate my programming learning, experience, and progression. Another reason is to make sure my code and solutions are indexed by search engines, so that other beginning programmers may get help if they need it. Finally, it is just nice for me to have my own code snippet library, to easily find snippets that I remember doing a particular job but I cannot always recall where I found it.

Challenge: Download jQuery script from jQuery.com (get the production version, not the development version). Link to the jQuery script file form your index.html. Write simple animation script to fade out a div element when a link is clicked.

Solution:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Beginner's jQuery</title>
	<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
	<script type="text/javascript" src="script.js"></script>
	<style type="text/css">
		#box {
			background: blue;
			width: 200px;
			height: 100px;
		}
	</style>
</head>
<body>
	<div id="box"></div>
	<a href="#">Click me</a>
</body>
</html>

Here is the script to animate the box fading away:

// start a generic function
$(function() {
	// when link is clicked, start a sub-function
	$('a').click(function() {
		// make the element with id='box' fade out over 5 seconds
		$('#box').fadeOut(5000);
	});
});

Note that you can also use fadeOut(’slow’); or ‘fast’ without specifying actual milliseconds.

  • Share/Bookmark




Leave a Reply