Anda di halaman 1dari 13

jQuery Tutorial

This tutorials is in beta version. What is jQuery? jQuery is the light weight javascript library to work with html elements in the browser. As per jQuery.com, it is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

When I used it for the first time, I was amazed to see how powerful and beautiful it is. The small amount of well written code can do a lot of work that need hours of time and skill to write JavaScript ourselves. This tutorials gives some frequently used examples of how jQuery works with demo and sample code.
jQuery is so powerful and robust that Microsoft has decided to ship it with Visual Studio making it compatible for asp hosting development. According to ScottGu of Micorosoft, "I'm excited today to announce that Microsoft will be shipping jQuery with Visual Studio going forward." (Read the complete article here). Needless to say that jQuery works with latest version of most of the advanced browser like IE, FireFox, Chrome, Safari, Opera. If you download the hotfix (http://code.msdn.microsoft.com/KB958502), your current Visual Studio 2008 will also support jQuery IntelliSense (Read IntelliSense for jQuery).

To start working with jQuery, you need to download the code library from jQuery.com website. jQuery code library is available in several flavour like pack, minified, documentation etc (current url of download is http://code.google.com/p/jqueryjs/downloads/list?can=1&q=), Download them as per your need. I have downloaded pack version of the code library. After you have downloaded the library (at the time of writing this tutorials, the current version is 1.2.6), you can reference it the way you reference any of the JavaScript code file. eg. <script src="/include/jquery-1.2.6.pack.js" type="text/javascript"> </script> Prerequisite: In order to understand these tutorials, you must have basic understanding about JavaScript and how it works. Lets see frequently used examples of jQuery in following articles. Please see top-left side tutorial menu for rest of the tutorials.

How to do? - Part 1


This tutorials shows how to do some commonly used scenarios like how to select an element, set class, remove class etc.

The first step

All jQuery statement starts with $(dollar) sign. Whenever we are going to write any function for jQuery, we should ensure that it will run after loading the complete document. To do that wrap the jQuery code inside following code block.
// this is the must $(document).ready(function() { // write jQury code block here // ........ })// this is the must

To find out an element

To find out an html element itself, you can use the name of the element such as div, input, table, td etc. Following code will find out all div elements in the page.
// html code <div>Text inside the div element.</div> jQuery code <script> $("div") </script>

To find out an element using id

To find out an html element using id, you can use following code. Notice that the id of the element starts with # (hash). Lets say, we have a div element like this
// html code <div id="idOfTheHtmlElement">Text inside the div element.</div> // jquery code $("#idOfTheHtmlElement")

To find out an element using class

To find out an html element using class name, you can use following code. Notice that the class of the element starts with . (dot).
// html code <div class="className">Text inside the div element.</div> jQuery code <script> $(".className") </script>

Getting and setting html element value

To get and set the value of the form element, use val method. If we want to get the value simply call the val() and if we want to set the value call the val(parameter) like below.
// html code <input type="text" id="jHowDoI1" class="demoBlock" value="Sample Text" /> <input type="button" id="btnGet" value="Get Value" /> <input type="button" id="btnSet" value="Set Value" /> // jQuery Code <script> $(document).ready(function() { $("#btnGet").click(function() { var val = $("#jHowDoI1").val(); alert(val); }) $("#btnSet").click(function() { $("#jHowDoI1").val("Set the value: changed"); })

}) </script>

Check for an element existence

If we want to check for an element existence, we can use if statement along with length of the element like below. In this code block I am using lenght property of the element to check if its length is more than one. It it is, it is assumed that element exists otherwise not (Notice the ! sign in the 2nd click event, that check for not existence). Even if we remove "Element exists" text inside the "jExists" div element it will return true.
// html code <div id="jExists" class="demoBlock" style="display:none;">Element exists</div> <input type="button" id="btnExists" value="Check for the existence of the Element and show"/> <input type="button" id="btnDoesnotExists" value="Check for the existence of the Element"/> // jQuery code <script> $(document).ready(function() { $("#btnExists").click(function() { if ($('#jExists').length) { $('#jExists').show(); } }) $("#btnDoesnotExists").click(function() { if (!$("#jExists1").length) // notice sign of exclamation

alert("Element doesn't exists"); }) }) </script>

Check for a class of an element

To check whether an element has a particular class or not, we can use is(argument) method. In the following block, you may see a slideToggle() function; don't worry about this right now, this will simply toggle display(slide) a particular html element.
// html code <div id="jCExists" class="demoBlock" style="display: none;">Demo Text</div> <input type="button" value="Class Exists" id="btnCExists" /> <input type="button" value="Class Doesn't Exists" id="btnCNExists" /> // jQuery Code <script> $(document).ready(function() { $("#btnCExists").click(function() { if ($("#jCExists").is(".demoBlock")) { $("#jCExists").slideToggle("slow"); } }) $("#btnCNExists").click(function() { if (!$("#jCExists").is(".demoBlockNOT")) { // notice sign of exclamation alert("demoBlock doesn't exists"); } }) }) </script>

How to escape a special character

There might be certain html element id or class that contain some special character in their name or id like ., [ or ] etc. We can use escape character (\\) to ignore them.
// html code <div id="div.EscapeID" class="demoBlock">Text inside div element having id as "div.EscapeClass" </div> <input type="button" id="btn.HideText" value="Hide above text" /> // jQuery block <script> $(document).ready(function() { $("#btn\\.HideText").click(function() {

}) }) </script>

$("#div\\.EscapeID").toggle();

Text inside div element having id as "div.EscapeClass" How to add/remove an attribute in an html element

To add or remove attributes of the html element, we can use attr(name, value) and removeAttr(name) methods respectively.
// html code <input type="text" id="txtAttribute" class="demoBlock" value="Demo text" /> <input type="button" value="Add Attribute: Disable TextBox" id="jbtnDisable" /> <input type="button" value="Remove Attribute: Enable TextBox" id="jbtnEnable" /> // jQuery code <script> $(document).ready(function(){ $("#jbtnDisable").click(function(){ $("#txtAttribute").attr("disabled", "disabled"); }) $("#jbtnEnable").click(function(){ $("#txtAttribute").removeAttr("disabled", "disabled"); }) }) </script>

How to get dropdown text and value

You can get the value of the selected item from the dropdown using val method as described above and to get the text, you can use text() method of the selected item. You can notice in the below code snippet that I have specified jQuery on the click event instead of writing separate function. If your requirement is short you can use inline jQuery too.
<select id="jSelect"> <option value="1">India</option> <option value="2">USA</option> </select> <input type="button" value="Get Value" onclick="alert($('#jSelect').val())"/> <input type="button" value="Get Text Value" onclick="alert($('#jSelect option:selected').text())"/>

How to load another webpage?

If your requirement is to load another page content at a particular section on your page, you can use load() method like below.
// html code <div id="divLoad" class="demoBlock"></div> <p><a id="aLoad" href="javascript:void(0)" title="Load signature page">Load signature Page and Hide this link</a></p> jQuery code <script> $(document).ready(function() { $("#aLoad").click(function() { $("#divLoad").load("/signature.aspx"); $("#aLoad").hide(); }) }) </script>

(Please wait for a while after clicking.)


DotNetFunda.com Signature download Your Name (1st line) Your Phone (2nd Line) How do you related DotNetFunda.com (3rd line, below Logo) Your Page/Profile (4th line) * (eg. The author is my best friend. OR I have written many articles in it.) *

How to do? - Part 2


This tutorials shows how to do some commonly used scenarios like how to add css style sheet, loop through elements of a particular type etc
To add css style with an element

To add the css stylesheet, we can use css method and pass the name and value as the parameter. In the below code, you can see that I have used css method and passed the attribute name and its value as parameter to the element I want to change.

<script> $(document).ready(function() { $("#jbtnChangeStyle").click(function() { $("#jdivAddStyle").css("border", "2px solid #CC3300") $("#jdivAddStyle").css("font-weight", "bold"); }) }) </script> <div id="jdivAddStyle" class="demoBlock">This is the sample class</div> <input type="button" value="Change CSS Style" id="jbtnChangeStyle" />

This is the sample class

Loop through each element

To loop through each elements, we can use each method. Here, you can see that onclick event of the button, I have got the parent element of the li element (ie ul id="jUlCount") and instructing to loop through each li element.
<script> $(document).ready(function() { $("#jbtnLoopLI").click(function() { $("li").each(function() { $(this).css("border", "1px dotted #FF0066"); }); }) }) </script> <ul id="jUlCount"> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> <li>Size</li> </ul> <input type="button" id="jbtnLoopLI" value="Loop through each number list" />

One Two Three Four Five Size

Loop through all elements of a particular type

To loop through all element of a particular type, you can use get() method that returns the array of the elements. After getting the elements, you can loop through the array and get the desired text or inner html contents using innerText or innerHTML.
<script>

$(document).ready(function() { $("#jbtnLoopAll").click(function() { var lis = $("#ulLoop li").get(); var allLIs = []; for (var i = 0; i < lis.length; i++) { allLIs.push(lis[i].innerText); } $("#jspanAdd").text(allLIs.join(" ")); }); }); </script> <ul id="ulLoop"> <li>Ram</li> <li>Mohan</li> <li>Gita</li> <li>Ramanuj</li> </ul> <span id="jspanAdd" class="demoBlock"></span><br /> <input type="button" id="jbtnLoopAll" value="Loop through all elements of a particular type" />

In the above code snippet, you can see that I have get all the li element using "#ulLoop li", where #ulLoop" is the id of the parent element and "li" is the element I want to get. Here, if I want to loop through all "li" element of the page, I can use $ ("li").get() instead of $("#ulLoop li").get(). In this code snippet, you can see that I have used "push" method to add values into the array and "join" method to join all the values of the array.

Ram Mohan Gita Ramanuj

Animation effect using jQuery


jQuery is not only useful for the basic work that we do using JavaScript but also for giving outstanding animation effect. In this tutorials, I will try to show how to use jQuery functions to animate the html elements.
How to show/hide an element

To simply show and hide element, we can use show() and hide() method of the jQuery. There are several parameter that can be passed in these two methods in order to give special effect. These parameters can are:

slow normal fast

Any numeric digit (number of milliseconds to run the animation)

If we do not pass any parameter to these functions, it act instantly. In the 2nd button click event, you can see that I have not passsed any parameter to the hide() function, so it will not animatte while hiding the element. In the click event of last two buttons, I have passed 3000 as parameter so while showing and hidding the animation duration will be 3000 milliseconds.

If we want to toggle display an html element, we can use toggle() method. We can also pass the same parameter that is applicable to show() and hide() methods.
// jQuery code <script> $(document).ready(function() { $("#jbtnShow").click(function() { $("#jShow").show("slow"); }) $("#jbtnHide").click(function() { $("#jShow").hide(); }) //--------------$("#jbtnShowFast").click(function() { $("#jShow").show("fast"); }) $("#jbtnHideNormal").click(function() { $("#jShow").hide("normal"); }) //---------------$("#jbtnShowCount").click(function() { $("#jShow").show(3000); }) $("#jbtnHideCount").click(function() { $("#jShow").hide(3000); }) // ----------------------$("#jbtnToggle").click(function() { $("#jShow").toggle("slow"); }) }) </script> // html code <div id="jShow" class="demoBlock" style="display:none;">This is the hiddent text</div> <input type="button" value="Show Text" id="jbtnShow" /> <input type="button" value="Hide Text" id="jbtnHide" /> | <input type="button" value="Show Fast" id="jbtnShowFast" /> <input type="button" value="Hide Normal" id="jbtnHideNormal" /> | <input type="button" value="Show by animating 3000 milliseconds" id="jbtnShowCount" />

<input type="button" value="Hide by animating 3000 milliseconds" id="jbtnHideCount" /> | <input type="button" value="Click to Toggle display" id="jbtnToggle" />

||| How to slide display an element

If we want to give a slide effect while showing or hiding the element, we can use slideDown() and slideUp() method respectively. We have freedom to pass the same parameter that is applicable to the show() and hide() method described above, even we can specify the animation duration in milliseconds as we have done above. If we want to toggle display with slide effect, we can use sliderToggle() method.
// jQuery code <script> $(document).ready(function() { $("#jbtnSlideDown").click(function() { $("#jdivWelcome").slideDown(); }) $("#jbtnSlideUp").click(function() { $("#jdivWelcome").slideUp("slow"); }) $("#jbtnSlideToggle").click(function() { $("#jdivWelcome").slideToggle(); }) }) </script> // html code <div id="jdivWelcome" class="demoBlock" style="display:none;"> Welcome to DotNetFunda.com. <br /><br /> DotNetFunda.Com is a popular Microsoft technologies related knowledge based website offering articles, tutorials, tips, forums, interview questions, sample projects with source code and other features including online resources, technical jokes, and IT activities around the world. <br /><br /> Please enjoy your visit and learn and/or share knowledge. Thanks. </div> <input type="button" value="Slide Down" id="jbtnSlideDown"/> <input type="button" value="Slide Up" id="jbtnSlideUp"/> <input type="button" value="Slide Toggle" id="jbtnSlideToggle"/>

How to give fade in/out effect

If we want to give fade effect to the html element, we can use fadeIn() and fadeOut() method to show and hide the element respectively with fading effect. We can also use slow, normal, fast and number of milliseconds as parameter to these methods as we had used with show() and hide() method above.

If we do not want to fade an element completely, we can use fadeTo(effect, amount) method and pass effect(slow, normal, fast) and amout (numeric value, where 0 is transparent and 1 is opaque) as parameter.
<script> $(document).ready(function() { $("#btnFadeIn").click(function() { $("#jDivFade").fadeIn(); }) $("#btnFadeOut").click(function() { $("#jDivFade").fadeOut(); }) $("#btnFadeLimited").click(function() { $("#jDivFade").fadeTo("slow", 0.40); })

}) </script>

<div id="jDivFade" class="demoBlock" style="width:300px;height:100px; display:none;text-align:center;">You are intelligent !!!</div> <input type="button" id="btnFadeIn" value="Fade In" /> <input type="button" id="btnFadeOut" value="Fade Out" /> <input type="button" id="btnFadeLimited" value="Fade to Limited amount" />

Animation using jQuery


In addition to give an effect using jQuery, we can also do animation using jQuery.
How to animate html element using its stylesheet properties

If we want to animate the html element using its stylesheet properties, we can use animate method and pass parameter and duration as parameters. In below example, you can see that I am animating "divAnimate1" using animate() method and passsing css stylesheet properties as parameter. In the last I have specified the duration in millisecond that shows that the whole effect should take place in 1500 milliseconds.
<script> $(document).ready(function() { $("#jbtnDiv").click(function() { $("#divAnimate1").animate({ width: "50%", opacity: 0.56, fontSize: "30pt", borderWidth: "5px", marginLeft: "150px", paddingLeft: "200px" }, 1500); })

$("#jbtnReset").click(function() { $("#divAnimate1").animate({ width: "100%", opacity: 1, fontSize: "10pt", borderWidth: "1", marginLeft: "5px", paddingLeft: "" }, 1500); }) }) </script> <div id="divAnimate1" class="demoBlock">Demo text</div> <input type="button" value="Animate the div" id="jbtnDiv" /> <input type="button" value="Reset" id="jbtnReset" />

In the above code snippet, you must have noticed that css stylesheet properties have been specified using camel case (first character in the lower case and first character of each following word should be in upper case) ie. instead of "margin-left", we should use "margin-Left". Demo text How to queue the animation effect

jQuery also facilitate us to animate several css stylesheet property simultaneously using "queue" parameter. If we specify queue as false, the animation we have specified for a particular element will not be queueed and it will run in parallel with another animation effects.
<script> $(document).ready(function() { $("#jbtnQueue").click(function() { $("#jdivQueue").animate({ height: "50px" }, { queue: false, duration: 1500 }) .animate({ color: "red" }, { queue: false, duration: 1500 }) .animate({ borderLeftWidth: "30px" }, { queue: false, duration: 1500 }) .animate({ padding: "20px" }, { queue: false, duration: 1500 }) .animate({ fontSize: "30px" }, { queue: false, duration: 1500 }) .animate({ width: "50%" }, { queue: false, duration: 1500 }); }) $("#jbtnNoQueue").click(function() { $("#jdivNoQueue").animate({ height: "50px" }, 1500) .animate({ color: "red" }, 1500) .animate({ borderLeftWidth: "30px" }, 1500) .animate({ padding: "20px" }, 1500) .animate({ fontSize: "30px" }, 1500) .animate({ width: "50%" }, 1500); }) $("#jbtnAll").click(function() { $("#jbtnQueue").add("#jbtnNoQueue").click(); })

$("#jbtnResetMultiple").click(function() { $("#jdivQueue").css({ height: "", color: "black", borderLeftWidth: "1px", padding: "", fontSize: "10pt", width: "100%" }); $("#jdivNoQueue").css({ height: "", color: "black", borderLeftWidth: "1px", padding: "", fontSize: "10pt", width: "100%" }); $("#jdivAll").css({ height: "", color: "black", borderLeftWidth: "1px", padding: "", fontSize: "10pt", width: "100%" }); $("#jdivAll").toggle("slow"); }) }) </script> <div id="jdivQueue" class="demoBlock">jQuery is cool.</div> <input type="button" value="Animate Simultaneously (not queued)" id="jbtnQueue" /> <div id="jdivNoQueue" class="demoBlock">jQuery is awesome.</div> <input type="button" value="Animate one by one (queued)" id="jbtnNoQueue" /> <div id="jdivAll" class="demoBlock">jQuery is great.</div> <input type="button" value="Animate both at one click" id="jbtnAll" /> <input type="button" value="Reset" id="jbtnResetMultiple" />

(Note: Please click Reset button after following buttons click) Note: This div block will toggle display on every Reset button click. jQuery is great.

jQuery is cool. jQuery is awesome.

Anda mungkin juga menyukai