Click here to Skip to main content
15,868,164 members
Articles / Web Development / CSS

jQuery for Beginners

Rate me:
Please Sign up or sign in to vote.
4.81/5 (82 votes)
11 Nov 2013CPOL5 min read 281.6K   10.8K   184   32
This article helps you to understand the JQuery with examples.

Image 1

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.

JavaScript
$(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

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.

HTML
<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.

JavaScript
$(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.

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.

HTML
<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:

JavaScript
$(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.

JavaScript
$("#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.

CSS
#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”.

HTML
<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.

CSS
#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.

JavaScript
$('.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. 

JavaScript
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.  

CSS
$(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

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:

HTML
<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.

JavaScript
$(".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.

JavaScript
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.

JavaScript
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.  

JavaScript
$(".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.

JavaScript
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)


Written By
Chief Technology Officer
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 0:42
professionalRakesh Kohale14-Apr-16 0:42 
QuestionGood article Pin
Rakesh Kohale14-Apr-16 0:42
professionalRakesh Kohale14-Apr-16 0:42 
GeneralMy vote of 1 Pin
Manan Garg9-Oct-14 1:52
Manan Garg9-Oct-14 1:52 
GeneralGreat Work... Thanks Pin
Sasika Miyuran16-Jul-14 8:40
professionalSasika Miyuran16-Jul-14 8:40 
GeneralMy vote of 1 Pin
Jignesh Khant8-May-14 22:58
Jignesh Khant8-May-14 22:58 
GeneralMy vote of 5 Pin
Gun Gun Febrianza12-Apr-14 15:20
Gun Gun Febrianza12-Apr-14 15:20 
GeneralRe: My vote of 5 Pin
Shakeel Iqbal12-Apr-14 20:54
Shakeel Iqbal12-Apr-14 20:54 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun9-Jan-14 17:50
Humayun Kabir Mamun9-Jan-14 17:50 
Generalvote 5 Pin
N.Banukobhan12-Dec-13 22:40
N.Banukobhan12-Dec-13 22:40 
QuestionFantastic Pin
WuRunZhe13-Nov-13 14:21
WuRunZhe13-Nov-13 14:21 
GeneralMy vote of 5 Pin
Waseem-Malik19-Sep-13 3:30
professionalWaseem-Malik19-Sep-13 3:30 
QuestionAdvance Carousel is not working properly ... Pin
prem parihar8-Apr-13 18:20
prem parihar8-Apr-13 18:20 
Questionhow to run this.. Pin
Member 965416110-Dec-12 21:59
Member 965416110-Dec-12 21:59 
GeneralMy vote of 5 Pin
shakil4u26-Nov-12 3:56
shakil4u26-Nov-12 3:56 
GeneralMy vote of 5 Pin
prem parihar17-Nov-12 5:22
prem parihar17-Nov-12 5:22 
GeneralMy vote of 5 Pin
csharpbd13-Nov-12 19:44
professionalcsharpbd13-Nov-12 19:44 
GeneralMy vote of 5 Pin
vaibhav mahajan8-Nov-12 19:42
vaibhav mahajan8-Nov-12 19:42 
GeneralMy vote of 5 Pin
Member 898400210-Sep-12 0:02
Member 898400210-Sep-12 0:02 
Generalthank you,bro.. its a great help for me Pin
Kamaljit Mahanto22-Aug-12 3:33
Kamaljit Mahanto22-Aug-12 3:33 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey29-Jun-12 4:05
professionalManoj Kumar Choubey29-Jun-12 4:05 
GeneralMy vote of 5 Pin
Reza Ahmadi18-Jun-12 9:40
Reza Ahmadi18-Jun-12 9:40 
Questionnice Pin
ritesh020120-Dec-11 1:42
ritesh020120-Dec-11 1:42 
Questionnice Pin
BillW3316-Sep-11 9:39
professionalBillW3316-Sep-11 9:39 
GeneralMy vote of 5 Pin
BrianBissell1-Sep-11 10:02
BrianBissell1-Sep-11 10:02 
GeneralMy vote of 4 Pin
Brian Herbert30-Aug-11 4:40
Brian Herbert30-Aug-11 4: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.