Friday, 29 July 2011

Jquery Series – Basic effects and events

In this tutorial series I will be writing about Jquery, the Javascript library written to simplify the changing of a web page on the fly. In this post I will provide example code for basic jQuery functions, click events, slide effects and fade effects. Firstly, the code below is the initial HTML I have used for this example. It is a red square with the width and height at 250 pixels.

<!DOCTYPE html>
<head>
<title>jJuery functions, click events and fade effects </title>
<script src="jquery-1.6.2.min.js"></script>

<style>
 #container{
  width:250px;
  height:250px;
  background-color:red;
 }
</style> 
</head>
<body>
<div id="container"></div>
</body>
</html>

The first example adds the click event to the ‘container’ div. When the div is clicked the background colour of the div will change to blue. I have used the shorten jquery function/wrapper ‘$()’ instead of writing ‘jQuery()’. Jquery selects HTML elements the same way as CSS selectors so it’s easy to learn.

<script>
 $(document).ready(function(){
  $("#container").click(function(){
   $("#container").css({"background-color":"blue"});
  });
 });
</script> 

The second example uses the slideUp() method to change the height property to 0. When the div is clicked the height of the div will slide up until the height is 0 and then hide the element. There is also the slideDown() method that does the opposite. It will change the height property from 0 to whatever the height specified in the css. Another method is the slideToggle() which slides up or down according to the current height of the element.

<script>  
 $(document).ready(function(){
  $("#container").click(function(){
   $("#container").slideDown();
  });
 });
</script>

The last example will fade the elements. Just like the previous example the methods are very similar: fadeIn(), fadeOut(), and fadeToggle(). When the div is clicked it will fade from opaque to transparent. You can also control the time of the fade by putting in milliseconds the number inside the parentheses.

<script> 
 $(document).ready(function(){
  $("#container").click(function(){
   $("#container").fadeOut();
  });
 });
</script> 

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP