Click here to Skip to main content
Click here to Skip to main content
Go to top

jQuery for Beginners

, 11 Nov 2013
Rate this:
Please Sign up or sign in to vote.
This article helps you to understand the JQuery with examples.

Introduction

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");
}); 

Selectors

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

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>
    <div id="contentArea" class="content">
        <div align="right"><a id="lnkClose" 
                 href="#" style="font-size: 10px;">
	Close</a></div>
           
        Your text will be here

    </div>
</div>

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 () {
        $("#contentArea").slideToggle("slow");
    });

    $("#lnkClose").click(function () {
        $("#contentArea").slideUp(200);
    });
});

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.

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" />
</div>

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

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

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>
    <div id="tabData">
        <div id="tab-data" class="tab1 selectedTab">
            tab 1 data
        </div>
        <div id="tab-data" class="tab2">
                tab 2 data
        </div>
        <div id="tab-data" class="tab3">
            tab 3 data
        </div>
    </div>
</div>

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

#tab-data
{
    display: none;
}
        
#tab-data.selectedTab
{
    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.

$('.selectTabHeader').removeClass('selectTabHeader');
$(this).addClass('selectTabHeader');

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 = this.id;
$('.selectedTab').removeClass('selectedTab');


$('.' + 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
            $('.selectTabHeader').removeClass('selectTabHeader');
            $(this).addClass('selectTabHeader');

            // Show Actual area
            var v = this.id;

            $('.selectedTab').removeClass('selectedTab');

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

Create Carousel

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

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
    $active.addClass('active');

    //Slider Animation
    $(".imageReel").animate({
        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 a.active').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
    RotateImmediate();

   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 a.active').next();
    if (next.length > 0) {
        $active = next;
        RotateImmediate();
    }
}

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

History

  • 28th August, 2011: Initial post.

License

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

Share

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
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralGreat Work... Thanks PinmemberSasika Miyuran16-Jul-14 8:40 
GeneralMy vote of 1 PinmemberJignesh Khant8-May-14 22:58 
GeneralMy vote of 5 Pinmember Gun Gun Febrianza12-Apr-14 15:20 
GeneralRe: My vote of 5 PinmemberShakeel Iqbal12-Apr-14 20:54 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun9-Jan-14 17:50 
Generalvote 5 PinmemberN.Banukobhan12-Dec-13 22:40 
QuestionFantastic PinmemberWuRunZhe13-Nov-13 14:21 
GeneralMy vote of 5 Pinmemberwaseem-ricky19-Sep-13 3:30 
QuestionAdvance Carousel is not working properly ... Pinmemberprem parihar8-Apr-13 18:20 
Questionhow to run this.. PinmemberMember 965416110-Dec-12 21:59 
GeneralMy vote of 5 Pinmembershakil4u26-Nov-12 3:56 
GeneralMy vote of 5 Pinmemberprem parihar17-Nov-12 5:22 
GeneralMy vote of 5 Pinmembercsharpbd13-Nov-12 19:44 
GeneralMy vote of 5 Pingroupvaibhav mahajan8-Nov-12 19:42 
GeneralMy vote of 5 PinmemberMember 898400210-Sep-12 0:02 
Generalthank you,bro.. its a great help for me PinmemberKamaljit Mahanto22-Aug-12 3:33 
GeneralMy vote of 5 Pinmembermanoj kumar choubey29-Jun-12 4:05 
GeneralMy vote of 5 PinmemberReza Ahmadi18-Jun-12 9:40 
Questionnice Pinmemberritesh020120-Dec-11 1:42 
Questionnice PinmemberCIDev16-Sep-11 9:39 
GeneralMy vote of 5 PinmemberBrianBissell1-Sep-11 10:02 
GeneralMy vote of 4 PinmemberPie At The Raven30-Aug-11 4:40 
QuestionNice, two suggestions Pinmemberjgauffin29-Aug-11 9:42 
AnswerRe: Nice, two suggestions PinmemberStaffan Sjöstedt31-Aug-11 1:02 
GeneralRe: Nice, two suggestions Pinmemberjgauffin31-Aug-11 1:40 
GeneralRe: Nice, two suggestions PinmemberStaffan Sjöstedt31-Aug-11 20:41 
GeneralRe: Nice, two suggestions PinmemberBrianBissell1-Sep-11 10:05 
Answer$(document).ready() Pinmemberamit910914-Nov-11 23:15 
GeneralMy vote of 5 PinmemberZhipeng Li28-Aug-11 17:02 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140921.1 | Last Updated 11 Nov 2013
Article Copyright 2011 by Shakeel Iqbal
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid