Thursday, November 12, 2009

Have fun with jQuery - Tutorial 2

As we discussed earlier, jQuery is a powerful javascript API on developing web applications. Here lets consider, how jQuery actions can be applied on specified elements.

Suppose you have got two buttons which we call ButtonA and ButtonB,


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

<script type="text/javascript">
$(document).ready(function(){
$("#btnA").click(function(event){
alert("Clicked ButtonA...!!!");
});
$("#btnB").click(function(event){
alert("Clicked ButtonB...!!!")
});
});

</script>
<body>
<p>
<input id="btnA" value="ButtonA" type="button">
<input id="btnB" value="ButtonB" type="button">
</p>
</body>

When you click on Buttons, it will pop up two different alert boxes as we defined in script.



That is how we define actions for a given element. To make it easy to understand, I displayed just popping up an alert box. It is useful in various applications.

Now lets see, how jQuery can be used with styling elements. First you better create some style classes like I have mentioned below.

<style type="text/css">
label.test { font-style: italic; }
label.test2 { color:#FF0033; }
</style>

Very easily you can apply your style class to an element using ELEMENT.addClass("CLASSNAME") function. If you want to remove it, you can call ELEMENT.removeClass("CLASSNAME") funciton. jQuery call for applying or removing class will receive the priority.
Example,

<script type="text/javascript" src="jquery.js"> </script>

<script type="text/javascript">
$(document).ready(function(){
$("#myLabel").addClass("test");
});
</script>
</head>
<body>
<h1>
<label id="myLabel">
Testing jQuery
</label>
</h1>
</body>

This will Present,

Now Lets remove an applied class and add another class,

<script type="text/javascript" src="jquery.js"> </script>

<script type="text/javascript">
$(document).ready(function(){
$("#myLabel").removeClass("test");
$("#myLabel").addClass("test2");
});
</script>
</head>
<body>
<h1>
<label class="test" id="myLabel">
Testing jQuery
</label>
</h1>
</body>

Now it will present,

Many more interesting things are coming.....
KIT.....

No comments:

Post a Comment