jQuery The Basics Part 2

So you enjoyed my first intro to jQuery and your hungry for more? Well here is some juicy bits for you to sink your teeth into. I will start with some simple introductions to some basic actions then we will create some pretty nifty stuff that you can then go away and put into practise further.

As a quick re-cap 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.

One of the most important things I find when using jQuery is always to have your actions wrapped in a $(document).ready Method.

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

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

Highlight each section as it is clicked

jQuery provides a simple way to select a single element or a group of elements. You can access anelement by type (div, span, p), id, CSS class and attribute etc. In this example, I am going to execute a function on the click of a div and once clicked I will assign a CSS class to that selected div element which has some css rules applied to it for highlighting.

First Div
Second Div
Third Div

The code is super simple:

                    
    $('div').click(
        function () {
            $('.SelectDiv').removeClass('SelectDiv');
            $(this).addClass('SelectDiv');
        }
    );

$(‘div’) will selected all theDiv element in the page and $(‘div’).click(function(){….}); means that on the click of the div the function inside the click() will call.
Easy uh!

As I mentioned above, you can select elements in different ways using jQuery. $(‘.SelectDiv’) Statement will select html elements which have the CSS class “SelectedDiv”. removeClass(‘SelectDiv’); removes the CSS class “SelectDiv” from all selected elements and $(this).addClass(‘SelectDiv’); adds/assigns the CSS class to the current clicked element.

Selectors and Filters in jQuery

There are so many ways you can select different elements and filter them that this post would end up going on forever and I am trying my hardest not to ramble on at you. But of course not to leave it out, here is a link to a table of many of the selectors and filters and examples: Jquery Selectors aren’t I good to you guys.

Sliding and SlideToggle

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

  1. SlideDown(speed, callback): This method gradually increase the height of the
    elements, from hidden to visible.
  2. SlideUp(speed, callback): This method gradually decrease 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 have “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.

Example

Collapse Box (Click Here)

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren

According to your website design, decide the collapsible Area and the element on which you
will handle the Slide behavior. In this example I created a div with the class of box and inside that used an anchor to execute the action and I chose to have a
div with the id “contentArea” for the area which should slide.

<div style="width: 400px">
    <div>
        Collapse Box (<a id="lnkCollapse" href="#" style="color: White; font-size: 12px;
            text-decoration: none;">Click Here</a>)
    </div>
    <div id="contentArea">
        <div align="right"><a id="lnkClose" href="#" style="font-size: 10px;">Close</a></div>

        Your text will be here

    </div>
</div>

The jQuery involved registers the click event of the html element and calls SlideToggle and the anchor with the id of “lnkClose” does the same but calls the SlideUp method of the “contentArea”.

$(document).ready(function () {

    $("#lnkCollapse").click(function () {
        $("#contentArea").slideToggle("slow");
    });

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

Fading Effects

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

  1. fadeTo(speed, opacity, callback): This method changes the opacity of selected elements to a 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.

Example (fadeTo)

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="/wp-content/uploads/2013/02/fade1.jpg" width="100px" height="100px" />
    <img src="/wp-content/uploads/2013/02/fade2.jpg" width="100px" height="100px" />
    <img src="/wp-content/uploads/2013/02/fade3.jpg" width="100px" height="100px" />
</div>

In the ready() function set the default opacity of all the images using $(“#fadeExp1 img”).fadeTo(0, 0.3);. Then on the hover event of each image you can have two functions, one for mouse over and one for mouse out and you set the opacity of each element in that function. For example:

$(document).ready(function () {

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

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

Example (fadeIn – fadeOut – fadeToggle)

Assign ids to all three <a> links and <img> elements. Then you can register the click event on the anchors.

<a id="lnkFadeIn"  href="#">Fade in</a> | 
<a id="lnkFadeOut" href="#">Fade out</a> | 
<a id="lnkFadeToggle" href="#">Fade toggle</a><br />

<img id="imgFade" src="/wp-content/uploads/2013/02/fade1.jpg" width="100px" height="100px" />

On click simply call the fading methods on the image element. You will also notice event.preventDefault(); method in the example. This method prevents or stops the default behavior of the element so the browser does not try and link off and jump to the top of the page.

$(document).ready(function () {

    $("#lnkFadeIn").click(function (event) {
        event.preventDefault();
        $("#imgFade").fadeIn(1000);
    });

    $("#lnkFadeOut").click(function (event) {
        event.preventDefault();
        $("#imgFade").fadeOut(1000);
    });

    $("#lnkFadeToggle").click(function (event) {
        event.preventDefault();
        $("#imgFade").fadeToggle(2000);
    });
});

Example

Congratualtion! You have won.

When the user clicks on the button, it shows a message for a few seconds and after that themessage fades out and vanishes. You can achieve this functionality in one simple block of code.

$(document).ready(function () {

    $("#btnShow").click(function () {
          $('.confirm_save').fadeIn(100).delay(1000).fadeOut(700);
    });   

});

Have you noticed the delay() method between the fadeIn() and fadeout() method? The
delay() method allows us to delay the execution of functions that follow it in the
queue.

Animations

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

  1. properties: A map of CSS properties, which changes during animation.
  2. duration: String 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 completion of animation.

Example 1

Click on the “More detail” button to increase the size of the image using animation
and show the description of the image. This is the html to implement this functionality.

    
<div id="divExp1" style="">
    <img id="img" src="/wp-content/uploads/2013/02/fade1.jpg" width="100px" height="100px" /><br />
    <a id="lnkMoreDetail" href="#">More detail</a>
    <div id="imgDescription" style="width:450px; background-color:#e1e1e1;  display: none;">
            Image description will be here.
        <div>
            <a id="lnkClose" href="#" >Close</a>
        </div>
    </div>
</div>

Then using jQuery we register the click event on the “lnkMoreDetail” element and increase the width and height of the image using “$(“#img”).animate({ width: 449, height: 339 }, “slow”);” Then we show the description and hide the more detail link.

Then on the click event of “lnkClose” we revert the changes.

$(document).ready(function () {

    $("#lnkMoreDetail").click(function (event) {

        event.preventDefault();

        $("#img").animate({ width: 449, height: 339 }, "slow");
        $("#imgDescription").show();
        $("#lnkMoreDetail").hide();

    });

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

        event.preventDefault();
        $("#imgDescription").hide();

        $("#img").animate({ height: 100 }, "fast");
        $("#img").animate({ width: 100 }, "fast");

        $("#lnkMoreDetail").show();

    });

});

Example 2

This is an example of how animation could be used on your site. It is a nice subtle effect on the hover of the social icons. It is implemented very simply like this:

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

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

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

More Advanced usuage

Tabbed Content

Tab 1 Tab 2Tab 3

Tab 1

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren

Tab 2

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren

Tab 3

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren

You can easily create a sophisticated tab control area using jQuery. It is as easy as this! Create Tab Headers or tabs by assigning IDs to each element as I assigned “tab1”, “tab2” and “tab3”. Set the first element as selected by assigning the CSS class “selectTabHeader”.

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

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

By default hide the 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 the click event of all header buttons. On the click of an element remove “selectTabHeader” CSS class from the last selected element and then assign selected CSS class to the clicked element by using this command:

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

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

Simple get the id of the clicked element. Suppose the user clicked on “tab2”. Remove the class “selectedTab” of the last selected content using this 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 the 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');
    });
});

Carousel

It is very easy to create a carousel using jQuery. Simply write this HTML to show images and descriptions.

<div id="carousel">
    <div id="imageContainer">
        <img src="/wp-content/uploads/2013/02/fade1.jpg" />
        <div>
            First image..
        </div>
    </div>
    <div id="imageContainer">
        <img src="/wp-content/uploads/2013/02/fade2.jpg" />
        <div>
            Second image..
        </div>
    </div>
    <div id="imageContainer">
        <img src="/wp-content/uploads/2013/02/fade3.jpg" />
        <div>
            Third image..
        </div>
    </div>
</div>

Write some CSS to hide the “imageContainer” by default.

#carousel
{
    width: 449PX;
    height: 375PX;
    border: 2px solid black;
        background-color:#948b6d;
}

#imageContainer
{

    display: none;
}

#imageContainer.selected
{

    display: block;
}

.imageDetail
{
    border-top: 2px solid black;
    padding: 2px;
    color: black;

}

Now it is time to use jQuery. First of all you need to show the first image container. You then have to start the timer to change the images after some interval.

$(document).ready(function () {
    SetCarousel();
    SetTimmer();
});

function SetCarousel() {
    $("#carousel #imageContainer").first().addClass("selected");
}

function SetTimmer() {
    setInterval(showNext, 2000);
}

“SetInerval” method will call “ShowNext” method every 2000 millisecond interval. The ShowNext method has some very simple routines. Simply remove the “selected” class of the last displayed element. Then assign the selected class to the next element. If next element is null then again select the first.

function showNext() {

    var sel = $("#carousel #imageContainer.selected")
    sel.removeClass('selected');

    var nextImge = sel.next();

    var id = $(nextImge).attr('id');
    if (id != null) {
        nextImge.addClass('selected');
    }
    else {
        SetCarousel();
    }
}

Advanced Carousel

Here is a description of first image

Description of second image

I am going to write 3rd image.
1 2 3

Now you should have enough knowledge to create advanced UI controls. In this example I will explain how to create a Carousel, which will change the images in a sliding style. The user can also change the image using the navigation buttons and also they can directly go to an image using the number options. This is the HTML markup used:

<div>
    <div>
        <div>
            <div>
                <a href="#" target="_blank" >
                    <img src="/wp-content/uploads/2013/02/fade1.jpg" />
                </a>
                <div>
                    Here is a description of first image
                </div>
            </div>
            <div>
                <a href="#" target="_blank" >
                    <img src="/wp-content/uploads/2013/02/fade2.jpg" />
                </a>
                <div>
                    Description of second image
                </div>
            </div>
            <div>
                <a href="#" target="_blank" >
                    <img src="/wp-content/uploads/2013/02/fade3.jpg" />
                </a>
                <div>
                    I am going to write 3rd image.
                </div>
            </div>
        </div>
    </div>
    <div>
        <div style="float: left;">
            <a href="javascript:RotatePrevious();"><<</a>
        </div>
        <div style="float: right;">
            <a href="javascript:RotateNext();">>></a>
        </div>
        <div>
            <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 the active CSS class to the first element. After that we need to 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 and you will get the total width of the reel. Then assign this width to the imageReel class with CSS.

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

To rotate the images it is also pretty 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 the 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 an 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 
}

Now for the numbers, when the user clicks a number select it as active
element and immediately slide to that image:

    //On Click
    $(".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 the current element and find its next or previous element 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();
    }
}