JQuery for Beginners


Introduction

JQuery is a JavaScript library, which has wide range of actions such as Event handling, animation, HTML document traversing and Ajax interaction for web development. JQuery simplifies JavaScript programming.
Download Sample

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

 Collapse | Copy Code
$(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,spanp), 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.
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.

 Collapse | Copy Code
<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.

 Collapse | Copy Code
$(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.

  1. fadeTo(speed, opacity, callback): This method changes the opacity of selected elements to specified opacity.
  2. fadeIn(speed, callback): This method gradually increases the opacity of the elements, from hidden to visible.
  3. fadeOut(speed, callback): This method gradually decreases the opacity of the elements, from visible to hidden.
  4. 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” todiv.

 Collapse | Copy Code
<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:

 Collapse | Copy Code
$(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 animate method is .animate( properties, [duration], [easing], [complete]).

  1. properties: A map of CSS properties, which changes during animation
  2. durationString or number to determine the duration of the animation
  3. easing: The name of easing function to use for the transition
  4. 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.

 Collapse | Copy Code
$("#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.

 Collapse | Copy Code
#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 contentdiv 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”.

 Collapse | Copy Code
<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.

 Collapse | Copy Code
#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.

 Collapse | Copy Code
        $('.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.

 Collapse | Copy Code
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.

 Collapse | Copy Code
$(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:

 Collapse | Copy Code
<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.

 Collapse | Copy Code
$(".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.

 Collapse | Copy Code
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.

 Collapse | Copy Code
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.

 Collapse | Copy Code
$(".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.

 Collapse | Copy Code
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();
    }
}

JQuery Tutorial for Beginners:

This jQuery tutorial is available as a PDF. See this post for details and download link.

jQuery Tutorial for BeginnersNot too long ago I wrote an article for Six Revisions called Getting Started with jQuery that covered some important things (concept-wise) that beginning jQuery developers should know. This article is the complete opposite; there’s no concepts, no principles, and very little lecturing — just some straight example code with brief descriptions demonstrating what you can do with jQuery.

This fast-paced tutorial should be able to get beginners up and running with jQuery very quickly, while also providing a good overview of what jQuery is capable of (although jQuery’s capabilities go far beyond this beginning tutorial).

Keep in mind that this tutorial is just a bunch of straightforward, superficial code examples and very brief explanations for beginners who want to avoid all the jargon and complexities. But I still highly recommend that all beginners get past this stuff by means of a good book, some more in-depth tutorials online, or by using the jQuery documentation.

Link to jQuery’s Source Code Remotely

This is an optional technique that many developers are using today. Instead of hosting the jQuery source code on your own server, you can link to it remotely. This ensures the fastest possible download time of the source code, since many users visiting your site might have the file already cached in their browser. Here is how your <script> tag should look:

Running Code Unobtrusively When the DOM is Ready

The first thing you need to be up and running with jQuery is what’s called the “document ready” handler. Pretty much everything you code in jQuery will be contained inside one of these. This accomplishes two things: First, it ensures that the code does not run until the DOM is ready. This confirms that any elements being accessed are actually in existence, so the script won’t return any errors. Second, this ensures that your code is unobtrusive. That is, it’s separated from content (HTML) and presentation (CSS).

Here is what it looks like:

  1. $(document).ready(function() {
  2.     // all jQuery code goes here
  3. });

Although you will normally include your jQuery code inside the above handler, for brevity the rest of the code examples in this tutorial will not include the “ready” handler.

Selecting Elements in jQuery

The jQuery library allows you to select elements in your HTML by wrapping them in$("") (you could also use single quotes), which is the jQuery wrapper. Here are some examples of “wrapped sets” in jQuery:

  1. $(“div”); // selects all HTML div elements
  2. $(“#myElement”); // selects one HTML element with ID “myElement”
  3. $(“.myClass”); // selects HTML elements with class “myClass”
  4. $(“p#myElement”); // selects paragraph elements with ID “myElement”
  5. $(“ul li a.navigation”); // selects anchors with class “navigation” that are nested in list items

jQuery supports the use of all CSS selectors, even those in CSS3. Here are some examples of alternate selectors:

  1. $(“p > a”); // selects anchors that are direct children of paragraphs
  2. $(“input[type=text]”); // selects inputs that have specified type
  3. $(“a:first”); // selects the first anchor on the page
  4. $(“p:odd”); // selects all odd numbered paragraphs
  5. $(“li:first-child”); // every list item that’s first child in a list

jQuery also allows the use of its own custom selectors. Here are some examples:

  1. $(“:animated”); // selects elements currently being animated
  2. $(“:button”); // selects any button elements (inputs or buttons)
  3. $(“:radio”); // selects radio buttons
  4. $(“:checkbox”); // selects checkboxes
  5. $(“:checked”); // selects selected checkboxes or radio buttons
  6. $(“:header”); // selects header elements (h1, h2, h3, etc.)

View a list of jQuery’s selectors and custom selectors

Manipulating and Accessing CSS Class Names

jQuery allows you to easily add, remove, and toggle CSS classes, which comes in handy for a variety of practical uses. Here are the different syntaxes for accomplishing this:

  1. $(“div”).addClass(“content”); // adds class “content” to all <div> elements
  2. $(“div”).removeClass(“content”); // removes class “content” from all <div> elements
  3. $(“div”).toggleClass(“content”); // toggles the class “content” on all <div> elements (adds it if it doesn’t exist, and removes it if it does)

You can also check to see if a selected element has a particular CSS class, and then run some code if it does. You would check this using an if statement. Here is an example:

  1. if ($(“#myElement”).hasClass(“content”)) {
  2.     // do something here
  3. }

You could also check a set of elements (instead of just one), and the result would return “true” if any one of the elements contained the class.

Manipulating CSS Styles with jQuery

CSS styles can be added to elements easily using jQuery, and it’s done in a cross-browser fashion. Here are some examples to demonstrate this:

  1. $(“p”).css(“width”, “400px”); // adds a width to all paragraphs
  2. $(“#myElement”).css(“color”, “blue”) // makes text color blue on element #myElement
  3. $(“ul”).css(“border”, “solid 1px #ccc”) // adds a border to all lists

View more CSS-related commands for jQuery

Adding, Removing, and Appending Elements and Content

There are a number of ways to manipulate groups of elements with jQuery, including manipulating the content of those elements (whether text, inline elements, etc).

Get the HTML of any element (similar to innerHTML in JavaScript):

  1. var myElementHTML = $(“#myElement”).html(); // variable contains all HTML (including text) inside #myElement

If you don’t want to access the HTML, but only want the text of an element:

  1. var myElementHTML = $(“#myElement”).text(); // variable contains all text (excluding HTML) inside #myElement

Using similar syntax to the above two examples, you can change the HTML or text content of a specified element:

  1. $(“#myElement”).html(“<p>This is the new content.</p>”); // content inside #myElement will be replaced with that specified
  2. $(“#myElement”).text(“This is the new content.”); // text content will be replaced with that specified

To append content to an element:

  1. $(“#myElement”).append(“<p>This is the new content.</p>”); // keeps content intact, and adds the new content to the end
  2. $(“p”).append(“<p>This is the new content.</p>”); // add the same content to all paragraphs

jQuery also offers use of the commands appendTo()prepend()prependTo(),before()insertBefore()after()insertAfter(), which work similarly to append but with their own unique characteristics that go beyond the scope of this simple tutorial.

View more info on some of the above commands

Dealing with Events in jQuery

Specific event handlers can be established using the following code:

  1. $(“a”).click(function() {
  2.     // do something here
  3.     // when any anchor is clicked
  4. });

The code inside function() will only run when an anchor is clicked. Some other common events you might use in jQuery include:

blurfocushoverkeydownloadmousemoveresizescrollsubmit,select.

View a more comprehensive list of jQuery events

Showing and Hiding Elements with jQuery

The syntax for showing, hiding an element (or toggling show/hide) is:

  1. $(“#myElement”).hide(“slow”, function() {
  2.     // do something once the element is hidden
  3. }
  4. $(“#myElement”).show(“fast”, function() {
  5.     // do something once the element is shown
  6. }
  7. $(“#myElement”).toggle(1000, function() {
  8.     // do something once the element is shown/hidden
  9. }

Remember that the “toggle” command will change whatever state the element currently has, and the parameters are both optional. The first parameter indicates the speed of the showing/hiding. If no speed is set, it will occur instantly, with no animation. A number for “speed” represents the speed in milliseconds. The second parameter is an optional function that will run when the command is finished executing.

You can also specifically choose to fade an element in or out, which is always done by animation:

  1. $(“#myElement”).fadeOut(“slow”, function() {
  2.     // do something when fade out finished
  3. }
  4. $(“#myElement”).fadeIn(“fast”, function() {
  5.     // do something when fade in finished
  6. }

To fade an element only partially, either in or out:

  1. $(“#myElement”).fadeTo(2000, 0.4, function() {
  2.     // do something when fade is finished
  3. }

The second parameter (0.4) represents “opacity”, and is similar to the way opacity is set in CSS. Whatever the opacity is to start with, it will animate (fadeTo) until it reaches the setting specified, at the speed set (2000 milliseconds). The optional function (called a “callback function”) will run when the opacity change is complete. This is the way virtually all callback functions in jQuery work.

jQuery Animations and Effects

You can slide elements, animate elements, and even stop animations in mid-sequence. To slide elements up or down:

  1. $(“#myElement”).slideDown(“fast”, function() {
  2.     // do something when slide down is finished
  3. }
  4. $(“#myElement”).slideUp(“slow”, function() {
  5.     // do something when slide up is finished
  6. }
  7. $(“#myElement”).slideToggle(1000, function() {
  8.     // do something when slide up/down is finished
  9. }

To animate an element, you do so by telling jQuery the CSS styles that the item should change to. jQuery will set the new styles, but instead of setting them instantly (as CSS or raw JavaScript would do), it does so gradually, animating the effect at the chosen speed:

  1. $(“#myElement”).animate(
  2.     {
  3.         opacity: .3,
  4.         width: “500px”,
  5.         height: “700px”
  6.     }, 2000, function() {
  7.         // optional callback after animation completes
  8.     }
  9. );

Animation with jQuery is very powerful, and it does have its quirks (for example, to animate colors, you need a special plugin). It’s worth taking the time to learn to use the animate command in depth, but it is quite easy to use even for beginners.

More info on the animate() command

More info on other effects-related jQuery commands

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s