Showing posts with label Cascading Style Sheets. Show all posts
Showing posts with label Cascading Style Sheets. 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, 23 December 2011

facebook like red notification simple css technique

While developing my current web project, i came across a requirement which has to be lashed with a notification similar style as facebook.

After puting some effort i found out the following implementation.

    

Here is a explanation of the above implementation using CSS and simple javascript.

The css


<style>

.noti_Container {
position:relative;
border:1px solid blue; /* This is just to show you where the container ends */
width:16px;
height:16px;
cursor: pointer;
}
.noti_bubble {
position:absolute;
top: -8px;
right:-6px;
padding-right:2px;
background-color:red;
color:white;
font-weight:bold;
font-size:0.80em;

border-radius:2px;
box-shadow:1px 1px 1px gray;
}

</style>

The HTML code


<div onclick="return f1();">
<img src="friends.png" style="border:none;"/>
<div id="n1">2</div>
</div>

The small javascript code to add some more functionality


<script>
function f1()
{
document.getElementById("n1").style.visibility='hidden';
}
</script>

The final implementation can be found here at http://fb.walletchange.com/profile.php

Tuesday, 29 November 2011

Facebook Style Alert Confirm Box with jQuery and CSS

                 

Create a facebook style alert box with jquery plug-in jquery.alert.js. Bellow is the complete tutorial

HTML / Javascript Code
Contains javascript and HTML Code.



<link href="facebook.alert.css" rel="stylesheet" type="text/css">

<script type="text/javascript"

src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js"></script>

<script type="text/javascript" src="jquery.alert.js"></script>

<script type="text/javascript"> $(document).ready( function()

{ $("#delete_confirm").click( function()

{ jConfirm('Are you sure you want ot delete this thread?', '', function(r)

{ if(r==true) { $("#box").fadeOut(300); } }); }); });

</script>
<div id="box" style=" background-color:#ffffcc;">

<a href="#" id="delete_confirm">Delete</a>

</div>



facebook.alert.css
Contains CSS code.



#popup_container

{

font-family:'Lucida Grande',arial;

font-weight:bold;

text-align:left;

font-size: 12px;

width: 364px;

height: 86px;

background: #F3F3F3;

border:solid 1px #dedede;

border-bottom: solid 2px #456FA5;

color: #000000; }
#popup_title

{ display:none; }
#popup_message

{ padding-top: 15px; padding-left: 15px; }
#popup_panel

{ text-align: left; padding-left:15px; }
input

{

background-color:#476EA7;

padding:3px; color:#FFFFFF;

margin-top:20px;

margin-right:10px;

}


Saturday, 26 November 2011

Facebook Style Footer Admin Panel

                 

The popularity of social media has been booming in the past few years and Facebook definitely has climbed high to the top of the social network rankings. Facebook has many Ajax driven features and applications that are very impressive, and one of the things I particularly like is the footer admin panel, where it neatly organizes frequently used links and applications.

This week I would like to cover part 1 of how to recreate the Facebook footer admin panel with CSS and jQuery.


Step 1. Wireframe and Tooltip Bubbles – HTML & CSS


Lay out the wireframe of the admin panel using an unordered list for the foundation. The last two list items (Alert Panel & Chat Panel) will have sub-panels nested within them. Since these two panels will float to the right, the order in the markup will be reversed.

Tooltip foundation

Notice that there is a <small> tag nested within the <a> tag, this is how we will achieve our tooltip bubble on the navigation.

HTML


<div id="footpanel">
<ul id="mainpanel">
<li><a href="#">Inspiration <small>
Design Bombs</small></a></li>
<li><a href="#">View Profile <small>
View Profile</small></a></li>
<li><a href="#">Edit Profile <small>
Edit Profile</small></a></li>
<li><a href="#">Contacts <small>
Contacts</small></a></li>
<li><a href="#">Messages (10) <small>
Messages</small></a></li>
<li><a href="#">Play List <small>
Play List</small></a></li>
<li><a href="#">Videos <small>
Videos</small></a></li>
<li id="alertpanel"><a href="#">
Alerts</a></li>
<li id="chatpanel"><a href="#">
Friends (<strong>18</strong>)</a></li>
</ul>
</div>

CSS


First start by fixing the panel to the bottom of the viewport.
#footpanel {
position: fixed;
bottom: 0; left: 0;
z-index: 9999;
/*--Keeps the panel on top of all other elements--*/
background: #e3e2e2;
border: 1px solid #c3c3c3;
border-bottom: none;
width: 94%;
margin: 0 3%;
}

As you may already know, IE6 does not understand fixed positioning. I stumbled across a tutorial that fixed this problem*.
*html #footpanel { /*--IE6 Hack - Fixed Positioning to the Bottom--*/
margin-top: -1px;
/*--Prevents IE6 from having an infinity scroll bar - due to 1px border on #footpanel--*/
position: absolute;
top:expression(eval(
document.compatMode &&document.compatMode=='CSS1Compat')
?documentElement.scrollTop+(
documentElement.clientHeight-this.clientHeight)
: document.body.scrollTop +(
document.body.clientHeight-this.clientHeight));
}

*Note: Due to heavy loading on the browser, an alternative solution would be to either use an position: absolute; or if the situation/client allows it use display: none; for those with IE6.

Style the unordered list which will be the foundation of this panel.
#footpanel ul {
padding: 0; margin: 0;
float: left;
width: 100%;
list-style: none;
border-top: 1px solid #fff;
/*--Gives the bevel feel on the panel--*/
font-size: 1.1em;
}
#footpanel ul li{
padding: 0; margin: 0;
float: left;
position: relative;
}
#footpanel ul li a{
padding: 5px;
float: left;
text-indent: -9999px;
/*--For text replacement - Shove text off of the page--*/
height: 16px; width: 16px;
text-decoration: none;
color: #333;
position: relative;
}
html #footpanel ul li a:hover{ background-color: #fff; }
html #footpanel ul li a.active {
/*--Active state when sub-panel is open--*/
background-color: #fff;
height: 17px;
margin-top: -2px;
/*--Push it up 2px to attach the active button to sub-panel--*/
border: 1px solid #555;
border-top: none;
z-index: 200;
/*--Keeps the active link on top of the sub-panel--*/
position: relative;
}

Tooltip Demo

Declare the text replacement for each link.
You can download these great icons by Pinvoke here.
#footpanel a.home{
background: url(home.png) no-repeat 15px center;
width: 50px;
padding-left: 40px;
border-right: 1px solid #bbb;
text-indent: 0;
/*--Reset text indent since there will be a
combination of both text and image--*/
}
a.profile{ background: url(user.png)
no-repeat center center; }
a.editprofile{ background: url(wrench_screwdriver.png)
no-repeat center center; }
a.contacts{ background: url(address_book.png)
no-repeat center center; }
a.messages{ background: url(mail.png)
no-repeat center center; }
a.playlist{ background: url(document_music_playlist.png)
no-repeat center center; }
a.videos{ background: url(film.png)
no-repeat center center; }
a.alerts{ background: url(newspaper.png)
no-repeat center center; }
#footpanel a.chat{
background: url(balloon.png)
no-repeat 15px center;
width: 126px;
border-left: 1px solid #bbb;
border-right: 1px solid #bbb;
padding-left: 40px;
text-indent: 0;
/*--Reset text indent since there will be
a combination of both text and image--*/
}
#footpanel li#chatpanel, #footpanel li#alertpanel {
 float: right; }
/*--Right align the chat and alert panels--*/

Tooltip Demo

Style the tooltip bubble, by default the <small> tag will be hidden with a display:none;. On hover over, allow the tooltip to appear with a display:block;
#footpanel a small {
text-align: center;
width: 70px;
background: url(pop_arrow.gif) no-repeat center bottom;
padding: 5px 5px 11px;
display: none; /*--Hide by default--*/
color: #fff;
font-size: 1em;
text-indent: 0;
}
#footpanel a:hover small{
display: block; /*--Show on hover--*/
position: absolute;
top: -35px;
/*--Position tooltip 35px above the list item--*/
left: 50%;
margin-left: -40px; /*--Center the tooltip--*/
z-index: 9999;
}

Friday, 25 November 2011

Method chaining

Yet another one of the really cool aspects of jQuery is the fact that most of the methods returns a jQuery object that you can then use to call another method. This allows you to do command chaining, where you can perform multiple methods on the same set of elements, which is really neat because it saves you and the browser from having to find the same elements more than once. Here's an example, and don't worry about the jQuery methods used in the following examples - they will be explained in later chapters:

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

It works like this: We instantiate a new jQuery object and select the divTest1 element with the $ character, which is a shortcut for the jQuery class. In return, we get a jQuery object, allowing us to manipulate the selected element. We use that object to call the text() method, which sets the text of the selected element(s). This method returns the jQuery object again, allowing us to use another method call directly on the return value, which is the css() method.

We can add more method calls if needed, but at some point, the line of code will become quite long. Fortunately for us, JavaScript is not very strict when it comes to the syntax, so you can actually format it like you want, including linebreaks and indentations. For instance, this will work just fine as well:

<div id="divTest2"></div>
<script type="text/javascript">
        $("#divTest2").text("Hello, world!")
                                        .removeClass("blue")
                                        .addClass("bold")
                                        .css("color", "blue");                                  
</script>

JavaScript will simply throw away the extra whitespace when interpreting the code and execute it as one long line of code with several method calls.

Note that some methods doesn't return the jQuery object, while others only return it depending on the parameters you pass to it. A good example of that is the text() method used above. If no parameters are passed to it, the current text of the selected element(s) is returned instead of a jQuery object, while a single parameter causes jQuery to set the specified text and return a jQuery object.

Introduction to jQuery selectors

A very common task when using JavaScript is to read and modify the content of the page. To do this, you need to find the element(s) that you wish to change, and this is where selector support in jQuery will help you out. With normal JavaScript, finding elements can be extremely cumbersome, unless you need to find a single element which has a value specified in the ID attribute. jQuery can help you find elements based on their ID, classes, types, attributes, values of attributes and much, much more. It's based on CSS selectors and as you will see after going through this tutorial, it is extremely powerful.

Because this is such a common task, the jQuery constructor comes in several forms that takes a selector query as an argument, allowing you to locate element(s) with a very limited amount of code for optimal efficiency. You can instantiate the jQuery object simply by writing jQuery() or even shorter using the jQuery shortcut name: $(). Therefore, selecting a set of elements is as simple as this:

$(<query here>)

With the jQuery object returned, you can then start using and altering the element(s) you have matched. In the following chapters, you will see examples of some of the many ways you can select elements with jQuery.

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.

Using attributes

In the previous chapter, we saw how we could find elements in a page from their class or their ID. These two properties are related because of the fact that you can use them to style the elements with CSS, but with jQuery, you can actually find elements based on any kind of attribute. It comes with a bunch of attribute selector types and in this article, we will look into some of them.

Find elements with a specific attribute


The most basic task when selecting elements based on attributes is to find all the elements which has a specific attribute. Be aware that the next example doesn't require the attribute to have a specific value, in fact, it doesn't even require it to have a value. The syntax for this selector is a set of square brackets with the name of the desired attribute inside it, for instance [name] or [href]. Here is an example:

<span title="Title 1">Test 1</span><br />
<span>Test 2</span><br />
<span title="Title 3">Test 3</span><br />

<script type="text/javascript">
$(function()
{
        $("[title]").css("text-decoration", "underline");
});
</script>

We use the attribute selector to find all elements on the page which has a title attribute and then underline it. As mentioned, this will match elements with a title element no matter what their value is, but sometimes you will want to find elements with a specific attribute which has a specific value.

Find elements with a specific value for a specific attribute


Here's an example where we find elements with a specific value:

<a href="http://www.google.com" target="_blank">Link 1</a><br />
<a href="http://www.google.com" target="_self">Link 2</a><br />
<a href="http://www.google.com" target="_blank">Link 3</a><br />

<script type="text/javascript">
$(function()
{
        $("a[target='_blank']").append(" [new window]");
});
</script>

The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value "_blank" and then append the text "[new window]" to them. But what if you're looking for all elements which don't have the value? Inverting the selector is very easy:
$("a[target!='_blank']").append(" [same window]");

The difference is the != instead of =, a common way of negating an operator within many programming languages.

And there's even more possibilities:

Find elements with a value which starts with a specific string using the ^= operator:
$("input[name^='txt']").css("color", "blue");

Find elements with a value which ends with a specific string using the $= operator:
$("input[name$='letter']").css("color", "red");

Find elements with a value which contains a specific word:
$("input[name*='txt']").css("color", "blue");

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

Sunday, 16 October 2011

The Best jQuery Plugins Inspired from Facebook and Twitter

jQuery Plugins For Twitter


jQuery plugin for Twitter


A simple, unobtrusive and customisable client-side method for easily embedding a Twitter feed into a web page. You can add alternative content to the container element. This will be replaced by your tweets when the plugin is executed by jQuery. 3 new customisation options: slideDuration (if slideIn is true, this will change the duration of the slide effect), showProfileLink (set to false if you want to hide the link), showTimestamp (set to false if you want to remove the timestamp from tweets – the timestamp is then added as a title on the individual tweet list items).

jQuery plugin for Twitter

jQuery Twitter API plugin


Plugin provides you with an easy Twitter API to access Twitter user information by twitter username. The first parameter is a Twitter username and the second is a callback function that will be called after jQuery gets user details from the Twitter servers.

Twitter API plugin

Making Our Own Twitter Timeline


With this plugin and tutorial you will create your own twitter-like timeline, where you can view and post your tweets. You can use the code that you can find on tutorial page for all kinds of purposes and be sure that the possibilities are endless.

Twitter Timeline

A Twitter List Powered Fan Page


Recently, Twitter rolled out a great new feature on their site – lists. You can now create and compile a list of twitter users and make it easier for others to follow all at once. Also, at the same time, they expanded their API to include list management functionality. This allows us to use these new tools to create a widget that flips lists the other way around – a fan page you can put in your sidebar, that allows your visitors to fill in their twitter name and join a specially crafted fan list in your twitter account.

Twitter List

Twitter Friends & Followers Widget – A jQuery Plugin


There is a Facebook fans widget, Google friends widget, what about a Twitter friends widget?! Here is a jQuery plugin that you can embed anywhere to display pictures of your Twitter followers or friends (whom you follow) and their latest tweets if you like. By featuring your Twitter friends or followers on your blog, you will encourage others to become friends too..

Twitter Friends Followers Widget

Who-Tweet Button : Fancy jQuery Plugin for Twitter


Author took the Topsy retweet button and jQuery-fied it, then added the “Who” part to it using the awesome Topsy API. To create this fancy share count button for your stories on twitter. that’s it! The Who part is about attributing the people who tweet your story by showing their Twitter pictures inside the retweet button. Topsy keeps a completehistory about Twitter trackbacks of your links which Author utilized in another jQuery plugin.

Who-Tweet Button

A jQuery Twitter Ticker


In this tutorial Author are going to create a pure jQuery & CSS twitter ticker which utilizes Twitter’s Search API. It will show your or your friends’ latest tweets, and will not require any server side code or databases. As a result, the ticker will be easily included into any web page and easily modified to your likings.

Twitter Ticker

Twit – Display Twitter Tweets on a Blog


Twit is a jQuery Plugin to Display Twitter Tweets on a Blog.

Display Twitter Tweets

Tweetquote


A simple JavaScript plugin, that pulls the latest Twitter Tweets, based on your search terms, and shows them on your website.

tweetquote

jQuery LiveTwitter


Lightweight, live updating Twitter search plugin for jQuery. LiveTwitter is a lightweight, live updating Twitter search plugin for jQuery.

jQuery LiveTwitter

Juitter


Juitter has a live mode which can display the latest tweets with an Ajaxed interface. It can display tweets from/to a user and containing any keywords. Optionally, this jQuery Twitter plugin can display the avatars & can be styled easily with CSS.

Juitter

Tweetable – A jQuery plugin


Tweetable is a lightweight jQuery plugin which enables you to display your twitter feed on your site quickly and easily. More than just displaying the feeds you can highlight @replys as well as links being dynamically generated for ease of use.

Tweetable

Veetter


Veetter is a jQuery Twitter plugin that allows you to easily display your tweets on your own site or blog.

Veetter

Realtime Related Tweets Bar: Another jQuery Plugin


Put up instant tweets related to a content of your choice with the Realtime Related Tweets Bar.

Realtime Related Tweets Bar

Tweet – jQuery plugin for Twitter


Put twitter on your website with tweet!, an unobtrusive javascript plugin for jquery.

jQuery plugin for Twitter

Facebook inspired jQuery plugins


Facebox


Facebox is a jQuery-based, Facebook-style lightbox which can display images, divs, or entire remote pages. It’s simple to use and easy on the eyes. Download the tarball, view the examples, then start enjoying the curves.

Facebox

Tipsy – Facebook-style tooltip plugin for jQuery


Tipsy is a jQuery plugin for creating a Facebook-like tooltips effect based on an anchor tag’s title attribute.

Facebook-style tooltip plugin

FCBKcomplete


Fancy facebook-like dynamic inputs with auto complete & pre added values.

FCBKcomplete

jQuery Plugin: Tokenizing Autocomplete Text Entry


This is a jQuery plugin to allow users to select multiple items from a predefined list, using autocompletion as they type to find each item. You may have seen a similar type of text entry when filling in the recipients field sending messages on facebook.

Tokenizing Autocomplete Text Entry

Facybox


A jQuery-based, Facebook/Fancybox-style lightbox which can display images, divs, or entire remote pages. It’s simple to use and easy on the eyes. Fancybox is great, but programmatically dealing with it is hard (you have to create an element on the fly and trigger a click on it).

facybox

Facebook Style Alert Confirm Box with jQuery and CSS


Author had designed Facebook Style Alert Confirm Box with jquery plug-in jquery.alert.js. It’s simple just changing some line of CSS code.

Facebook Style Alert Confirm Box

Facebook like Autosuggestion with jQuery, Ajax and PHP


Do you want know how to implement Autosuggestion search with jquery. Author had developed Facebook like Autosuggestion user search with jQuery, Ajax and PHP. It’s simple and clean just you have to change the database details.

Facebook like Autosuggestion

Creating a Facebook-like Registration Form with jQuery


Facebook is a showcase of great UI design. And as it has become a major part of our lives, it has also raised the bar for web development, pushing developers to meet higher expectations. This however has a good side – it challenges web developers and designers to better themselves and constantly improve their work. In this tutorial, we are going to learn from the best, and create a facebook-like sign up form.

Facebook-like Registration Form with jQuery

Ajaxflagmenu


AjaxFlagMenu is a simple vertical menu developed JavaScript, design is inspired from a social website Facebook, this menu is dynamically through functionality of Ajax by the XMLHttpRequest object.

ajaxflagmenu

FcbkListSelection


FcbkListSelection – fancy item selector (like facebook friends selector) with wide range of options.

FcbkListSelection

Facebook Like Datetime Picker – Jquery Plugin


Jquery provide datetime picker UI that really awesome. And many other developer like to develop datetime picker like that. But sometime we need a simple style that match with our website style. And we can see it on Facebook Login page. And Author inspired by that create simple datetime picker with Jquery. It is a very simple plugin and maybe usefull for simple interface too.

Facebook Like Datetime Picker – Jquery Plugin

Facebook Style jQuery Chat


This jquery chat implements all those features of gmail or facebook chat. Its so simple to integrate into your website.


Elastic


This Jquery plugin makes your textareas grow and shrink to fit its content. It was inspired by the auto growing textareas on Facebook. The major difference between Elastic and its competitors is its weight.

Elastic

jQuery Plugin : edit Image FaceBook Style


Author first jQuery Plugin – the FaceBook Style Image Editing jQuery Plugin. It is not so hard after all. This will add a link when hover on image. For instance, if you hover on your profile image on facebook. This Plugin meanwhile works on Div only.

Image FaceBook Style

Boxy


Boxy is a flexible, Facebook-style dialog box for jQuery with support for dragging and size tweening. It differs from other overlays I’ve seen by providing an object interface to control dialogs after they’ve been created. And for simple usage scenarios, boxy also provides a jQuery plugin for automatically hooking up links and forms, as well as an ask() helper for presenting multiple choices to the user.

Boxy
Enhanced by Zemanta

Tuesday, 30 August 2011

Facebook Style CSS JQuery drop down menus



Now a days drop down menus are becoming more and more popular. They arebeing used in  most modern websites like facebook, gmail, gplus, orkut, gmail, yahoo...

There is no secret that they are using JQuery and HTML to implement the above feature.

Even you can do this by writing some very simple code.

 

       

 

 

 

 

Step-1:

Lets write our HTML code.
<div style="height:300px;">
            <div style="width:162px;">
                <dl style="">
                   <dt>
                   <a class="" id="linkglobal"
                   style="cursor: pointer;"></a></dt>
                    <dd>
                        <ul style="display: none;" id="ulglobal">
                            <li><a href="#">Everyone</a></li>
                            <li><a href="#">Friends</a></li>
                            <li><a href="#">Only Me</a></li>
                            <li><a href="#">Customize</a></li>
                      </ul>
                   </dd>
                </dl>
            </div>
        </div>

Step-2:
The next step is to add some CSS which will further stylize the menu
which is going to look just like facebook.
<style type="text/css">

    *{
        padding:0;
        margin:0;
    }

    body{
        color: #333333;
        direction: ltr;
        font-family:
        "lucida grande",tahoma,verdana,arial,sans-serif;
        font-size: 11px;
        text-align: left;
    }

/* Grey Small Dropdown */

/* General dropdown styles */
.dropdown dl{ margin-left:5px; }
.dropdown dd, .dropdown dt, .dropdown ul
{ margin:0px; padding:0px; }
.dropdown dd { position:relative; }

/* DT styles for sliding doors */
.dropdown dt a {background:#EEEEEE
url(privacyOff.png) no-repeat scroll right center;
    display:block; width:40px; height:22px; cursor:pointer;}

.dropdown dt a.selected{
    background:#EEEEEE url(privacyOn.png)
    no-repeat scroll right center;
}
.dropdown dt a span {
cursor:pointer; display:block; padding:5px;}

/* UL styles */
.dropdown dd ul {
background:#EEEEEE none repeat scroll 0 0; display:none;
    list-style:none; padding:3px 0; position:absolute;
    left:0px; width:160px; left:auto; right:0;
    border:1px solid #656565; cursor:pointer;
    }
.dropdown dd ul li{
background-color:#EEEEEE; margin:0; width:160px;
}
.dropdown span.value { display:none;}
.dropdown dd ul li a {
display:block; font-weight:normal; width:137px;
text-align:left; overflow:hidden; padding:2px 4px 3px 19px;
color:#111111; text-decoration:none;
}
.dropdown dd ul li a:hover{
background:#656565; color:white; text-decoration:none;
}
.dropdown dd ul li a:visited{
text-decoration:none;
}
</style>

Step-3 :

Now lets include the JQuery into our webpage and start writing the necessary JQuery function calls.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".dropdown dt a").click(function() {

// Change the behaviour of onclick states for links within the menu.
var toggleId = "#" + this.id.replace(/^link/,"ul");

// Hides all other menus depending on JQuery id assigned to them
$(".dropdown dd ul").not(toggleId).hide();

//Only toggles the menu we want since the menu could be showing and we want to hide it.
$(toggleId).toggle();

//Change the css class on the menu header to show the selected class.
if($(toggleId).css("display") == "none"){
$(this).removeClass("selected");
}else{
$(this).addClass("selected");
}

});

$(".dropdown dd ul li a").click(function() {

// This is the default behaviour for all links within the menus
var text = $(this).html();
$(".dropdown dt a span").html(text);
$(".dropdown dd ul").hide();
});

$(document).bind('click', function(e) {

// Lets hide the menu when the page is clicked anywhere but the menu.
var $clicked = $(e.target);
if (! $clicked.parents().hasClass("dropdown")){
$(".dropdown dd ul").hide();
$(".dropdown dt a").removeClass("selected");
}});
});
</script>