Marketplace for Content, Tests and Assessment
 
 
Home > Programming / tutorials > Jquery Tutorial With Javascript

Jquery Tutorial With Javascript

January 27th, 2010 Vinay Leave a comment Go to comments

Introduction

Today JQuery is a buzz in every tinsel town. From the day web sites began coming into the world wide web space, developers are trying hard to please their users. Javascript arrived and it added spices in it. Developers began playing with javascript and created tens of thousand useful things for the users and made things interactive. But this comes with a price. Creating and maintaining javascript application requires a lot of patience and a lot of trial and error. On the top of this if we wanted to  write  a piece of javascript that creates effects and animation, we had make sure every thing is working and sometimes struggling with table, div, span bla  bla bla. JQuery came into the picture like life savior and it made our life very much comfortable. Just have a look at the piece of code written below :-

<html>
<head>
<script src=”jquery-1.3.2.js”></script>
<script>
$(document).ready(function(){
$(”p”).click(function(){
$(this).hide()
})
})
</script>
</head>
<body>
<p>You click on me, I will come after “Introduction”</p>
</body>
</html>

You can download code examples used in this tutorial here jquery code examples

This is just beginning and it can bring a lot of fun on your website. Imagination is the only limit.

Objective

(1)   What is JQuery

(2)   Why use JQuery

(3)   How JQuery works

(4)   Creating effects with JQuery

(5)   JQuery with server side technologies (ASP.net)

(6)   Future of JQuery

What is JQuery

JQuery has only one motto. Write less, do more. In simple words JQuery is a lightweight javascript library. Library, because the core lies in one library and that is nothing but a javascript file. Current version of JQuery is 1.3.2 and you can either download it from http://docs.jquery.com/Downloading_jQuery or you can find it in my sample zip file that comes with this tutorial. Believe me it is very much to learn and quickly you can integrate it with your web applications. It simplifies javascript greatly. You can create a very dynamic web application by just using HTML & JQuery (since it is part of Javascript, understand javascript as well) alone.

Why use JQuery

(1)   You want javascript to show the effects and animation that has proven track record, so that you do not have to burn your mid night oil for bug fixes.
(2)   If you appreciate, how social networking websites give the power of interactions among users.
(3)   Quickly development with rich UI’s.
(4)   Very easy to learn and integrate.
(5)   You want to call some service and fill some data on some parameters and absolutely without page refresh.
(6)   And last but not the least you want to show that you also know JQuery and your CV can accommodate this. Believe me, you just google around and see job floods that requires JQuery knowledge.

At the end of this tutorial you will get to know Jquery and how to use it effectively.

How JQuery works

As I said earlier, JQuery is very easy to learn and integrate. Just include the library and we go. We will call our example again.

<html>
<head>
<script src=”jquery-1.3.2.js”></script>

<script>
$(document).ready(function(){
$(”p”).click(function(){
$(this).hide()
})
})
</script>
</head>
<body>
<p>You click on me, I will come after “Introduction”</p>
</body>
</html>

Examine the bold text under <script>. We have just download it from  (http://docs.jquery.com/Downloading_jQueryor you can download it from this tutorial. Then we include a <p> tag in the body. Now the game begins. We want <p> text to disappear. So the moment we click the text inside <p>, it gets disappeared. Included javascript file has tons of methods written that takes our hard work off. This code will simply make all the <p> text disappear. Let’s examine the above code line by line.

(1)   <script src=”jquery-1.3.2.js”></script>
// Include JQuery library
(2)   <script>
(3)   $(document).ready(function(){
// The basic syntax to use JQuery is
// $ (selector).action()
(4)   $(”p”).click(function(){
// We want to make all <p> text disappear
// so we start with $
// here selector is p, so $(“p”)
// since we want this to happen on click, so click will be our action
// so here is complete script
// $(“p”).click(function) : since it is a function, so used (function). Nothing fancy.
(5)    $(this).hide()
// above code follows the same syntax except it calls the JQuery hide() method.
// now our script is ready to hide all the <p> text.
})
})
</script>

This is just a tip of iceberg. A lot of more will come in our way. Below, we will examine the basic syntax those are capable to create powerful stuff.

$(”selector”) selects all <selector> elements.
$(”selectorp#id”) selects the <selector> element with assigned id.

We will examine a piece of code that will give more insight on it.

<html>
<head>
<script src=”jquery-1.3.2.js”></script>
<script>
$(document).ready(function(){
$(”button#btnHide”).click(function(){
$(”p#txt”).hide()
})
$(”button#btnShow”).click(function(){
$(”p#txt”).show()
})
})
</script>
</head>
<body>
<p>This is a JQuery demo.</p>
<button>Hide the text</button>
<button>Show the text</button>
</p>
</body>
</html>

In the above example, we have taken two html buttons and a text inside <p>. btnHide button suppose to hide the text “This is a JQuery demo”, while btnShow is suppose to show the text. Please follow my above instructions, how to write these events.

$(“selector#id”).action

Here “selector” is button and its id can be either btnHide or btnShow. Action is click. So here is our script.
So $(“button#btnHide”).click(function) : Since this is suppose to hide the <p> text, so we called the JQuery hide() method and vice versa to show().

Some of you, who have programmed in XML will say, it is following XPath root and so it is. JQuery uses XPath style selectors to select element with given attributes.

Let’s explore JQuery further. Now we want our <p> text in above example to load <p> text in blue but when again it is shown by btnShow button, we want it to come in red color.

$(”button#btnShow”).click(function(){
$(”p#txt”).show();
$(”p#txt”).css(”color”,”red”)
})
<p style=”color:blue;”>This is a JQuery demo.</p>
We just changed our requirement at 2 places. First we changed the color of <p> text as blue and second, we gave the color as red in btnShow click action.

Create effects using JQuery

Further we can create the effects using other parameters of show() & hide() method.

<html>
<head>
<script src=”jquery-1.3.2.js”></script>
<script>
$(document).ready(function(){
$(”button#btnHide1″).click(function(){
$(”p#txt1″).hide(1000)
})
$(”button#btnShow1″).click(function(){
$(”p#txt1″).show(1000);
})
})
</script>
</head>
<body>
<p style=”color:white;background-color:blue;”>This is a JQuery demo.This is a JQuery demo.This is a JQuery demo.<br>
This is a JQuery demo.This is a JQuery demo.This is a JQuery demo.<br>
This is a JQuery demo.This is a JQuery demo.This is a JQuery demo.<br>
This is a JQuery demo.This is a JQuery demo.This is a JQuery demo.<br>
This is a JQuery demo.This is a JQuery demo.This is a JQuery demo.<br>
This is a JQuery demo.This is a JQuery demo.This is a JQuery demo.<br>
This is a JQuery demo.This is a JQuery demo.This is a JQuery demo.<br>
This is a JQuery demo.This is a JQuery demo.This is a JQuery demo.<br>
</p>
<button>Hide the text</button>
<button>Show the text</button>
</body>
</html>

hide() and show() JQuery methods additionally take input parameters as well. Suppose you are creating a web application and on the registration page, you have a “Terms and Condition” link, which is suppose to show the “Terms and condition” of your website. Server side code will refresh the page and it will show the “Terms and condition” (assuming it should come under a panel). Using JQuery will make this more interactive. Just run the above code in your browser and you can see the effects. When user clicks on “Hide the text” button, it slowly hides the text under <p>, which looks so good. After all UI is all about this. It simply executes the “btnHide” click action and hide the text inside <p> with a delay of 1000 milliseconds, which gives the user rich UI experience.

I just let you to explore all the rich experience JQuery can offer to you.

JQuery with server side technologies using ASP.NET

Since JQuery is nothing but a javascript library, so you can use it with any server side technology like ASP.NET, PHP, Ruby on rails etc. and as said earlier very easy to integrate as well.

For an example, our previous JQuery example shows and hides the “Terms and Condition” and prerequisite was “Terms and Condition” text should be available within <p> and </p>. Suppose “Terms and Condition” text is very long and you want to call some service and populate the test within <p> and </p>.
// Javascript Function
$.post(”/ServiceURL/Method”, { parameter if any}, function(terms){
// Populate your “Terms and Condition” within <p> and </p>
}

In the above example we make the request thorough post method and we get our terms and condition in a string. Alternatively we can use the get method to call the service.

Let’s take a very realistic example of JQuery with sever side script. Here we are going to create a webservice in ASP.NET 3.5. We will take “Northwind” database (comes free with Sql Server 2000 & can be downloaded from Microsoft website, if you are using Sql Server 2005 or later). Since this is not a tutorial on creating webservice in asp.net 3.5, so I will not go into deep as what is webservice and how to create a webservice in asp.net 3.5. Those who are novice with such terms, can follow the link http://en.wikipedia.org/wiki/Web_service . Secondly, we will write a [WebMethod] that returns all the categories in the “NorthWind” database. We will send the output in JSON format. Those who are not familiar with JSON can reach my article http://www.skill-guru.com/blog/2010/01/09/json-javascript-tutorial/ . I have commented the web service, so that it can be easily digested. Ok, enough discussion; back to code.

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Services;

namespace JQueryService
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
}
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<Categories> GetCategories()
{
string nwConn = System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
var catList = new List<Categories>();
using (SqlConnection conn = new SqlConnection(nwConn))
{
const string sql = @”Select CategoryName, Description from Categories”;
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataReader dr = cmd.ExecuteReader(
CommandBehavior.CloseConnection);
if (dr != null)
while (dr.Read())
{
var category = new Categories
{
CategoryName = dr.GetString(0),
Description = dr.GetString(1),
};

catList.Add(category);
}
return catList;
}
}
}
}
}

public class Categories
{
public string CategoryName { get; set; }
public string Description { get; set; }
}

Above web service creates a Categories class and declares two attributes, “CategoryName” & “Description”. These are attributes in which we are interested to display.

<%@ Page Language=”C#” AutoEventWireup=”true” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1″ runat=”server”>
<title>JQuery in action : Call GetCategories [WebMethod] and lists category name and its description</title>
<script src=”jquery-1.3.2.js” type=”text/javascript”></script>
<script type=”text/javascript”>
$(document).ready(function() {
$.ajax({
type: “POST”,
url: “Service1.asmx/GetCategories”,
data: “{}”,
contentType: “application/json; charset=utf-8″,
dataType: “json”,
success: function(list) {
$(”#output”).append(”<ul id=’star’></ul>”);
for (i = 0; i < list.d.length; i++) {
$(”#star”).append(”<li>” + list.d[i].CategoryName
+ ” : ” + list.d[i].Description + “</li>”);
}
},
error: function(e) {
$(”#output”).html(”Oops! broken link.”);
}
});
});
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<h3>JQuery in action : Call GetCategories [WebMethod] and lists category name and its description</h3>
<div id=”output”>
</div>
</form>
</body>

Above asp.net form calls our web service and takes output in JSON format. Once we get the results in JSON, we can now easily loop through it and bind the result sets into <div> tag.

JQueryOutPut3-300x187

You should get the output as the same screen above. Same way you can create the service in your favorite server side script and get a call from UI. You can download all the codes described from the tutorial, that I have kept in a zip file.

Future of JQuery

JQuery has  lots of potentials and power to make your application very interactive, fast & rich in experience. JQuery team went ahead and made ready made UI’s that can easily be integrated in a seamless manner. Just plug and play. In their words “ jQuery UI provides abstractions for low-level interaction and animation, advanced effects and high-level, themeable widgets, built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.”, and so it is. JQuery UI offers ready made calendars, widgets, drag and drop features and a lot more to offer and all are customizable as per your need. Follow the link http://www.jqueryui.com/, what JQuery UI has to offer. Every browser is giving the support of JQuery UI’s and I am sure once you start using JQuery, you will find every reason to code JQuery in your web applications.

You can download code examples used in this tutorial here jquery code examples

Get Adobe Flash playerPlugin by wpburn.com wordpress themes