Animated Sharing Bar With jQuery & CSS

22 January 2010 Friday

This application was viewed 1695 times




Animated Sharing Bar With jQuery & CSS

Social networks can make a big difference on the popularity of a blog. Sites that communicate better and understand social media are usually the most popular.

A move towards this goal would be to find a way to encourage your visitors to share your content on the networks they are most active on.

Today we are doing just that, by using pure JavaScript with the jQuery framework, to make an animated sharing bar, which will enable your website visitors to share posts on a number of social networks.

Go ahead and download the demo files and continue with step one of this tut.

View The DEMO

Step 1 – XHTML

As usual, we start off with the XHTML markup. The sharing area is constructed by using three main div containers:

  • #share – this element acts as a container which holds the other two. It also has some CSS3 properties applied, such as rounded corners;
  • #stage – this is where the animation takes place. On page load jQuery detects the horizontal and vertical centers and uses them to position the rotating divs. It is also floated to the left;
  • #share-label – this has the “share the love” image as a background. It is also floated to the left and thus positioned right next to the #stage div.

But lets have a detailed look:

demo.html

01.<div id="share">
02.<div id="stage">
03.  
04.<div class="btn digg"><div class="bcontent"><a class="DiggThisButton"></a><script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></div></div>
05.<div class="btn tweetmeme"><div class="bcontent"><script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script></div></div>
06.<div class="btn dzone"><div class="bcontent"><script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script></div></div>
07.<div class="btn reddit"><div class="bcontent"><script type="text/javascript" src="http://www.reddit.com/button.js?t=2"></script></div></div>
08.<div class="btn facebook"><div class="bcontent"><a name="fb_share" type="box_count" href="http://www.facebook.com/sharer.php">Share</a><script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script></div></div>
09.  
10.</div>
11.  
12.<div id="share-label">
13.<!-- This is where the share some love image appears -->
14.</div>
15.  
16.</div>

The code above is all you need to add to your page (in addition to the js and css files), so you can show the animated bar below your articles.

Each button has a generic btn class and an individual one (digg, tweetmeme, etc). This makes it possible to gather the common rules shared by the buttons in a single class and make it easier to customize at a later time.

Also notice that inside of each of the button divs, there is an individual JavaScript file that actually generates the button on the page. Those are provided by the social networks and usually display the button exactly where the script tag is inserted.

Now lets see how these elements are styled.

Step 2 – CSS

I’ve divided the CSS code into two parts.

demo.css – Part 1

01.#share{
02.    /* The share box container */
03.    width:500px;
04.    background:#ececec;
05.    height:220px;
06.    margin:60px auto;
07.    overflow:hidden;
08.  
09.    -moz-border-radius:12px;
10.    -webkit-border-radius:12px;
11.    border-radius:12px;
12.}
13.  
14.#share-label{
15.    /* The image on the right */
16.    background:url(img/share.png) no-repeat 50% 50%;
17.    float:left;
18.    height:220px;
19.    width:200px;
20.}
21.  
22.#stage{
23.    /* This is where the animation takes place */
24.    position:relative;
25.  
26.    border-right:1px solid #DDDDDD;
27.    width:290px;
28.    height:220px;
29.    background:white;
30.    float:left;
31.  
32.    border-bottom-left-radius:12px;
33.    border-top-left-radius:12px;
34.  
35.    -moz-border-radius-bottomleft:12px;
36.    -moz-border-radius-topleft:12px;
37.  
38.    -webkit-border-bottom-left-radius:12px;
39.    -webkit-border-top-left-radius:12px;
40.}
41.  
42..btn{
43.    /* This class is assigned to every share button */
44.    background-color:white;
45.    height:90px;
46.    left:0;
47.    top:0;
48.    width:60px;
49.    position:relative;
50.    margin:20px 0 0 10px;
51.    float:left;
52.}
53.  
54..bcontent{
55.    /* Positioned inside the .btn container */
56.    position:absolute;
57.    top:auto;
58.    bottom:20px;
59.    left:0;
60.}

Maybe at this stage you are wondering how the actual buttons are animated in a circular movement on the page.

A major part of the technique takes place inside the #stage CSS class above. The stage itself is relatively positioned, which enables the buttons (which have absolute positioning assigned by jQuery below, and are direct descendants) to be positioned accordingly.

This means that setting top and left to zero on the buttons, positions them in the top-left corner of the stage.

You’ll see the rest of the technique in step 3.

demo.css – Part 2

01./* Individual rules for every share button */
02.  
03..digg{  background:url(img/digg_reflection.png) no-repeat -4px bottom;}
04..reddit{    background:url(img/reddit_reflection.png) no-repeat -4px bottom;}
05..facebook{  background:url(img/facebook_reflection.png) no-repeat bottom center;}
06..tweetmeme{ background:url(img/twit_reflection.png) no-repeat -5px bottom;}
07..dzone{ background:url(img/dzone_reflection.png) no-repeat -7px bottom;}
08.  
09..thanksto{
10.    position:absolute;
11.    bottom:2px;
12.    right:4px;
13.    font-size:10px;
14.}
15.  
16..thanksto a,.thanksto a:visited{
17.    color:#BBB;
18.}
19.  
20./* Customizing the facebook share button */
21.  
22.span.fb_share_no_count {
23.    display:block;
24.}
25.  
26.span.fb_share_count_top.fb_share_no_count {
27.    line-height:54px;
28.}
29.  
30.span.fb_share_count_nub_top.fb_share_no_count{
31.    display:none;
32.}
33.  
34.span.fb_share_no_count span.fb_share_count_inner {
35.    background:#3B5998 url(http://static.fbshare.me/f_only.png) no-repeat scroll 20px 5px;
36.    display:block;
37.}

In the second part of the style sheet, we assign individual rules to each button which define a unique background image with the reflection. After this we customize the facebook button, so that its styling matches the rest of the buttons.

With this we can continue with step 3.

Step 3 – jQuery

With the speed with which modern browsers render JavaScript, it gets easier to make eye-catching animations, previously reserved only for technologies as Adobe Flash.

But before getting down to work, we need to include two  script files in the head of our page:

1.<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
2.<script type="text/javascript" src="script.js"></script>

The first one includes the jQuery library from Google’s CDN, and the second line includes our own script.js file, covered in detail below:

script.js

01.$(document).ready(function(){
02.  
03.    /* This code is run on page load */
04.  
05.    var deg=0;
06.    var dif=-3;
07.  
08.    /* Assigning the buttons to a variable for speed: */
09.    var arr = $(´.btn´);
10.  
11.    /* Caching the length of the array in a vаriable: */
12.    var len = arr.length;
13.  
14.    /* Finding the centers of the animation container: */
15.    var centerX = $(´#stage´).width()/2 - 40;
16.    var centerY = $(´#stage´).height()/2 - 60;
17.  
18.    /* Applying relative positioning to the buttons: */
19.    arr.css(´position´,´absolute´);
20.  
21.    /* The function inside the interval is run 25 times per second */
22.    setInterval(function(){
23.  
24.        /* This forms an area with no activity on mouse move in the middle of the stage */
25.        if(Math.abs(dif)<0.5) return false;
26.  
27.        /* Increment the angle: */
28.        deg+=dif;
29.  
30.        /* Loop through all the buttons: */
31.        $.each(arr,function(i){
32.  
33.            /* Calculate the sine and cosine with the new angle */
34.            var eSin = Math.sin(((360/len)*i+deg)*Math.PI/180);
35.            var eCos = Math.cos(((360/len)*i+deg)*Math.PI/180);
36.  
37.            /* Setting the css properties */
38.            $(this).css({
39.                top:centerY+25*eSin,
40.                left:centerX+90*eCos,
41.                opacity:0.8+eSin*0.2,
42.                zIndex:Math.round(80+eSin*20)
43.            });
44.        })
45.    },40);
46.  
47.    /* Detecting the movements of the mouse and speeding up or reversing the rotation accordingly: */
48.    var over=false;
49.    $("#stage").mousemove(function(e){
50.  
51.        if(!this.leftOffset)
52.        {
53.            /* This if section is only run the first time the function is executed. */
54.            this.leftOffset = $(this).offset().left;
55.            this.width = $(this).width();
56.        }
57.  
58.        /* If the mouse is over a button, set dif to 0, which halts the animation */
59.        if(over) dif=0;
60.        else
61.            dif = -5+(10*((e.pageX-this.leftOffset)/this.width));
62.  
63.        /* In the other case calculate the speed according to the X position of the mouse */
64.    });
65.  
66.    /* Detecting whether the mouse is positioned above a share button: */
67.    $(".bcontent").hover(
68.        function(){over=true;dif=0;},
69.        function(){over=false;}
70.    );
71.});

The main idea here, is that we use setInterval to set up a function to be run every 40 milliseconds. This means that it is run 25 times a second, or if you compare it with a movie screen, this is 25 frames per second. In other words more than enough to display a smooth animation (providing that the rendering speed of the browser is fast enough, and that there are no other scripts interfering).

As this is not a computation-heavy animation, it runs pretty smoothly on all browser versions (even as old as IE6). However, the smoothest animation I’ve observed is in Safari and Chrome (it would run nicely in Firefox too, providing that you don’t have a lot of add-ons or opened tabs).

You can see throughout the code above, that I tend to assign the results of jQuery selectors or other functions to variables. This is done to improve the speed of the script, otherwise all those functions and methods would be calculated on every frame (for a total of 25 times per second) which would ultimately bring down the performance and smoothness of the animation.

With this our animated sharing bar is complete!

Tags: css, jquery, bar, sharing,


Animated Sharing Bar With jQuery & CSSBookmark and Share

Comments

  • lancelsacs lancelsacs

    2013-01-16 08:27:08

    sac lancel french flair

    Avant de semelles orthopédiques affaires, il est vraiment bon de faire valoir sortie de sac Lancel podiatres baldest semelles appropriées qui tiennent meilleurs auspices et l'abondance pour les pieds. Même en admettant qu'ils peuvent être coûteux, l'acceptation de l'artefact a augmenté en raison de ses récompenses. Le caractère absolu est naïvement pas une paire de porte-monnaie regard de la même précision. Ces additifs ne sont pas réellement toute prise de soldes sac lancel sur l'Internet seul contemporaine si theyre absolument capables de plus. Ils seront Lancel sacs sont fournis central d'un vaste choix de couleurs pour archétype ciel bleu, rose bonbon, bleu abyssal, l'étain, de l'environnement s'applique affable vient de magenta. Lancel sacs comme valides se pose dans foisonnant sortes et ainsi le champ d'application de l'ajustement pour amuser chaque demande. soldes lancel sac à accepter la dernière tendance à la mode, vous pouvez accréditer magazines d'actualisation ou de chercher des sites actualisation assorties. Son adaptée aux articles séquelles accessibles et sac Lancel traitement des dossiers apparaissent désirs affiliés hydrates de Lancel french flair sous large adhésion à l'exportation de presque anniversaire de l'accession au faddy en matériaux, formes, modèles, l'adhésion à l'exportation sac lancel en solde pas chers pansement et aussi vous pouvez visualiser. Lieu de travail, sous porte-monnaie large, c'est si vous admirez dans l'adhésion à des bracelets faddy. En outre, il s'agit du meilleur moment de l'année pour nous offrir des cadeaux. Donnant le cadeau n'est pas seulement une approche de la création des amis mais aussi de comprendre pour nous d'apprendre. Beaucoup de gens sages compléter ou améliorer les vente privée Lancel élégant à leurs copains.

    http://www.lancel-fr.com/

  • coachbag coachbag

    2013-01-03 09:39:31
    http://www.coachoutletonlinenusa.com/ Coach Outlet Online Coach Outlet
    http://www.coachxfactoryoutletonline.com/ Coach Factory Online
    http://www.coachespursesoutletonline.net/ Coach Outlet Online
    http://www.coachscoachoutlet.net/ Coach Outlet coachfactory.com/shop
    http://www.vip-coachbags2013.net/ Coach Outlet Coach Store Online
    http://www.usacoachefactoryoutlet.com/ Coach Factory Outlet
    http://www.coachsfactoryonline.com/ Coach Factory Outlet Online
    http://www.thecoachoutleto.com/ Coach Outlet Coach Bags Outlet
    http://www.buyccoachfactory.com/ Coach Factory Coach Factory Outlet
    http://www.coachoutletonlineebay.com/ Coach Outlet Coach Factory Outlet
    http://www.michaelkorsusaonlines.com/ Michael Kors USA Michael Kors Outlet Online
    http://www.shopoguccishoes.com/ Gucci Shoes UK Gucci Mens Shoes
    http://www.mk-michaelkorsoutlets.net/ Michael Kors Outlet Michael Kors
    http://www.michaelkorsoutlettoyou.net/ Michael Kors Michael Kors Factory
    http://www.the-michaelkorsoutlets.net/ Michael Kors Outlet Michael Kors Outlet Online
  • cc xu

    2012-12-23 06:07:42
    XTT-日本でのNO.1人気あるダウンジャケットブランド----モンクレール!冬の日本、一番はやってるクリスマスプレゼントはもちろんモンクレール ダウンです。モンクレール アウトレットの店はさまざまなデザインがあり、値段安いし質も保証あります。さらに今、Moncler アウトレットの店は運賃なしです!クレジットカ—ドで注文したら、十日内には注文した商品は必ず届けます。こんなに安くて便利なショッピング、迷わず買いましょう!
    Louis Vuitton Bags is the history of France's most outstanding leather,in Paris in 1854 opened the first suitcase louis vuitton sale shop name in its own brand.Over the past century has been to advocate refined,quality,comfortable "travel philosophy",starting as a design basis.louis vuitton outlet the name has now spread throughout Europe,became a symbol of the finest travel products.louis vuitton bags outlet store's goods sold to all over the world,quality is guaranteed,and the audience free postage.If you do not want a good Christmas gift,then hurry to the louis vuitton bags on sale store to order it.
    Moncler Outlet enduring mid-renovation and refurbishment,the set dressing style people prefer leisure,moncler jackets will always be the best choice.Design without too pompous,or to totally practical concise styleattractive,neat concise leisure wind consumers can not miss the moncler.In the cold winter,if you do not have a favorite down jacket,moncler outlet store will certainly be your favorite style.
    Are you ready to send what gift in this Christmas?Maybe we can give you some advice.louis vuitton outlet are amazing shopping site in this world,because through it,you can bought the louis vuitton bags in an incredible price,maybe a new way to get Louis Vuitton Handbag,that is louis vuitton online store,as I understand they take the bag from Louis vuitton factory,no tax,no house rent,no compete,these make the price lower then louis vuitton shop,so why not shop the louis vuitton online,amazing Louis Vuitton handbag are belong to you.
    If you are worried for Christmas gift,hermes bags may be a good choice,as the world’s most expensive brand,if you have one, that must stand that you are a good station person in your country, Hermes is famous of it’s hermes handbags,as the hermes handbag’s high qulity and best design, maybe the price is the best in the world.Two series of hermes is popular,that is hermes kelly bags,and hermes birkin bags,this two series make Hermes more popular, so visit our site to get your love.
    What should you send gift in christmas?hermes handbags is waiting for you.Maybe Hermes Handbags is very expensive,but you will be interisted in our replica hermes handbags,we have hermes birkin bags,Hermes Kelly Bags and so on,all of them is quality assured and beautiful,so buy hermes bags on our site,amazing surprise is waiting for you.
  • af jj

    2012-11-03 02:55:26
    ZBY-

    Christmas is coming!coach outlet is also coming this world now!Coach bags,most famous brand in usa,also the world,why are coach spread so wide,that is because cheap with fashion,the reason why is so cheap because coach always have coach outlet online,we are the online store of coach bags,and they take their product all is from coach factory outlet,no tax no room rent is the advance of coach outlet online store,so come and shopping us now,beautiful bag are waitting for you.
    Are you ready to send what gift in this Christmas?Maybe we can give you some advice.louis vuitton outlet are amazing shopping site in this world,because through it,you can bought the louis vuitton bags in an incredible price,maybe a new way to get Louis Vuitton Handbag,that is louis vuitton online store,as I understand they take the bag from Louis vuitton factory,no tax,no house rent,no compete,these make the price lower then louis vuitton shop,so why not shop the louis vuitton online,amazing Louis Vuitton handbag are belong to you.
    If you want to buy coach for a christmas gift,you can go to our store online.coach outlet is cheapest mall to bought coach bags.as a famous brand in the world,have discount is a incredible thing.Find online store is a new way to get Coach Bags,coach outlet online obviously is a perfect way to get it,in this winter are you really ready to be a fashion women,usa coach outlet will help you,so join us now!coach outlet store online wating for you comeing!
    If you are worried for Christmas gift,hermes bags may be a good choice,as the world’s most expensive brand,if you have one, that must stand that you are a good station person in your country, Hermes is famous of it’s hermes handbags,as the hermes handbag’s high qulity and best design, maybe the price is the best in the world.Two series of hermes is popular,that is hermes kelly bags,and hermes birkin bags,this two series make Hermes more popular, so visit our site to get your love.
    A lot of people want to get a beautiful Coach Bag in christmas.Where can we buy coach bags? A lot of people choose to go to coach outlet store online.All products what sale in coach outlet online are top quality and low price.We promise you to recieve your buy about 5~7days. usa coach outlet directly sell for customers.Do you want to free to buy Coach Bags in your home?Please click coach outlet.
    belstaff jackets is the most popular winter brand in the world,if you don't know,that means you out.belstaff coat is famous of its high-level material and fahisonable design,so that's why so many people choose Belstaff to though the cold winter.Nowaday surffing the internet is the lifestyle of most people,but have you bought things on the internet,I introduce you to try to buy things in the internet,because you can buy belstaff sale on the internet,that way you can get big discount than in reality world,in the brand belstaff trialmaster series is the hottest,this series suit for all kinds of people,whatever you like,whatever you are,you suit it.
    Why buy coach bags from us? Because we have all kinds of Coach products,and these products are high quality and low price.coach factory provide the most perfect service, your order will arrive about 5~7days.Free shipping any order of $99+.Go shopping in people's eyes is women's patent as if .Now a new choice for women is going to coach factory online.If you want to buy Coach Poppy Bag or Coach Wallet, but don't want to go out, coach factory outlet must be your best choice.Are you still hesitate? To click on your mouse to choose your like.
    What should you send gift in christmas? hermes handbags is waiting for you.Maybe Hermes Handbags is very expensive,but you will be interisted in our replica hermes handbags,we have hermes birkin bags,Hermes Kelly Bags and so on,all of them is quality assured and beautiful,so buy hermes bags on our site,amazing surprise is waiting for you.
    On the eve of Christmas comes, coach factory outlet also provide to the most preferential price at this time. coach outlet olinehave many beautiful products, there must be your like.Such Coach bags,Coach sunglass,Coach wallet and so on.Free shipping for any order of $99+.our store will give you a nice present.coach outlet must be Shopping paradise what you want to go.
    What should we buy winter clothes?I think a moncler jackets is necessaery,online moncler is a good way to get a perfect Moncler.Moncleris famous of it amazing qulity and it's consummate manual work,when you ware it,you will feel warm,whatere how cold the winter is,Moncler can take care of your body.Our online store afford latest moncler coat,so in the cold winter you can also fashion and attractive,so visit our moncler online shop,it will take you a warm winter.

You write your thoughts

Please login to post comments here from the right corner.

your add
icon free icon icon set vector icon free catalog catalog template jquery news ticker widget tools tutorial php slider video youtube effects menu thumbnail forms facebook zoom image combo multiselect modal polaroid gallery expand code feedback contact navigation slider tagcloud Skateboard psd templates files badges subscribe panel login temlate file free office holland free template tabs prototype css scriptaculous opacity moo autocomplete wordpress themes design theme button images photoshop fonts font nav pdf logo style high javascript pretty photo jqery lightbox Themes Blog popular blog desing joomla xhtml brushes hair footer admin mootols slide show blackbox new download class first plugin upload browse Page effect modalbox web application urlitooltips sliding boxes captions flatchat chat ajax messaging browser hoverlightbox CSS Dev General Javascript PHP SQL search avatar vector Drupal Joomla Oscommerce javaScript phototype manager ajaxplorer flash xml rotator bookmarking pageflip slideshow poll text component script mediaplayer imagegallery pictograms car poster player mp3 radio onlineradio navigations drop-down collection brush tree textures paper pop-up bumpbox web2.0 iphone film frame twitter page fan mail delete dynamic calender form handbook city social paint timeline clock connect bar sharing accordion quotes ticker photo-effects background 3D media player graphic rss leaf green glossy bubble icon comic clean cool web 2.0 png actionscript ietter rotating Menu animated textured site masking pasword app layer sponge bob popup bubble tooltips horizontal prototip tooltip pack charachters comics blog action icon.psd flavour navi tango gradients istanbul mixed css3 sleek animations program html5 website Layer styles ultimate candy Media icons dropdown snow icon innerfade hover sub tag