Showing posts with label Span and div. Show all posts
Showing posts with label Span and div. Show all posts

Wednesday, 18 January 2012

jquery visitors flip counter like digital clock

I was visiting a website called stepout.com. I came across this members counter which seem to be cool. So here i explain it for you, how it is done.


Step-1 : We start by adding some jquery plugins and css to our page


 <!-- jQuery from Google CDN, REQUIRED -->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <!-- My flip counter script, REQUIRED -->
    <script type="text/javascript" src="js/flipcounter.min.js"></script>
    <!-- Style sheet for the counter, REQUIRED -->
    <link rel="stylesheet" type="text/css" href="css/counter.css" />

    <!-- jQueryUI from Google CDN, used only for the fancy demo controls, NOT REQUIRED for the counter itself -->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script>
    <!-- Style sheet for the jQueryUI controls, NOT REQUIRED for the counter itself -->
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/vader/jquery-ui.css" />
    <!-- Style sheet for the demo page, NOT REQUIRED for the counter itself -->
    <link rel="stylesheet" type="text/css" href="css/demo.css" />

Step-2 : Next job is to put some div tags where it will be displayed


<li>Increment:
            <span id="inc_value">123</span> <a href="#">[?]</a><div id="inc_slider"></div>
            <div>
                <p>This slider controls the counter increment by using the <b>setIncrement</b> method:</p>
                <code>myCounter.setIncrement(value);</code>
            </div>
        </li>

Step-3 : Our next job is to have some javascript customization


<script type="text/javascript">
    //<![CDATA[

    // Initialize a new counter
    var myCounter = new flipCounter('counter', {value:10000, inc:123, pace:800, auto:true});

    $(function(){

        /**
         * Demo controls
         */

        var smartInc = 0;

        // Increment
        $("#inc_slider").slider({
            range: "max",
            value: 123,
            min: 1,
            max: 1000,
            slide: function( event, ui ) {
                myCounter.setIncrement(ui.value);
                $("#inc_value").text(ui.value);
            }
        });

        // Pace
        $("#pace_slider").slider({
            range: "max",
            value: 800,
            min: 100,
            max: 1000,
            step: 100,
            slide: function( event, ui ) {
                myCounter.setPace(ui.value);
                $("#pace_value").text(ui.value);
            }
        });

        // Auto-increment
        $("#auto_toggle").buttonset();
        $("input[name=auto]").change(function(){
            if ($("#auto1:checked").length == 1){
                $("#counter_step").button({disabled: true});
                $(".auto_off_controls").hide();
                $(".auto_on_controls").show();

                myCounter.setPace($("#pace_slider").slider("value"));
                myCounter.setIncrement($("#inc_slider").slider("value"));
                myCounter.setAuto(true);
            }
            else{
                $("#counter_step").button({disabled: false});
                $(".auto_off_controls").show();
                $(".auto_on_controls").hide();
                $("#add_sub").buttonset();
                $("#set_val, #inc_to, #smart").button();
                myCounter.setAuto(false).stop();
            }
        });
        $("#counter_step").button({disabled: true});
        $("#counter_step").button().click(function(){
            myCounter.step();
            return false;
        });

        // Addition/Subtraction
        $("#add").click(function(){
            myCounter.add(567);
            return false;
        });
        $("#sub").click(function(){
            myCounter.subtract(567);
            return false;
        });

        // Set value
        $("#set_val").click(function(){
            myCounter.setValue(12345);
            return false;
        });

        // Increment to
        $("#inc_to").click(function(){
            myCounter.incrementTo(12345);
            return false;
        });

        // Get value
        $("#smart").click(function(){
            var steps = [12345, 17, 4, 533];

            if (smartInc < 4) runTest();

            function runTest(){
                var newVal = myCounter.getValue() + steps[smartInc];
                myCounter.incrementTo(newVal, 10, 400);
                smartInc++;
                if (smartInc < 4) setTimeout(runTest, 10000);
            }
            $(this).button("disable");
            return false;
        });

        // Expand help
        $("a.expand").click(function(){
            $(this).parent().children(".toggle").slideToggle(200);
            return false;
        });

    });

    //]]>
    </script>
</body>

Saturday, 24 December 2011

Creating a Simple Photo Album with jQuery Similar to Facebook

For the javascript part, I’ve decided to use jQuery as well as the jquery.cycle and jquery.lightbox plugins.


HTML structure


The HTML code needed for a gallery like this is actually rather simple. All we have to do, is to print the images as plain old linked HTML images and wrap image collections in container elements (DIVs).



<h1>My Photo Collection</h1>

<p id="intro">

  This is my photo album...yaddi-yaddi-ya...

</p>

<div class="album">

  <h2>Wicked Album</h2>

  <a href="photos/image1.jpg">

    <img src="photos/thumb_image1.jpg" alt="Lorem" />

  </a>

  <a href="photos/image2.jpg">

    <img src="photos/thumb_image2.jpg" alt="Ipsum" />

  </a>

  <a href="photos/image3.jpg">

    <img src="photos/thumb_image3.jpg" alt="Lorem" />

  </a>

</div>

<div class="album">

  <h2>Wickier Album</h2>

  <a href="photos/image4.jpg">

    <img src="photos/thumb_image4.jpg" alt="Ipsum" />

  </a>

  <a href="photos/image5.jpg">

    <img src="photos/thumb_image5.jpg" alt="Yadi" />

  </a>

  <a href="photos/image6.jpg">

    <img src="photos/thumb_image6.jpg" alt="Yadi" />

  </a>

  <a href="photos/image7.jpg">

    <img src="photos/thumb_image7.jpg" alt="Ya" />

  </a>

</div>

<div class="album">

  <h2>Wickiestest Album</h2>

  <a href="photos/image8.jpg">

    <img src="photos/thumb_image8.jpg" alt="Lorem" />

  </a>

  <a href="photos/image9.jpg">

    <img src="photos/thumb_image9.jpg" alt="Ipsum" />

  </a>

</div>




The Magic of jQuery Plug-Ins


In order to turn this into something a bit more exciting than a bunch of linked images with a blue border, we add some JavaScript and CSS to the page.

First, make sure to include jQuery, jQuery Cycle and jQuery Lightbox to the page. Then add the following JavaScript code to another .js-file that is loaded into the same page:



$(document).ready( function() {

  // Dynamically add nav buttons as these are not needed in non-JS browsers

  var prevNext = '<div id="album-nav"><button ' +

                   'class="prev">&laquo; Previous' +

                   '</button><button>' +

                   'Next &raquo;</button></div>';

  $(prevNext).insertAfter('.album:last');

  // Add a wrapper around all .albums and hook jquery.cycle onto this

  $('.album').wrapAll('<div id="photo-albums"></div>');

  $('#photo-albums').cycle({

    fx:     'turnDown',

    speed:  500,

    timeout: 0,

    next:   '.next',

    prev:   '.prev'

  });

  // Remove the intro on first click -- just for the fun of it

  $('.prev,.next').click(function () {

    $('#intro:visible').slideToggle();

  });

  // Add lightbox to images

  $('.album a').lightBox();

});




You may of course remove the cycling effect.
The only JavaScript you’d then need is $('.album a').lightBox();.

Adding Style Info


Last, we add some style info to make our albums look at least somewhat good.



/** for this example, I don't give a rats (*) about IE */

.album {

  width: 600px !important;

  clear: both;

}

.album h2 {

  clear: both;

}

.album a {

  display: block;

  float: left;

  margin-right: 1em;

  padding: 0.5em;

  border: 1px solid black;

  background-color: #eee;

  text-align: center;

}

.album a:hover {

  border-color: blue;

}

.album img {

  width: 72px;

  height: 100px;

  border: 0;

}

#album-nav {

  margin-top: 1em;

  max-width: 500px;

}

.prev, .next {

  border: 1px outset #ccc;

  color: #000075;

  background-color: white;

  font-weight:bold;

  padding: 0.25em;

}

.prev:hover,.next:hover {

  border-style: inset;

}

.prev {

  float: left;

}

.next {

  float: right;

}




Finish!

Friday, 25 November 2011

Hello, world!

Every decent programming tutorial will start with a "Hello, world!" example and this tutorial is yet another one of them. In the previous chapter, we learned how to include jQuery on our page, so that we may start using all of its great features. You need to know a bit more about how jQuery works, before you can start writing your own code, but just to make sure that everything is working, and for you to see how simple jQuery is, let's kick off with a little example:

<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>

Okay, so we have a div tag with the id of "divTest1". In the JavaScript code we use the $ shortcut to access jQuery, then we select all elements with an id of "divTest1" (there is just one though) and set its text to "Hello, world!". You may not know enough about jQuery to understand why and how this works, but as you progress through this tutorial, all of the elements will be explained in detail.

Even such a simple task as this one would actually require quite a few extra keystrokes if you had to do it in plain JavaScript, with no help from jQuery:

<div id="divTest2"></div>
<script type="text/javascript">
document.getElementById("divTest2").innerHTML = "Hello, world!";
</script>

And it would be even longer if our HTML element didn't have an ID, but for instance just a class.

Normally though, you wait for the document to enter the READY state before you start manipulating its content. The above examples will work in most browsers and likely even work when you do more advanced stuff, but certain tasks may fail if you try to do them before the document is loaded and ready. Fortunately, jQuery makes this very easy as well, as we will see in the next chapter. After that, we will start looking into one of the most important aspects of jQuery, which has already been used in the above example: Selectors.

Using elements, ID's and classes

The #id selector


A very common selector type is the ID based, which we saw in the "Hello, world" example. It uses the ID attribute of a HTML tag to locate the desired element. An ID should be unique, so you should only use this selector when you wish to locate a single, unique element. To locate an element with a specific ID, write a hash character, followed by the ID of the element you wish to locate, like this:
$("#divTest")

An example of it in use:

<div id="divTest"></div>
<script type="text/javascript">
$(function()
{
        $("#divTest").text("Test");
});
</script>

Now, while there is only a single element that matches our query above, you should be aware that the result is a list, meaning that it can contain more than one element, if the query matches more than one. A common example of this is to match all elements which uses one or several CSS classes.

The .class selector


Elements with a specific class can be matched by writing a . character followed by the name of the class. Here is an example:

<ul>
        <li class="bold">Test 1</li>
        <li>Test 2</li>
        <li class="bold">Test 3</li>
</ul>
<script type="text/javascript">
$(function()
{
        $(".bold").css("font-weight", "bold");
});
</script>

The element selector


You can also match elements based on their tag names. For instance, you can match all links on a page like this:

$("a")

Or all div tags like this:

$("div")

If you use a multi-element selector, like the class selector we used in the previous example, and we know that we're looking for elements of a specific type, it's good practice to specify the element type before the selector. Not only is it more precise, it's also faster for jQuery to process, resulting in more responsive sites. Here is a re-written version of the previous example, where we use this method:
$("span.bold").css("font-weight", "bold");

This will match all span elements with "bold" as the class. Of course, it can be used with ID's and pretty much all of the other selectors as well.

Selectors can do much more for you though. Read on for more cool examples.

Parent/child relation selectors

jQuery also allows you to select elements based on their parent element. There are two variations: One which will only match elements which are a direct child to the parent element, and one which will match all the way down through the hierarchy, e.g. a child of a child of a child of a parent element.

The syntax for finding children which are direct descendants of an element looks like this:

$("div > a")

This selector will find all links which are the direct child of a div element. Replacing the greater-than symbol with a simple space will change this to match all links within a div element, no matter if they are directly related or not:

$("div a")

Here's an example where we color bold tags blue if they are directly descending from the first test area:

<div id="divTestArea1">
        <b>Bold text</b>
        <i>Italic text</i>
        <div id="divTestArea2">
                <b>Bold text 2</b>
                <i>Italic text 2</i>
                <div>
                        <b>Bold text 3</b>
                </div>
        </div>
</div>

<script type="text/javascript">
$("#divTestArea1 > b").css("color", "blue");
</script>

As you will see, only the first bold tag is colored. Now, if you had used the second approach, both bold tags would have been colored blue. Try the following example, where the only thing changed is the greater-than character which has been replaced with a space, to note that we also accept non-direct descendants or "grand children" as they are sometimes called:

<div id="divTestArea1">
        <b>Bold text</b>
        <i>Italic text</i>
        <div id="divTestArea2">
                <b>Bold text 2</b>
                <i>Italic text 2</i>
                <div>
                        <b>Bold text 3</b>
                </div>
        </div>
</div>

<script type="text/javascript">
$("#divTestArea1 b").css("color", "blue");
</script>

Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method. We'll look into that in another chapter of this tutorial.

Custom animations with the animate() method

In previous chapters, we looked into the built-in fading and sliding effect methods of jQuery. However, you can much more than just that. With the animate() method, you can create custom animations where you manipulate pretty much any numerical CSS property of an element. This allows you to e.g. move a box slowly across the screen or have it jump up and down. Let's try something very simple:

<div style="height: 60px;">
        <div id="divTestBox1" style="height: 50px; width: 50px;
background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox1").animate(
                {
                        "left" : "200px"
                }
        );
});
</script>

The first, and only required, parameter of the animate function is a map of the CSS properties that you wish to have altered. In this case, we have an absolutely positioned div element, which we tell jQuery to move until it has reached a left property of 200 pixels.
The second parameter allows you to specify the duration of the animation in milliseconds or as "slow" or "fast" which is the same as 600 or 200 ms. With this, we can slow down the above example as much as we want:

<div style="height: 60px;">
        <div id="divTestBox2" style="height: 50px; width: 50px;
background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox2").animate(
                {
                        "left" : "200px"
                },
                5000
        );
});
</script>

As the third parameter, we can specify a callback function to be called once the animation is done. This can be very useful for performing a number of different animations in a row. For instance, check out this example:

<div style="height: 40px;">
        <div id="divTestBox3" style="height: 20px; width: 20px;
background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox3").animate(
                { "left" : "100px" },
                1000,
                function()
                {
                        $(this).animate(
                                { "left" : "20px" },
                                500,
                                function()
                                {
                                $(this).animate({ "left" : "50px" }, 500);
                                }
                        )
                }
        );
});
</script>

It might seem a bit overwhelming, but what we do is that we call the animate method and ask for the left property of our test "div" to be animated until it reaches a left of 100 pixels. We want it to take 1 second (1000 milliseconds) and once it completes, we wish for a new animation to start, which moves it back to 20 pixels within half a second, and as soon as THAT animation is done, we move it a bit right again, so that it now has a left property of 50 pixels.

However, since jQuery comes with queue functionality for animations, you can actually achieve the above example in a much simpler manner. This however only applies when you want a set of animations to performed after each other - if you want to do something else when an animation is complete, the above example will still be the way to go. Here's the queue version:

<div style="height: 40px;">
<div id="divTestBox4" style="height: 20px; width: 20px; background-color: #89BC38;
position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox4").animate({ "left" : "100px" }, 1000);
        $("#divTestBox4").animate({ "left" : "20px" }, 500);
        $("#divTestBox4").animate({ "left" : "50px" }, 500);
});
</script>

Getting and setting CSS classes

Just like it's very easy to manipulate content and attributes of elements, as we saw in the previous chapters, it's equally easy to manipulate the CSS of elements. jQuery gives you easy access to changing both the style attribute, which you manipulate using the css() method, as well as the class(es) of an element, where several different methods lets you modify it.

Let's start by looking into changing the class attribute. The class attribute takes one or several class names, which may or may not refer to a CSS class defined in your stylesheet. Usually it does, but you may from time to time add class names to your elements simply to be able to reach them easily from jQuery, since jQuery has excellent support for selecting elements based on their class name(s).

I have defined a couple of very simple CSS selectors in my stylesheet, mostly for testing purposes:
.bold {
        font-weight: bold;
}

.blue {
        color: blue;
}

In the following example we will use three of the most interesting class related methods: hasClass(), which checks if one or several elements already has a specific class defined, addClass(), which simply adds a class name to one or several elements and the removeClass() methods, which will.... well, you've probably already guessed it.

<a href="javascript:void(0);" onclick="ToggleClass(this);">Toggle class</a>

<script type="text/javascript">
function ToggleClass(sender)
{

        if($(sender).hasClass("bold"))
                $(sender).removeClass("bold");
        else
                $(sender).addClass("bold");
}
</script>

The example is actually very simple. When the link is clicked, we send the link itself (this) as a parameter to the ToggleClass() method that we have defined. In it, we check if the sender already has the "bold" class - if it has, we remove it, otherwise we add it. This is a pretty common thing to do, so obviously the jQuery people didn't want us to write an entire three lines of code to it. That's why they implemented the toggleClass() method, with which we can turn our entire example above into a single line of code:

<a href="javascript:void(0);" onclick="$(this).toggleClass('bold');">
Toggle class</a>

Of course, we can select multiple elements, where we can add or remove multiple classes, as well. Here's an example of just that:

<div id="divTestArea1">
        <span>Test 1</span><br />
        <div>Test 2</div>
        <b>Test 3</b><br />
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestArea1 span, #divTestArea1 b").addClass("blue");
        $("#divTestArea1 div").addClass("bold blue");
});
</script>

First we select the span and the b tag, which we add a single class to: the bold class. Then we select the div tag, which we add two classes to, separated by a space: The bold and the blue class. The removeClass() methods works just the same way, allowing you to specify several classes to be removed, separated with a space.

The before() and after() methods

In the previous chapter, we used the append() and prepend() methods to insert stuff inside an element, but in some cases, you need to insert things before or after one or several elements instead. jQuery has the before() and after() methods for just this purpose, and they are just as easy to use. Check out this example:

<a href="javascript:void(0);" onclick="$('input.test1')
.before('<i>Before</i>');">Before</a>  
<a href="javascript:void(0);" onclick="$('input.test1')
.after('<b>After</b>');">After</a>

<br /><br />

<input type="text" class="test1" value="Input 1" name="txtInput1" /><br />
<input type="text" class="test1" value="Input 2" name="txtInput2" /><br />

Depending on which of the two links you click, an italic or a bold tag will be inserted before or after each input element on the page using the "test1" class. Just like with append() and prepend(), both after() and before() allows you to use HTML strings, DOM elements and jQuery objects as parameters and an infinite amount of them as well. We'll demonstrate that in the next example:

<a href="javascript:void(0);" onclick="InsertElements();">Insert elements</a>
<br /><br />
<span id="spnTest2">Hello world? </span>

<script type="text/javascript">
function InsertElements()
{
        var element1 = $("<b></b>").text("Hello ");
        var element2 = "<i>there </i>";
        var element3 = document.createElement("u");
        element3.innerHTML = "jQuery!";

        $("#spnTest2").after(element1, element2, element3);
}
</script>

In this example, we create a jQuery object, an HTML string and a JavaScript DOM element, and then we use the after() method to insert all of them after our span tag. Of course, the before() method could have been used in exactly the same way.

There are variations of the before() and after() methods, called insertBefore() and insertAfter(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to insert data before or after, with a parameter of what is to be inserted, you do the exact opposite. Which method to use obviously depends on the situation, but here's an example showing you how to use them both:

<a href="javascript:void(0);" onclick="InsertElementsBefore();">
Insert elemenets</a>
<br /><br />
<span id="spnTest3">Hello world? </span>

<script type="text/javascript">
function InsertElementsBefore()
{      
        $("#spnTest3").before($("<i></i>").text("before() "));
        $("<b></b>").text("insertBefore() ").insertBefore("#spnTest3");
}
</script>

In this example, we insert the items before the span tag, but you could of course do the exact same using after() and insertAfter(), if you wish to insert after the target elemenet. As you can see, the result is the same - only the order of what we do differs.

The remove() and empty() methods

In the last couple of chapters, we have worked with adding new elements to a page, but of course jQuery can help you remove them as well. There are mainly two methods for this: remove() and empty(). The remove() method will delete the selected element(s), while the empty() method will only delete all child elements of the selected element(s). The following example should illustrate the difference - be sure to click the links in the right order though:

<a href="javascript:void(0);" onclick="$('#divTestArea1').empty();">
empty() div</a>  
<a href="javascript:void(0);" onclick="$('#divTestArea1').remove();">
remove() div</a>
<div id="divTestArea1" style="height: 100px; width: 300px; padding: 20px;
border: 1px solid silver; background-color: #eee;">
        <b>Bold text</b>
        <i>Italic text</i>
</div>

The first link will call the empty() method on our test div, removing all the child elements. The second link will remove the entire div, including any child elements. Pretty simple stuff.

The remove() method comes with one optional parameter, which allows you to filter the elements to be removed, using any of the jQuery selector syntaxes. You could of course achieve the same simply by doing the filtering in your first selector, but in some situations, you may be working on a set of already selected elements. Check out this example of it in use:

<a href="javascript:void(0);" onclick="$('#divTestArea2 b').remove('.more');">
remove() more bold</a>
<div id="divTestArea2" style="height: 100px; width: 300px; padding: 20px;
border: 1px solid silver; background-color: #eee;">
        <b>Bold text</b><br />
        <b class="more">More bold text</b><br />
        <b class="more">Even more bold text</b><br />
</div>

We start out by selecting all bold tags inside our test div. We then call the remove() method on the selected elements, and pass in the .more filter, which will make sure that we only get elements which uses the class "more". As a result, only the last two bold texts are removed.

You can of course use even more advanced selectors as a filter too. Have a look at the "Selectors" topic of this tutorial for inspiration.

The bind() method

One of the most important aspects of dealing with events through jQuery is the bind() and unbind() methods. As the names imply, they will simply attach and unattach code to one or several events on a set of elements. We saw a very simple usage example for the bind() method in the introduction chapter for events, and here is a more complete one:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
$(function()
{
        $("a").bind("click", function() {
                alert($(this).text());
        });
});
</script>

It works by selecting all links (<a> elements) and then bind the anonymous function you see to the click event. A cool little feature is that jQuery will automatically assign the element that is clicked, to the "this" keyword inside of the anonymous function. This will allow you to access the element that activates the element, even when you assign the same code to multiple elements.

When jQuery calls your method, it will pass information about the event as the first parameter, if you have specified one or more parameters on it. For instance, the event object passed will contain information about where the mouse cursor is, which type the event is, which keyboard key or mouse button was pressed (if any) and much more. You can see all the properties and methods on the event object here: http://api.jquery.com/event.which/

Here is an example:

<div id="divArea" style="background-color: silver; 
width: 100px; height: 100px;">
</div>
<script type="text/javascript">
$("#divArea").bind("mousemove", function(event)
{
        $(this).text(event.pageX + "," + event.pageY);
});
</script>

We create a div element of a reasonable size and a background color. For this div, we subscribe to the mousemove event, with an anonymous function with a parameter called "event". This object gives us access to the pageX and pageY properties, which tells us where on the page the mouse cursor currently is, relative to the top left corner of the document. Try the example and move the cursor over the div element and you will see the coordinates updated as you move the mouse.

The bind() method also allows you to pass in data of your own and access it from the event object. This also allows you to set values at the time you bind the event, and be able to read this value at the time the event is invoked, even though the original variable you used may have changed. Here's an example where you can see just that:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
        $("a").bind("click", { message : msg }, function(event) {
                msg = "Changed msg";
                alert(event.data.message);
        });
});
</script>

We pass the value as the secondary parameter of the bind() method, as a map of keys and values. You can pass more than one value by separating them with a comma. To access the value inside the event handler, we use the data property of the event object. This property contains sub-properties for each of the values you have passed, which means that you can access the value of the message parameter using event.data.message.

Despite the fact that we change the value of the "msg" variable inside the event handler, the message displayed will still be "Hello, world!" every time you click on one of the links, because it's evaluated as soon as the event handler is bound, which is once the page has been loaded.

The live() method

In the previous chapters, we used the bind() and unbind() methods to attach and detach event handlers to various elements on the page. This works great for elements which already exists, but what if you want your event handler to be attached to future elements as well? Normally you would have to do this manually, upon creating the new elements, and this is still possible. However, using the live() method, you can inform jQuery to attach your event handler to any future elements which matches your original selector, without having to lift a finger. Let me first show you an example where we use the bind() method, and then replace it with the live() method, to show you the difference:

<div id="divTestArea1">
        <a href="javascript:void(0);" onclick="AddBox();">Add box</a>
        <div class="test">This is a box</div>
</div>

<script type="text/javascript">
$(function()
{
        $(".test").bind("mouseover", function()
        {
                $(this).css("background-color", "blue");
        }).bind("mouseout", function()
        {
                $(this).css("background-color", "white");
        });
});

function AddBox()
{
        var div = $("<div></div>").addClass("test").text("Another box");
        $("#divTestArea1").append(div);
}
</script>

Okay, this example might seem a bit complicated, but actually it's not. Let me walk you through it. We have a link, which will call the AddBox() JavaScript method, and then we have a div with the class "test". The AddBox() method will simply add another div to the page, with the same class, so that when you click the link, you get yet another box on the page. In the ready event, we select all elements with the "test" class and then we bind a handler to two of the events: The mouseover and the mouseout event, where we change the color of the element invoking the event. Try the example in your browser. The first div will have the mouseover effect, but if you click the link to add more boxes, they won't have the same effect. The reason is pretty obvious: We attached the events before these new boxes were created.

Now try the following example instead. I have only changed two words in it: The two calls to bind() has been replaced with calls to live():

<div id="divTestArea2">
        <a href="javascript:void(0);" onclick="AddBox();">Add box</a>
        <div class="test">This is a box</div>
</div>

<script type="text/javascript">
$(function()
{
        $(".test").live("mouseover", function()
        {
                $(this).css("background-color", "blue");
        }).live("mouseout", function()
        {
                $(this).css("background-color", "white");
        });
});

function AddBox()
{
        var div = $("<div></div>").addClass("test").text("Another box");
        $("#divTestArea2").append(div);
}
</script>

Now if you run this example, you will see that even though you add new elements after the page has loaded, jQuery will automatically attach the event handlers to them for you. The live() method works just like bind() in all the other aspects, so check the previous chapters for more information on it. The same goes for the die() method, which works just like the unbind() method, but should be used for cases where the live() method has been used.

Saturday, 7 May 2011

Gmail, Facebook Style jQuery Chat amazing!!!



Demo
Please load the following links in different browsers otherwise it wont work:

[caption id="" align="alignright" width="245" caption="Image via CrunchBase"]Image representing Facebook as depicted in Cru...[/caption]

Sample Chat User Swadesh
Sample Chat User Vimla
Sample Chat User Brijesh

Introduction
Everyone loves the gmail and facebook inline chat modules. This jQuery chat module enables you to seamlessly integrate Gmail/Facebook style chat into your existing website.



Features
1. Gmail style bottom right display of chat boxes
2. Keeps chat boxes open and stores state (data) even when pages are browsed/refreshed similar to Facebook
3. Displays “Sent at…” after 3 minutes of inactivity
4. Displays “X says…” & blinks chat boxes when window is not in focus
5. Minimize and close chat boxes
6. Auto-resize of text input box
7. Auto-scrolling of chat text
8. Auto-back-off polling policy (hits the server less-often when chat activity is low)
9. Extremely simple to integrate into existing site

Getting Started
First download the module (link below)

You must first create a mySQL table as below (or import db.txt provided in project files)
CREATE TABLE IF NOT EXISTS `chat` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `from` varchar(255) NOT NULL DEFAULT '',
  `to` varchar(255) NOT NULL DEFAULT '',
  `message` text NOT NULL,
  `sent` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `recd` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=539 ;


CREATE TABLE IF NOT EXISTS `users` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) DEFAULT NULL,
  `password` varchar(30) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `gender` varchar(8) NOT NULL,
  `dob` varchar(16) NOT NULL,
  `phone` varchar(20) NOT NULL,
  `profile_image` varchar(50) NOT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`uid`, `username`, `password`, `email`, `gender`, `dob`, `phone`, `profile_image`) VALUES
(1, 'Swadesh', 'pass1', 'itswadesh@gmail.com', '', '', '', ''),
(2, 'Brijesh', 'pass1', 'brijesh@gmail.com', '', '', '', ''),
(3, 'Vimla', '', 'pass1', 'vimla@gmail.com', '', '', '');

Add the following scripts to your page template
<code><script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/chat.js"></script>
</code>

Add the following CSS to your page
<link type="text/css" rel="stylesheet" media="all" href="css/chat.css" />
<link type="text/css" rel="stylesheet" media="all" href="css/screen.css" /><!--[if lte IE 7]>
<link type="text/css" rel="stylesheet" media="all" href="css/screen_ie.css" />
<![endif]-->

Now in your list of users online, add “javascript:chatWith(’USERNAME’);” function where USERNAME is the username for that particular user who he/she wants to chat with.

Once that is done, edit chat.php and set your database parameters and try your website.

For better understanding, load 3 different browsers (internet explorer, firefox, safari) and point them to samplea.php, sampleb.php and samplec.php.

Click on “chat with john doe” link and watch the chat functionality come alive!

Inorder to integrate your existing website, you must place all your content between the “main_container” div tag.

Browser Compatibility
1. Firefox 2+
2. Internet Explorer 6+
3. Safari 2+
4. Opera 9+