Events and Effects in JQuery


In several scenarios we would be required to execute a code at document load or a button click on the client side. Lets take a look at how this can be done in JQuery
  • Writing code on Document load :

    $(document).ready(function () { 
       /*Your JQuery code here */
    });

    This code selects the document and when it is ready(ie when the document loads) the code written inside is executed.
  • Writing code on Click :

    $(“#button1”).click(function(){ 
        /*Your JQuery code here */
    });

    Here, “button1” is a button. The code written inside the above block will execute when the “button1” is clicked.

    This code will hide paragraph2 when the page loads and hide paragraph1 on button click

    <html>
     <head>
       <title>jQuery demo</title>
       <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
       <script> 
           $(document).ready(function () {
               $("#paragraph2").hide();
               $("#button1").click(function () {
                   $("#paragraph1").hide();
               });
           }); 
       </script>
     </head>
     <body>
       <button id="button1">Click Me</button>
       <p id="paragraph1">This is a first paragraph</p>
       <p id="paragraph2">This is a second paragraph</p>
     </body>
    </
    html
    >

    This was to hide a paragraph element. Similarly you can try out other effects in JQuery from the functions given below for elements other than paragraph too.
     
  • hide(‘slow') : Slowly hides the element
  • show() : shows a hidden element
  • show('slow') : Shows a hidden element slowly
  • slideUp() : Hides an elements with a sliding motion.
  • toggle() : Toggle an element to display or hide.
  • fadeout()/fadeout(‘slow') : To fade out an elemenr
  • fadeTo("slow",0.25) : Fades the element to a specified opacity. Try changing the value of second parameter

In the next one, we will make a slider control in JQuery.