Showing posts with label toggle. Show all posts
Showing posts with label toggle. Show all posts

Monday 11 October 2010

jQuery Functions and Toggle

Below are a few examples of how to create functions in jQuery. Th real beauty lies in the fact that you can create your own library of functions in an external file. You should try and make them as flexible as possible.

See demo.

<!DOCTYPE html>
<html lang="en>
<head>
<meta charset="UTF-8">
<title>jQuery Functions</title>
<style type="text/css">
body
{
font-family:Sans-serif;
}
.myToggleClass
{
background:#FF0000;
font-size:2em;
color:#FFFFFF;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script>
/* Functions are declared here */
$.fn.firstWithoutParameters = function()
{
alert('Without parameters');
}
$.fn.secondWithParameters = function(param)
{
alert('With parameter of '+param);
}
$.fn.grow = function()
{
return $(this).css('font-size','2em');
}
$.fn.growSlowly = function()
{
return $(this).animate(
{
fontSize:'2em'
}, 1500 );
}
$.fn.doTheToggle = function()
{
return $(this).toggleClass('myToggleClass');
}

/* Functions are called here */
$(document).ready(function()
{
$('#first').click(function()
{
$(this).firstWithoutParameters();
});
$('#second').click(function()
{
$(this).secondWithParameters('Jimmy');
});
$('#third').click(function()
{
$(this).grow();
});
$('#fourth').click(function()
{
$(this).growSlowly();
});
$('#fifth').click(function()
{
$(this).doTheToggle();
});
});
</script>
</head>
<body>
<p id="first">first</p>
<p id="second">second</p>
<p id="third">third</p>
<p id="fourth">fourth</p>
<p id="fifth">fifth</p>
</body>
</html>