Monday, May 2, 2011

jQuery Basics

I wanted to learn jquery for long time, but kept postponing since it is possible to do most of the normal client functions that I do (like validation, showing alerts, pop up etc) using classic javascript itself. But when it comes to complex functions (like fading out/fading in controls or animation), doing it in javascript becomes difficult. And you have to worry about browser compatability too.

Thats the reason why I started to learn jQuery.... and it was pretty easy and really helpful.

Given below are the steps that I followed in creating a simple example.

1) The first thing to do is to download the jquery Js file from (When I downloaded the file the version was "jquery-1.5.1.min.js")

2) Create an html file and include the download js file in the html file

<script src="Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>

Ok... now we are ready to start using jQuery. Elements are accessed in jQuery as $("#controlId")... the same code in javascript would be "document.getElementById("controlId").

3) Let us set a value in textbox using jQuery

a) First Create a textbox and button control in html as given below

<input type="text" id="txtBox1" value="test" />

<input type="button" value="Set Value" onclick="SetValue();" />

b) Set text "Hello World" in text box using jQuery as given below

function SetValue() {
$("#txtBox1").val("Hello world")

Wasn't that easy. Let us look at some other simple functions of jQuery.

Fade Out

function FadeOut() {

Fade In

function FadeIn() {

Let us now see how to animate a div

Include a div element in html
<div id="divAnimate" class="ui-dialog" style="display:none;border:1px solid gray;width:0px;">
<div class="ui-widget-header" style="width:300px;">
Just a box

Include 2 buttons to invoke 'hide' and 'display' animations

<div class="codeBlock">
<input type="button" value="Animate-Display" onclick="Animate_Display();" />
<input type="button" value="Animate-Hide" onclick="Animate_Hide();" />
</div >

Include script for "hide" and "display" functions

function Animate_Display() {
$("#divAnimate").css({ "display": "block", "overflow": "auto" });
$("#divAnimate").animate({ width: "300px",height:"300px" }, 1000);
function Animate_Hide() {
$("#divAnimate").animate({ width: "0px", height: "0px" }, 1000, function() {
function Animation_Complete() {
$("#divAnimate").css({ "display": "none", "overflow": "auto" });

No comments: