Click here to Skip to main content
14,690,026 members
Articles » Web Development » Client side scripting » Beginners
Posted 27 Aug 2011


184 bookmarked

jQuery for Beginners

Rate me:
Please Sign up or sign in to vote.
4.81/5 (81 votes)
11 Nov 2013CPOL
This article helps you to understand the JQuery with examples.

Image 1


jQuery is a JavaScript library which has a wide range of actions such as event handling, animation, HTML document traversing, and AJAX interaction for web development. jQuery simplifies JavaScript programming.

$(document).ready Method

The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics are not loaded yet.

$(document).ready(function() {
    alert("document is ready");


jQuery provides a simple way to select single element or group of elements. You can access element by type (div, span, p), id, CSS class and attribute, etc. I have explained the basic selectors here. You can find some other selectors in the attached project with examples.

jQuery Example Code Description
$('element') $('blockquote').css('color','red'); It selects all elements with the given tag name. In this example, it will return all <blockquote> elements in the document.
$('#id') $('#item1').css('color','red'); It selects single element with the given id. If more than one element has been assigned the same id, first match result will be returned.
$('.class') $('.myCss').css('color','red'); It selects all the elements with given class.

Sliding Effect

jQuery provides three methods to show or hide elements in sliding behavior.

  1. SlideDown(speed, callback): This method gradually increases the height of the elements, from hidden to visible.
  2. SlideUp(speed, callback): This method gradually decreases the height of the elements, from visible to hidden.
  3. SlideToggle(speed, callback): This method toggles between SildeUp() and SlideDown() for selected elements.

All three methods has "Speed" and "callback" parameters. The Speed parameter can have the following values:

  • slow
  • normal
  • fast
  • milliseconds, e.g., 100, 500, 1000, etc.

The callback parameter is the name of a function that executes after the function completes.

Sliding Example

Image 2

According to your website design, decide collapsible Area and element on which you will handle Slide behavior. In this example, I created Box using DIVs and choose DIV having id “contentArea” for sliding.

<div class="box" style="width: 400px">
    <div class="title">
        Collapse Box (<a id="lnkCollapse" 

                  href="#" style="color: White; font-size: 12px;
            text-decoration: none;">Click Here</a>)
    <div id="contentArea" class="content">
        <div align="right"><a id="lnkClose" 

                 href="#" style="font-size: 10px;">
        Your text will be here


Register click event of the HTML element and call SlideToggle and SlidUp method for the “contentArea”. More details of this example are available in the attached project.

$(document).ready(function () {

    $("#lnkCollapse").click(function () {

    $("#lnkClose").click(function () {

Fade Effect

jQuery also provides four methods to gradually change the opacity of the selected element using Fade effect.

  • fadeTo(speed, opacity, callback): This method changes the opacity of selected elements to specified opacity.
  • fadeIn(speed, callback): This method gradually increases the opacity of the elements, from hidden to visible.
  • fadeOut(speed, callback): This method gradually decreases the opacity of the elements, from visible to hidden.
  • fadeToggle(speed, callback): This method toggles between FadeIn() and FadeOut() for selected elements.

Image 3

In this example, I will set the opacity of the image on hover. Add images in to the DIV and assign id “fadeExp1” to div.

<div id="fadeExp1">
    <img src="Images/b1.jpg" width="100px" height="100px" />
    <img src="Images/b2.jpg" width="100px" height="100px" />
    <img src="Images/b3.jpg" width="100px" height="100px" />

In ready() function, set the default opacity of all images using $(“#fadeExp1 img”).fadeTo(0, 0.3); statement. Then register Hover event on each image and provide two functions in it, one for mouse over and one for mouse out and set the opacity of element there. See example code below:

$(document).ready(function () {

    $("#fadeExp1 img").fadeTo(0, 0.3);

    $("#fadeExp1 img").hover(function () {
        $(this).fadeTo("slow", 1.0);
        function () {$(this).fadeTo("slow", 0.3);

Animation Effect

jQuery also provides an easy way to animate element. The syntax of the animate method is .animate( properties, [duration], [easing], [complete]).

  • properties: A map of CSS properties, which changes during animation
  • duration: String or number to determine the duration of the animation
  • easing: The name of easing function to use for the transition
  • complete: A function to call on the complete of animation

Image 4

A very cool and simple example for the icons list in your website, simply register hover event on the image. On mover over, set top=-15 and on mouse out set top=0 again.

$("#divSocial a img").hover(
    function () {
                    $(this).animate({ top: "-15" });
    function () {
                    $(this).animate({ top: "0" });

Don’t forget to set the relative position of the image.

#divSocial a img
    position: relative;
    border: none;

Create Tab Control

Image 5

You can easily create a sophisticated tab control using jQuery. Let's start learning how can we quickly create a tab control. Create Tab Header or tabs by assigning IDs to each element as I assigned “tab1”, “tab2” and “tab3”. Set first element as selected by assigning CSS class “selectTabHeader”.

Now create Tab content area. I created separate divs for each tab content. Assign same id “tab-data” to content div as I assigned in given example and also assign dummy CSS class to div having same id as parent tab button contains. I assign CSS class “tab1”, “tab2” and “tab3”.

<div id="tabArea">
    <div id="tabHeader">
        <a id="tab1" class="tab selectTabHeader">Tab 1 </a>
        <a id="tab2" class="tab">Tab 2</a>
        <a id="tab3" class="tab">Tab 3 </a>
    <div id="tabData">
        <div id="tab-data" class="tab1 selectedTab">
            tab 1 data
        <div id="tab-data" class="tab2">
                tab 2 data
        <div id="tab-data" class="tab3">
            tab 3 data

By default, hide all tab content area using CSS and display only selected tab contents.

    display: none;
    display: block;
    color: black;
    background: white;
    height: 400px;
    padding: 5px;

Register click event of all header buttons. On the click of element, remove “selectTabHeader” CSS class from last selected element and then assign selected CSS class to clicked element by using command.


Use the same technique for content area. Remove CSS class “selectedTab” from last selected tab and assign this class to content area of selected element.

Simply get the id of click element. Suppose user clicked on “tab2”. Remove the class "selectedTab" of last selected content using command. 

var v =;

$('.' + v).addClass('selectedTab');

Now you have to show the content area of the selected element. Simply find the HTML element which has the CSS class same as the id of selected element. Suppose “tab2", assign "selectedTab" CSS class to that element.  

$(document).ready(function () {

    $('#tabHeader a').click(function () {

            // Set header

            // Show Actual area
            var v =;


            $('.' + v).addClass('selectedTab');

Create Carousel

Image 6

After reading previous topics, now you have enough knowledge to create advance UI controls. In this example, I will explain how to create a Carousel, which will change the images in sliding style. User can also change image using navigation buttons and also he can directly go to image using number options. Write the HTML as given below:

<div class="advanceCarousel">
    <div class="carouselWindow">
        <div class="imageReel">
            <div class="image">
                <a href="#" target="_blank" >
                    <img src="images/b1.jpg" />
                <div class="description">
                    Here is a description of first image
            <div class="image">
                <a href="#" target="_blank" >
                    <img src="images/b2.jpg" />
                <div class="description">
                    Description of second image
            <div class="image">
                <a href="#" target="_blank" >
                    <img src="images/b3.jpg" />
                <div class="description">
                    I am going to write 3rd image.
    <div class="paggingBar">
        <div style="float: left;">
            <a class="aNav" href="javascript:RotatePrevious();"><<</a>
        <div style="float: right;">
            <a class="aNav" href="javascript:RotateNext();">>></a>
        <div class="paging">
            <a href="#" rel="1">1</a>
            <a href="#" rel="2">2</a>
            <a href="#" rel="3">3</a>

In the ready function, assign active CSS class to the first element. After that, determine the width of the total reel. Get the width of the window and then get the total number of images. Multiply the Width by size, you will get the total width of the reel. Then assign this width to the imageReel CSS class.

$(".paging a:first").addClass("active");

//Get size of images, number of images, Determine the size of the image reel.
var imageWidth = $(".carouselWindow").width();
var imageSum = $(".imageReel .image img").size();
var imageReelWidth = imageWidth * imageSum;

//Adjust the image reel to its new size
$(".imageReel").css({ 'width': imageReelWidth });

Image rotating method also has very simple logic. You just need to determine the left position of the Image reel. So get the index of the active image. Multiply it with image width to determine to slide distance. Then animate the left CSS property.

rotate = function () {
    var triggerID = $active.attr("rel") - 1; 		//Get number of times to slide

    var image_reelPosition = triggerID * imageWidth; 	//Determines the distance 
						//the image reel needs to slide

    $(".paging a").removeClass('active'); 		//Remove all active class

    //Slider Animation
        left: -image_reelPosition
    }, 500);

startRotation() is a method which kicks off the rotation. It selects the next active element after some interval and calls rotate() to display this active image.

function startRotation() {

    play = setInterval(function () {

        $active = $('.paging').next();

        if ($active.length == 0) {
            $active = $('.paging a:first'); //go back to first

        rotate();  //Trigger the paging and slider function
    }, 7000); //Timer speed in milliseconds 

Register click event on the page number, when user will click, select it as active element and immediately slide to that image.  

$(".paging a").click(function () {
    $active = $(this); //Activate the clicked paging

    //Reset Timer

   return false; //Prevent browser jump to link anchor

Slide next and previous functionality is also very simple. Get current element and find its next or previous where you want to navigate and after selecting call RoatateImmediate() method.

function RotateNext() {
    var next = $('.paging').next();
    if (next.length > 0) {
        $active = next;

function RotatePrevious() {
    var next = $('.paging').prev();
    if (next.length > 0) {
        $active = next;


  • 28th August, 2011: Initial post.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Shakeel Iqbal
Software Developer (Senior) TEO
Pakistan Pakistan
Passion and positive dedication is essential part of success. I believe on hardworking and sharing knowledge with others. I always try to be a better than I am and think positive for positive result.

My Blogs

My Linked-In Profile

Comments and Discussions

GeneralMy vote of 5 Pin
Rakesh Kohale14-Apr-16 1:42
professionalRakesh Kohale14-Apr-16 1:42 
QuestionGood article Pin
Rakesh Kohale14-Apr-16 1:42
professionalRakesh Kohale14-Apr-16 1:42 
GeneralMy vote of 1 Pin
Manan Garg9-Oct-14 2:52
MemberManan Garg9-Oct-14 2:52 
GeneralGreat Work... Thanks Pin
Sasika Miyuran16-Jul-14 9:40
professionalSasika Miyuran16-Jul-14 9:40 
GeneralMy vote of 1 Pin
Jignesh Khant8-May-14 23:58
MemberJignesh Khant8-May-14 23:58 
GeneralMy vote of 5 Pin
Gun Gun Febrianza12-Apr-14 16:20
Member Gun Gun Febrianza12-Apr-14 16:20 
GeneralRe: My vote of 5 Pin
Shakeel Iqbal12-Apr-14 21:54
MemberShakeel Iqbal12-Apr-14 21:54 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun9-Jan-14 18:50
MemberHumayun Kabir Mamun9-Jan-14 18:50 
Generalvote 5 Pin
N.Banukobhan12-Dec-13 23:40
MemberN.Banukobhan12-Dec-13 23:40 
QuestionFantastic Pin
WuRunZhe13-Nov-13 15:21
MemberWuRunZhe13-Nov-13 15:21 
GeneralMy vote of 5 Pin
Waseem-Malik19-Sep-13 4:30
professionalWaseem-Malik19-Sep-13 4:30 
QuestionAdvance Carousel is not working properly ... Pin
prem parihar8-Apr-13 19:20
Memberprem parihar8-Apr-13 19:20 
Questionhow to run this.. Pin
Member 965416110-Dec-12 22:59
MemberMember 965416110-Dec-12 22:59 
GeneralMy vote of 5 Pin
shakil4u26-Nov-12 4:56
Membershakil4u26-Nov-12 4:56 
GeneralMy vote of 5 Pin
prem parihar17-Nov-12 6:22
Memberprem parihar17-Nov-12 6:22 
GeneralMy vote of 5 Pin
csharpbd13-Nov-12 20:44
professionalcsharpbd13-Nov-12 20:44 
GeneralMy vote of 5 Pin
vaibhav mahajan8-Nov-12 20:42
Membervaibhav mahajan8-Nov-12 20:42 
GeneralMy vote of 5 Pin
Member 898400210-Sep-12 1:02
MemberMember 898400210-Sep-12 1:02 
Generalthank you,bro.. its a great help for me Pin
Kamaljit Mahanto22-Aug-12 4:33
MemberKamaljit Mahanto22-Aug-12 4:33 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey29-Jun-12 5:05
professionalManoj Kumar Choubey29-Jun-12 5:05 
GeneralMy vote of 5 Pin
Reza Ahmadi18-Jun-12 10:40
MemberReza Ahmadi18-Jun-12 10:40 
Questionnice Pin
ritesh020120-Dec-11 2:42
Memberritesh020120-Dec-11 2:42 
Questionnice Pin
BillW3316-Sep-11 10:39
professionalBillW3316-Sep-11 10:39 
GeneralMy vote of 5 Pin
BrianBissell1-Sep-11 11:02
MemberBrianBissell1-Sep-11 11:02 
GeneralMy vote of 4 Pin
Brian Herbert30-Aug-11 5:40
MemberBrian Herbert30-Aug-11 5:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.