Animated Notification bubble icon with CSS3 keyframe animation

The other day, while working on a web project, I had to emphasize somehow a dynamic notification bubble. Basically, every time the notification value changes, a visual effect was needed in order to get user’s attention. So I made that using CSS3 keyframe animation.

notification-bubble-animation

The HTML

For this example, we’ll borrow the markup structure and look from my CSS3 dropdown menu.

<ul>
    <li><a href="">Dashboard</a></li>
    <li><a href="">Friends</a></li>
    <li>
    	<a href="">Message
    		<span>9</span>
    	</a>
    </li>
    <li><a href="">Games</a></li>
    <li><a href="">Settings</a></li>
</ul>

The focus will be on the <span>, which is the notification bubble that will be animated.

The CSS

The .animating class represents an CSS3 animation that uses a bezier curve.

.animating{
	animation: animate 1s cubic-bezier(0,1,1,0);			
}

@keyframes animate{
	from {
	   transform: scale(1);
	}
	to {
	   transform: scale(1.7);
	}
}

The jQuery

It’s not as easy as you might think to restart an animation and Chris Coyier wrote a good article about it.

The method I chose for this example involves using JavaScript’s setTimeout() method. So, every time the notification value changes, the .animating class is removed after a second (exactly how long the proper animation lasts).

In production, you will not need the counterValue variable. This is used just for our working example in order to be able to increment and decrement the notification value.

var counterValue = parseInt($('.bubble').html()); // Get the current bubble value

function removeAnimation(){
	setTimeout(function() {
		$('.bubble').removeClass('animating')
	}, 1000);			
}

$('#decrease').on('click',function(){
	counterValue--; // decrement
	$('.bubble').html(counterValue).addClass('animating'); // animate it
	removeAnimation(); // remove CSS animating class
})

$('#increase').on('click',function(){
	counterValue++; // increment
	$('.bubble').html(counterValue).addClass('animating'); // animate it
        removeAnimation(); // remove CSS animating class

view demo

Simple, but effective

I think this is a simple and practical example on how to use a CSS3 animation to enhance user experience. Further, you can experiment with the bezier curve values and come up with some other cool effects.

Thanks for reading and looking forward to read your thoughts!

Posted by: Dhiraj kumar

jQuery Plugin for Cartoon-like Background Image Sprite Animation – AniDG – (alernative to animated Gif)

What is AniDg?

AniDg is a simple plugin for jQuery which allows you animate background images. The plugin is basically an alternative to the animated GIF but with several benefits. At first, it’s always better to use an animated GIF as this format is supported by all browsers without any JavaScript code or additional markup, but the “dark side” of it is that an animated GIF allows only 256 colors and you cannot control animation in any way. The AniDg loads a long vertical image and changes its background position with the speed you setup, giving you more control of the animation. For Better quality you can call PNG, JPG, GIF images in background image sprite as per your requirements.

Demo

jQuery Plugin AniDG Background image animation

Features

  1. Light-weight script (Only 1Kb :))
  2. Easy to integrate
  3. Fully customizable via CSS
  4. Works with all modern browsers 🙂

How to Use

METHOD #1: EASY

Simply place the following code anywhere inside thetag of your webpage:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://demo.web3designs.com/jquery-ani.dg.min.js"></script>

METHOD #2: ADVANCED

STEP ONE: Download AniDg.zip or http://demo.web3designs.com/AniDg.zip. The package already contains all files used in this demo.

STEP TWO: Unzip and place the file jquery-ani.dg.min.js in the same location as the webpage that is displaying the animation. (Make sure paths to files are correct.)

STEP THREE: include the following code in the <head>…</head> section of your webpage:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery-ani.dg.min.js"></script>

3.) Add a style containing the url to your background with animation (this may be added to a separate CSS document or inside the <head>…</head> tag):

<style type="text/css">
#animation-1 {
background: url(images/sample-animation.gif) no-repeat left top;
}
</style>

4.) Add an empty DIV which will display animation in your document:

<div id="animation-1"></div>

5.) Add the following code to your <head>…</head> tag to initialize AniDg and start the animation.

<script type="text/javascript">
$(document).ready(function(){
$('#animation-1').anidg({ frameWidth: 100, frameHeight: 100, speed: 100, totalFrames: 19 });
$('#animation-1').anidg.play();
});
</script>

That’s it 😉 Click the Demo button to see it in action.

Public Functions

anidg.play()
Start playing animation.

anidg.pause()
Pause animation.

anidg.stop()
Stop animation.

Parameters

The table below contains a list of parameters accepted by the .anidg() function.

Parameters Description
frameWidth Width of a single frame.
frameHeight Height of a single frame.
speed Animation speed.
totalFrames Total frames in the animation.
loop Loop an animation or not. By default, value is true.

Posted by: Dhiraj kumar

How to create a simple CSS3 loading animation

While playing DIRT 3, I’ve noticed a very cool triangle animation as part of their UI. Almost immediately, I thought about how to build a similar version of it using CSS3.

So, in this article you’ll see an experiment about how to create a simple CSS3 loading animation.

css3-loading-animation

For this example, I’ll be using two CSS3 animations: one that fades the color for the triangles and one animation that rotates the whole design. These two animations, synchronized, will help creating a quite nice effect.

The HTML

Initially, I wanted to use pseudo-elements in order to have less markup elements.

Here’s how the markup looks like:

<div class="loading-wrap">
  <div class="triangle1"></div>
  <div class="triangle2"></div>
  <div class="triangle3"></div>
</div>

The CSS

There are some things you may find interesting here:

  • For a nice color fade across all three triangles, you need to increment the animation-delay.
  • Notice the gap between 20% and 100% for the rotation key-frames. This helps adding a stop effect for the animation.
.loading-wrap {
  width: 60px; height: 60px;
  position: absolute;
  top: 50%; left: 50%;
  margin: -30px 0 0 -30px;
  background: #777;
  animation: rotation ease-in-out 2s infinite;
  border-radius: 30px;
}

.triangle1, .triangle2, .triangle3 {
  border-width: 0 20px 30px 20px;
  border-style: solid;
  border-color: transparent;
  border-bottom-color: #67cbf0;
  height: 0; width: 0;
  position: absolute;
  left: 10px; top: -10px;
  animation: fadecolor 2s 1s infinite;
}

.triangle2, .triangle3 {
  content: '';
  top: 20px; left: 30px;
  animation-delay: 1.1s;
}

.triangle3 {
  left: -10px;
  animation-delay: 1.2s;
}

@keyframes rotation {
    0% {transform: rotate(0deg);}
    20% {transform: rotate(360deg);}
    100% {transform: rotate(360deg);}
}

@keyframes fadecolor {
    0% {border-bottom-color: #eee;}
    100%{border-bottom-color: #67cbf0;}
}

view demo

Browser support

Try using modern browsers like:

  • Chrome,
  • Firefox (Gecko),
  • Opera 12+,
  • Internet Explorer 10 or
  • Safari 5+.

Conclusion

This is an experiment and you must be aware of it. For now, I think an animated GIF will do the job better in most of cases.

Also, this isn’t that example that advocates for using CSS3 stuff instead images to save HTTP requests. It is not applicable here as limited browser support for CSS3 animations has something to say. Though, I hope you’ll find this example useful and inspiring for your future projects.

Thanks for reading and I’m looking forward to read your opinions!

Posted by: Dhiraj kumar

An Awesome CSS3 Animated Dropdown Menu

It’s a sure thing that CSS3 features like transitions, animations and transforms can add extra spice to your designs.

In this article you will see how you can build an awesome CSS3 animated dropdown menu with some of these cool features.  This is something I wished to do for a while and I finally made it. I just added support for smartphones / mobile devices and fixed the navigation for iPad and iPhone also.

css3-animated-dropdown-menu-preview

Here’s a quick preview for the CSS3 animated dropdown menu that we’re going to create today:

css3-menu-animation

The HTML

The HTML structure hasn’t changed at all, simple and minimal. Here’s an excerpt:

<ul id="menu">
        <li><a href="#">Home</a></li>
        <li>
                <a href="#">Categories</a>
                <ul>
                        <li><a href="#">CSS</a></li>
                        <li><a href="#">Graphic design</a></li>
                        <li><a href="#">Development tools</a></li>
                        <li><a href="#">Web design</a></li>
                </ul>
        </li>
        <li><a href="#">Work</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>
</ul>

The CSS

I revised and improved the styles in order to create this unique CSS3 animated dropdown menu. So, below you can find the commented pieces of styles:

Mini reset

Reset the default ul styles.

#menu, #menu ul {
        margin: 0;
        padding: 0;
        list-style: none;
}

Main level

The #menu is basically the main ul for this menu. CSS3 things like gradientsshadows and rounded corners help us to create the below:

css3-menu-wrapper

#menu {
        width: 960px;
        margin: 60px auto;
        border: 1px solid #222;
        background-color: #111;
        background-image: linear-gradient(#444, #111);
        border-radius: 6px;
        box-shadow: 0 1px 1px #777;
}

Clear floats

Here is Nicolas Gallagher‘s clearing method I’ve been using lately:

#menu:before,
#menu:after {
        content: "";

        display: table;
}

#menu:after {
        clear: both;
}

#menu {
        zoom:1;
}

List elements

css3-menu-elements

Please notice the #menu li:hover > a  selector. This is perhaps the most important CSS trick for this CSS3 dropdown menu.

So, this is how this works: Select an “a” element that is child of a “li” ; the “li” element must be a descendant of the “#menu”. Read more here.

#menu li {
        float: left;
        border-right: 1px solid #222;
        box-shadow: 1px 0 0 #444;
        position: relative;
}

#menu a {
        float: left;
        padding: 12px 30px;
        color: #999;
        text-transform: uppercase;
        font: bold 12px Arial, Helvetica;
        text-decoration: none;
        text-shadow: 0 1px 0 #000;
}

#menu li:hover > a {
        color: #fafafa;
}

*html #menu li a:hover { /* IE6 only */
        color: #fafafa;
}

Submenus

With CSS3 transitons we can animate changes to CSS properties like margin or opacity. This is very cool and I’ve used this for animating the CSS3 sub-menus. The result is great if you ask me:

css3-menu-animation

#menu ul {
        margin: 20px 0 0 0;
        _margin: 0; /*IE6 only*/
        opacity: 0;
        visibility: hidden;
        position: absolute;
        top: 38px;
        left: 0;
        z-index: 1;
        background: #444;
        background: linear-gradient(#444, #111);
        box-shadow: 0 -1px 0 rgba(255,255,255,.3);
        border-radius: 3px;
        transition: all .2s ease-in-out;
}

#menu li:hover > ul {
        opacity: 1;
        visibility: visible;
        margin: 0;
}

#menu ul ul {
        top: 0;
        left: 150px;
        margin: 0 0 0 20px;
        _margin: 0; /*IE6 only*/
        box-shadow: -1px 0 0 rgba(255,255,255,.3);
}

#menu ul li {
        float: none;
        display: block;
        border: 0;
        _line-height: 0; /*IE6 only*/
        box-shadow: 0 1px 0 #111, 0 2px 0 #666;
}

#menu ul li:last-child {
        box-shadow: none;
}

#menu ul a {
        padding: 10px;
        width: 130px;
        _height: 10px; /*IE6 only*/
        display: block;
        white-space: nowrap;
        float: none;
        text-transform: none;
}

#menu ul a:hover {
        background-color: #0186ba;
        background-image: linear-gradient(#04acec, #0186ba);
}

First and last list elements styles

css3-dropdown-first-last-items

#menu ul li:first-child > a {
        border-radius: 3px 3px 0 0;
}

#menu ul li:first-child > a:after {
        content: '';
        position: absolute;
        left: 40px;
        top: -6px;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        border-bottom: 6px solid #444;
}

#menu ul ul li:first-child a:after {
        left: -6px;
        top: 50%;
        margin-top: -6px;
        border-left: 0;
        border-bottom: 6px solid transparent;
        border-top: 6px solid transparent;
        border-right: 6px solid #3b3b3b;
}

#menu ul li:first-child a:hover:after {
        border-bottom-color: #04acec;
}

#menu ul ul li:first-child a:hover:after {
        border-right-color: #0299d3;
        border-bottom-color: transparent;
}

#menu ul li:last-child > a {
        border-radius: 0 0 3px 3px;
}

The jQuery

As you already get used to, IE6 gets some extra attention:

$(function() {
  if ($.browser.msie && $.browser.version.substr(0,1)<7)
  {
        $('li').has('ul').mouseover(function(){
                $(this).children('ul').css('visibility','visible');
                }).mouseout(function(){
                $(this).children('ul').css('visibility','hidden');
                })
  }
});

While the :hover pseudo-class does not work for other elements than anchor, we just need to add this small jQuery snippet to fix it. It’s pretty self-explanatory.

Update: Mobile navigation support

css3-mobile-dropdown

This is something I wished to do for a while and I finally made it. I just added support for mobile devices and fixed the navigation for iPad.

You know how much I love CSS only solutions, but this time we’ll be using some jQuery to enhance this menu. To view the result, you can narrow your browser window or browse it with your smartphone.

The viewport meta tag

To maintain everything at the correct scale, the first thing added is the viewport meta tag:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Small HTML update

You need to wrap the above HTML structure using something like: <nav id="menu-wrap">. This will be our relative holder for the mobile navigation.

The jQuery add

After page loads, we’ll add the #menu-trigger element which does exactly what you think: will trigger the mobile menu when it will be clicked. Further, in the CSS, you’ll see that this element is displayed using CSS3 media queries.

Another thing here is the iPad device detection. As you can see below, we’ll remove the fancy transition effect and stick to toggling display: none/block. This way, the functionality will be maintained also on the iPad.

/* Mobile */
$('#menu-wrap').prepend('<div id="menu-trigger">Menu</div>');
$("#menu-trigger").on("click", function(){
        $("#menu").slideToggle();
});

// iPad
var isiPad = navigator.userAgent.match(/iPad/i) != null;
if (isiPad) $('#menu ul').addClass('no-transition');

The mobile CSS

Here, the CSS3 media queries do the trick. We’ll add CSS rules to override the initial styles:

#menu-trigger { /* Hide it initially */
        display: none;
}

@media screen and (max-width: 600px) {

        #menu-wrap {
                position: relative;
        }

        #menu-wrap * {
                box-sizing: border-box;
        }

        #menu-trigger {
                display: block; /* Show it now */
                height: 40px;
                line-height: 40px;
                cursor: pointer;
                padding: 0 0 0 35px;
                border: 1px solid #222;
                color: #fafafa;
                font-weight: bold;
                background-color: #111;
                /* Multiple backgrounds here, the first is base64 encoded */
                background: url(data:image/png;base64,iVBOR...) no-repeat 10px center, linear-gradient(#444, #111);
                border-radius: 6px;
                box-shadow: 0 1px 1px #777, 0 1px 0 #666 inset;
        }

        #menu {
                margin: 0; padding: 10px;
                position: absolute;
                top: 40px;
                width: 100%;
                z-index: 1;
                display: none;
                box-shadow: none;
        }

        #menu:after {
                content: '';
                position: absolute;
                left: 25px;
                top: -8px;
                border-left: 8px solid transparent;
                border-right: 8px solid transparent;
                border-bottom: 8px solid #444;
        }       

        #menu ul {
                position: static;
                visibility: visible;
                opacity: 1;
                margin: 0;
                background: none;
                box-shadow: none;
        }

        #menu ul ul {
                margin: 0 0 0 20px !important;
                box-shadow: none;
        }

        #menu li {
                position: static;
                display: block;
                float: none;
                border: 0;
                margin: 5px;
                box-shadow: none;
        }

        #menu ul li{
                margin-left: 20px;
                box-shadow: none;
        }

        #menu a{
                display: block;
                float: none;
                padding: 0;
                color: #999;
        }

        #menu a:hover{
                color: #fafafa;
        }       

        #menu ul a{
                padding: 0;
                width: auto;
        }

        #menu ul a:hover{
                background: none;
        }

        #menu ul li:first-child a:after,
        #menu ul ul li:first-child a:after {
                border: 0;
        }               

}

@media screen and (min-width: 600px) {
        #menu {
                display: block !important;
        }
}       

/* iPad */
.no-transition {
        transition: none;
        opacity: 1;
        visibility: visible;
        display: none;
}

#menu li:hover > .no-transition {
        display: block;
}

view demo

Your turn

I hope you enjoyed this article and the techniques I used. Please share your comments and questions below!

Posted by: Dhiraj kumar

Fancy FAQ page using CSS3 only

Usually, a FAQ page is that long page with lots of questions and answers, the one we are searching for when we need some extra info regarding a subject. So, for example, if you own a website that sells stuff, then you will need a page like that.

In this article I’ll show you how to create a fancy FAQ page using CSS3 only, no JavaScript.

css3-faq-page

The idea

When I visited Facebook’s Help Center section (theirs FAQ’s), I noticed a cool effect for the answers previews. They show a small, faded and clipped text preview for the answer, and then, when the question is clicked, the complete answer is revealed.

After seeing it, of course I immediately thought about how can I create a similar effect using CSS3 only. So, further you’ll see how I made it.

The HTML

We will start as usual with the markup structure:

<section class="faq-section">
    <input type="checkbox" id="q1">
    <label for="q1">Question?</label>
    <p>... The intro paragraph that will be clipped ...</p>
    <p>... Extra and optional paragraph ...</p>
</section>

fancy-faq-page-using-css3-only-markup

  • In the above image, the label is the proper heading of the section. But, if you want to use better semantic, you can wrap the label into a h1.
  • Using label::before allow us to create the right triangle shape. On a side note, double colon for pseudo-elements is the CSS3 way.
  • The first paragraph for each section is the intro preview for the complete answer. For this example, I used the adjacent sibling combinator to target it.

How it works?

There’s no rocket science here. The technique we will use today is called the checkbox hack and it relies on the ability of toggle-ing an <input type="checkbox" id="abc"> using the<label for="abc">. Also, in the same time, the checkbox input will be hidden.

I played before with this cool technique, but never had the opportunity to create a practical example actually. So, this is my shot! 🙂

If you want to read more about this technique, Chris Coyier wrote a while ago an article where he shows some cool stuff you can do with the checkbox hack.

The CSS

Below you have the styles, I commented some lines for a better understanding:

/*Add some spacing*/
.faq-section{
        margin: 40px 0;
        position: relative;
}

/*Hide the paragraphs*/
.faq-section p{
        display: none;
}       

/*Hide the checkboxes */
.faq-section input{
        position: absolute;
        z-index: 2;
        cursor: pointer;
        opacity: 0;
        display: none\9; /* IE8 and below */
        margin: 0;
        width: 100%;
        height: 36px;
}

/*Show only the clipped intro */
.faq-section label+p{
        display: block;
        color: #999;
        font-size: .85em;
        transition: all .15s ease-out;
        /* Clipping text */
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
}

/*If the checkbox is checked, show all paragraphs*/
.faq-section input[type=checkbox]:checked~p{
        display: block;
        color: #444;
        font-size: 1em;
        /* restore clipping defaults */
        text-overflow: clip;
        white-space: normal;
        overflow: visible;
}

/*Style the label*/
.faq-section label{
        font-size: 1.2em;
        background: #eee;
        display: block;
        position: relative;
        height: 20px;
        padding: 7px 10px;
        font-weight: bold;
        border: 1px solid #ddd;
        border-left: 3px solid #888;
        text-shadow: 0 1px 0 rgba(255,255,255,.5);
        transition: all .15s ease-out;
}

/*Remove text selection when toggle-ing*/
.faq-section label::selection{
        background: none;
}

.faq-section label:hover{
        background: #f5f5f5;
}

/*If the checkbox is checked, style the label accordingly*/
.faq-section input[type=checkbox]:checked~label{
        border-color: #ff7f50;
        background: #f5deb4;
        background-image: linear-gradient(to bottom, #fff, #f5deb4);
        box-shadow: 0 0 1px rgba(0,0,0,.4);
}

/*Label's arrow - default state */
.faq-section label::before{
        content: '';
        position: absolute;
        right: 4px;
        top: 50%;
        margin-top: -6px;
        border: 6px solid transparent;
        border-left-color: inherit;
}

/*Update the right arrow*/
.faq-section input[type=checkbox]:checked~label::before{
        border: 6px solid transparent;
        border-top-color: inherit;
        margin-top: -3px;
        right: 10px;
}

Browser support

What about the older browsers? That’s a normal question, and the answer is graceful degradation:

fancy-faq-page-graceful-degradation

Using the following snippet, we’re targeting browsers like IE8 and below. So, we’ll enable the HTML5 elements like section and then add some custom styles in order to keep the FAQ’s content readable.

<!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <style>
                .faq-section label,
                .faq-section label:hover{
                        cursor: default;
                        background: #eee;
                }
                body .faq-section p{ /* Increase specificity */
                        display: block;
                        color: #444;
                        font-size: 1em;
                        text-overflow: clip;
                        white-space: normal;
                        overflow: visible;
                }
    </style>
<![endif]-->

Update: i0S support

You asked for it, now you have it: iOS browser support. I had some time to think about it and I made updates regarding hiding the checkbox.

Here’s my fix, tested on iPhone and iPad using the latest iOS versions:

.faq-section input{
        position: absolute;
        z-index: 2;
        cursor: pointer;
        opacity: 0;
        display: none\9; /* IE8 and below */
        margin: 0;
        width: 100%;
        height: 36px;
}
  • position: absolute – While .faq-section wrapper is relative positioned, we’ll need this to visually place our checkbox above the label.
  • z-index: 2 – Make sure it will be above section content, including label.
  • cursor: pointer – Optionally, this will add a pointer cursor when you hover on it.
  • opacity: 0 and display: none\9 – Visually hide the checbox, while on browsers like Internet Explorer 8 and below will be hidden.
  • margin: 0 – Remove default margin.
  • width: 100% and height: 36px – The checkbox height value matches the height of the label. Also, using 100% for the width will expand the checbox in order to fully cover the label.

Done!

That’s all, I hope you liked this article. Please feel free to comment and share your thoughts/ideas about the result.

Posted by: Dhiraj kumar

10 Web Usability tips for your website

At the beginning, perhaps you were developing websites just for fun or you were just learning some new tricks, but now, when you are developing a website or a web application you can’t afford to skip the usability basics rules.

In this article we’ll try to remember some basic, unwritten web usability rules.

usability-tips

1. Place the logo always in the left corner of the viewport

As drivers use to search for green traffic light to start leaving the intersection, users search the logo in the left side of the website to click on it. They are used to click on it to access the home/main page of the website. Also, as usability tests proved, the left corner of a website is the most visible content.

2. Add CSS states (almost) to everything

Nothing is more annoying that hovering a website menu, or a button, link etc without seeing a change. The user is searching for interactivity and if you, as web developer don’t offer him that, you will lose him. Beside hover, for example a button should have also an active state (pressed style). This way the user will fell he’s always under control.

CSS states example

<a href="#" id="button-style">My Button</a>

a#button-style{
  background: #eaeaea;
}

a#button-style:hover{
  background: #9c9c9c;
}

a#button-style:active{
  background: #777777;
}

3. Use label’s “for” attribute

When in a form, and you need to click on a checkbox input or radio input, it will always be easier to be able to check/uncheck the input by toggle-ing also on the label. Using labels for forms is also an accesibility “golden rule”. Getting back to usability rules, a common mistake is to use the label tag without it’s for attribute. Here is a good example for using labels when inner a form:

<input type="radio" name="options" id="id-1">
<label for="id-1">First option </label>

<input type="radio" name="options" id="id-2">
<label for="id-2">Second option </label>

As result,selecting a radio option is easier. Cool huh?

First option
Second option

4. Breadcrumbs

Using breadcrumbs could be compared with GPS navigation, the user will know his current position inside the website, it will help him to no get lost. You want to guide him through your website and you don’t want to have him annoyed by the fact he’s lost – because in this case you risk to loose him, he could exit your website immediately. Get inspired by the well known breadcrumbs patterns around the internet.

5. Highlight form fields

If you are dealing with text inputs and textareas you should use CSS focus state to specify when the user has clicked inside an input or textarea. This way user will know which form element he clicked.

Quick CSS example

input[type=text]{
  border: 1px solid #9c9c9c;
  background: #eaeaea;
}

input[type=text]:focus{
  border: 1px solid #323232;
  background: white;
}

6. Use HTML tags accordingly

Use heading, paragraph, bold elements in the right way, as they should be used. Take advantage of them by using heading to highlighting titles, use paragraphs to add a text section and bold to highlight words in the text section. Make your text easier to read by creating a text flow, this way the user will easier scan titles and sections.

Also keep in mind to use headings in their “normal” order: h1, h2,…etc. It’s recommended again not having more then one h1 per page, usually h1 contains a very important text like main title of the page, for example could be “purchase” or “download”.

7. Create a sitemap

A site map is a website structure representation, a link collection that helps improving user’s website navigation.

8. Rich content footer

Every time you build a site you should keep in mind that a website should have a header, content and footer, in some cases the last one is missing and the website looks a bit strange…it’s like “hmm…something’s missing?!”.  Lately footers are getting richer and richer content, so take advantage and add information to it and do not forget to get inspired.

9. Think as you are the user

Also, you are an user after all, but imagine you are your own website user, try scenarios, act as you have no idea about the content of your site and try finding important links as purchase, download etc. If it’s hard for you, because you already know every comma in your site, ask a friend or colleague for a feedback. Keep in mind that every opinion matters.

10. Read, read and….read again about usability

If you think you know enough, that means you still have a lot to learn. Usability evolves, but the main principles are staying and reading can help you improve yourself.
Here’s a short book list I’d recommend to read:

  • Don’t Make Me Think – Steve Krug
  • Designing Web Usability: The Practice of Simplicity – Jakob Nielsen
  • Designing Web Interfaces: Principles and Patterns for Rich Interactions – O’Reilly

Posted by: Dhiraj kumar

Practical CSS3 tables with rounded corners

css3-tables-browser-supportThere has been some discussion in the past about how/when to use tables in web development. Though, the conclusion is the same: when you’re dealing with tabular data, tables are absolutely required.

Designing a table is a challenge – and here I’m not talking only about the way it looks. It’s (mostly) about how easy is your table to read. If your table isn’t easy to scan, usually users get annoyed as they lose focus when trying to find the right column and row.

Having said that, today we’re going to create beautiful and practical tables styled using CSS3. Also, jQuery will be used to create fallbacks for older browsers.

What’s so cool about these tables?

In this article you’ll see how CSS3 and tables can work together to create some cool and usable results.

  • Rounded corners with no images
  • Very easy to update – there are no extra CSS id’s or classes added
  • User-friendly and easy to read

Rounded table corners

Here’s the trick: while border-collapse‘s default value is separate, we need also to set theborder-spacing to 0.

table {
    *border-collapse: collapse; /* IE7 and lower */
    border-spacing: 0;
}

For IE7 and lower, we need to add a specifically line, in order to create a good fallback for the tables.

Then, we just need to round some corners:

th:first-child {
    -moz-border-radius: 6px 0 0 0;
    -webkit-border-radius: 6px 0 0 0;
    border-radius: 6px 0 0 0;
}

th:last-child {
    -moz-border-radius: 0 6px 0 0;
    -webkit-border-radius: 0 6px 0 0;
    border-radius: 0 6px 0 0;
}

th:only-child{
    -moz-border-radius: 6px 6px 0 0;
    -webkit-border-radius: 6px 6px 0 0;
    border-radius: 6px 6px 0 0;
}

jQuery hover fallback

You may already know that when it comes about IE6:hover does not actually work on non-anchor elements.

So, to make it work, instead the CSS solution we’ve used:

.bordered tr:hover{
  background: #fbf8e9;
  -o-transition: all 0.1s ease-in-out;
  -webkit-transition: all 0.1s ease-in-out;
  -moz-transition: all 0.1s ease-in-out;
  -ms-transition: all 0.1s ease-in-out;
  transition: all 0.1s ease-in-out;
}

you could use some jQuery code to simulate the hover effect:

$('.bordered tr').mouseover(function(){
    $(this).addClass('highlight');
}).mouseout(function(){
    $(this).removeClass('highlight');
});

and here’s also the styles for the CSS highlight class:

.highlight{
  background: #fbf8e9;
  -o-transition: all 0.1s ease-in-out;
  -webkit-transition: all 0.1s ease-in-out;
  -moz-transition: all 0.1s ease-in-out;
  -ms-transition: all 0.1s ease-in-out;
  transition: all 0.1s ease-in-out;
}

The above is basically the .bordered tr:hover duplicate.

jQuery zebra fallback

To create the zebra effect, using CSS3, we’ve selected the even rows within the tbody:

.zebra tbody tr:nth-child(even) {
    background: #f5f5f5;
    -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    -moz-box-shadow:0 1px 0 rgba(255,255,255,.8) inset;
    box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
}

Now, the above selector is a CSS3 one – so no support for older browsers. Below you’ll see how we may target and style the even rows for all browsers:

$(".zebra tbody tr:even").addClass('alternate');

A simple jQuery line.

.alternate {
    background: #f5f5f5;
    -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    -moz-box-shadow:0 1px 0 rgba(255,255,255,.8) inset;
    box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
}

The CSS class that will style the even rows.

Browser support

The tables already degrade very nice on older browsers, so it’s up to you if you want to use also the above jQuery solutions. It’s all about the visitors audience you’re targeting.

view demo

Conclusion

Do you like the CSS3 tables I made? Feel free to comment about the final result and thanks for reading this article!

Posted by: Dhiraj kumar

9 Ways to Speed Up Your Web Pages with HTML5 & CSS3

Web designers/developers are always looking for new ways to improve the speed and performance of the pages. With some of the new features available in HTML5, there are several ways that you can improve your web applications/pages to give your user a better experience. We’ve compiled 9 easy-to-implement HTML5 tips and tricks here that would help you streamline your website without investing in additional infrastructure.

1. Use HTML5 Forms and Inputs

HTML5 has introduced a whole new set of form attributes and input types to upgrade your existing HTML forms. Not all browsers are supporting these yet, but for the ones that are there are some useful features built in.

  • autofocus focuses the caret on page load so you can begin typing in the field immediately
  • placeholder allows you to set default text in a field that will clear when the field is clicked
  • required will not let the form submit if the field is not filled out
  • pattern lets you specify a custom regular expression that the field must meet

Since these functions are now built-in, you will not need to create JavaScript functions to handle them. This will speed up your pages and create a more responsive feel to your page.

2. Use CSS Transitions

Using CSS transitions instead of JavaScript functions will greatly improve the speed of your pages as well as create an clean visual transition between two states. By using the totheleft andtotheright you can move a box around to create transitional movement. For example:

div.box {
    left:50px;
    //for webkit browsers
    -webkit-transition: all 0.3s ease-out;
    //for mozilla
    -moz-transition: all 0.3s ease-out;
    //for opera
    -o-transition: all 0.3s ease-out;
    //other browsers
    transition: all 0.3s ease-out;
}
div.box.totheleft {
    left0px;
}
div.box.totheright {
    left80px;
}

Since the number of bytes sent to the browser is much less when using CSS-based animations instead of JavaScript, the animation will be quicker and more responsive.

3. Use HTML5 Web Storage

When you need to store information such as in a cookie, you create an inefficient situation where the cookie data must be added to every HTTP request header. This ultimately makes a large impact on response time. Using HTML5, we can create a solution to this problem and store information in Web Storage instead of cookies.

Two Web Storage objects, sessionStorage and localStorage have been created to store persistent user data on the client-side for the length of the session. This data is not transferred through the HTTP request so it does not slow down the response time of the page. Here is a small example:

//check to see if localstorage is present (browser supports HTML5)
if (('localStorage' in window) && window.localStorage !== null) {
    //store items
    localStorage.wishlist = '["Bear", "Cow", "Pig"]';
}

As you can see, this method is much simpler than cookies since we do not need to specify an expiration or store the cookie with the document in the DOM.

4. Use Web Workers

Web Workers are part of the new HTML5 specification and are an API for running scripts in the background. This creates an almost multi-thread-like environment where large processing can happen in the background while normal page function can continue to function. When using a Web Worker, you just need to specify the script that the worker will be running, any event listeners (if any) and then start the worker. Here is an example:

var worker = new Worker('doWork.js');
worker.addEventListener('message'function(e) {
    console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.

There are many situations where using Web Workers would create a much faster application environment such as image processing, text formatting or receiving and processing large files.

5. Use Web Sockets

Web Sockets is a specification for an API that allows for two-way communication with a remote host. This method can be used between a client and server application or can be implemented between web browsers and servers. Since Web Sockets has a very light-weight frame, the bandwidth consumption is much less and often creates a 35% reduction in bytes sent as well as ping times that are 3-5 times shorter than standard HTTP.

Not only can Web Sockets create faster communication, it can create a way for your application to work in limited environments. Since Web Sockets only run on port 80, they can be used as a way to get around blocked ports that your application may need.

6. Use Application Cache

Application caching creates a way for developers to have offline web sites and applications. This allows for offline browsing, reduced server loads and faster site speeds since some elements are cached. The developer can specify which files the browser should store in the cache manifest file, which is a simple text file of resources. Here is an example of a cache manifest file:

CACHE MANIFEST
# 2011-06-18:v3
# Explicitly cached entries
index.htm
style.css
# offline.htm will be displayed if the user is offline
FALLBACK:
/ /offline.htm

This manifest file references a “catch all” page that will be displayed if the user tries to access pages that are not cached while offline. Only the pages specified in the “cached entries” section will be available to the user. You must enable the page to use the application cache and point it to your manifest file. Here is how you reference the file:

<html manifest="http://www.example.com/example.appcache">
  ...
</html>

Manifest cache files can have any file extension but you need to be sure that your web server is setup to handle them with the correct MIME type. For example, in Apache:

AddType text/cache-manifest .appcache

Using the application cache you can create a viable, offline experience for your users with very little effort. When speeding up your pages, caching can be very helpful in creating less server traffic and caching the static items that you do not update often.

7. Use CSS Instead of Images

Using CSS effects instead of images can be an easy way to speed up your site and many popular image techniques can be replicated using CSS. Not only do you cut down on the number of bytes going through your server but you cut down on HTTP requests. Here are some great CSS techniques that you can use to cut down on the images your site is using:

  • CSS Masks
  • Box-shadow
  • Transforms
  • RGBA/Alpha opacity
  • Border-radius
  • Linear and radial gradients

8. Use Hardware Acceleration

While hardware acceleration may not be available in all browsers yet, it packs a big punch in those that support it. If your application uses animations or 3D transforms you can turn on hardware acceleration to get the GPU working for you. In order to use this feature you need to use a HTML5 canvas and your applications will instantly become twice as fast at rotations, scaling and opacity. These features will have the benefit of being handled directly by the GPU and won’t require a redraw of the layer contents.

9. Use Client-side Databases

Currently, the major browsers can’t agree on which client-side database to support but Web SQL Database and IndexedDB can be used to greatly improve the speed of data storage to the client-side instead of sending the data back to your server. Not only will this decrease HTTP requests but it will cut down on the load of your server when the user wants to do simple tasks like search, sort or filter.

Unfortunately, since most browsers support Web SQL DB and Mozilla only supports IndexedDB, you will either have to choose to support the two or cut out Mozilla users. However, both of them are simple to learn and use so it isn’t hard to begin using these to speed up the storage of data for your pages.

As you can see, there are many great new features in HTML5 that you can use to begin speeding up your web pages and create a better user experience for web applications. Getting started with HTML5 is easy and pays off with big benefits almost from the start. Get started by implementing some of these features in your sites and you will begin to see that there are great things ahead for your sites with HTML5.

Posted by: Dhiraj kumar

jQuery Basics Tutorial – How To Use jQuery & How jQuery Works?

jQuery: The Basics

This is a basic tutorial, designed to help you get started using jQuery. If you don’t have a test page set up yet, start by creating a new HTML page with the following contents:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Demo</title>
  </head>
  <body>
    <a href="http://jquery.com/">jQuery</a>
    <script src="jquery.js"></script>
    <script>

    </script>
  </body>
</html>

Edit the src attribute in the script tag to point to your copy of jquery.js. For example, if jquery.js is in the same directory as your HTML file, you can use:

 <script src="jquery.js"></script>

You can download your own copy of jQuery from the Downloading jQuery page

Launching Code on Document Ready

The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:

 window.onload = function(){ alert("welcome"); }

Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn’t run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML ‘document’ isn’t finished loading yet, when you first try to run your code.

To circumvent both problems, jQuery has a simple statement that checks the document and waits until it’s ready to be manipulated, known as the ready event:

 $(document).ready(function(){
   // Your code here
 });

Inside the ready event, add a click handler to the link:

 $(document).ready(function(){
   $("a").click(function(event){ alert("Thanks for visiting!"); });
 });

Save your HTML file and reload the test page in your browser. Clicking the link on the page should make a browser’s alert pop-up, before leaving to go to the main jQuery page.

For click and most other events, you can prevent the default behaviour – here, following the link to jquery.com – by calling event.preventDefault() in the event handler:

 $(document).ready(function(){
   $("a").click(function(event){
     alert("As you can see, the link no longer took you to jquery.com");
     event.preventDefault();
   });
 });

Complete Example

The following is an example of what the complete HTML file might look like if you were to use the script in your own file. Note that it links to Google’s CDN to load the jQuery core file. Also, while the custom script is included in the <head>, it is generally preferable to place it in a separate file and refer that file with the script element’s src attribute

 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="utf-8">
   <title>jQuery demo</title>
 </head>
 <body>
   <a href="http://jquery.com/">jQuery</a>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
       $("a").click(function(event){
         alert("As you can see, the link no longer took you to jquery.com");
         event.preventDefault();
       });
     });
   </script>
 </body>
 </html>

Adding and Removing an HTML Class

Important: The remaining jQuery examples will need to be placed inside the ready event so that they are executed when the document is ready to be worked on. See Launching Code on Document Ready above for details.

Another common task is adding (or removing) a class.

First, add some style information into the <head> of your document, like this:

 <style>
    a.test { font-weight: bold; }
 </style>

Next, add the addClass call to your script:

  $("a").addClass("test");

All your a elements will now be bold.

To remove the class, use removeClass

 $("a").removeClass("test");
  • (HTML allows multiple classes to be added to an element.)

Special Effects

In jQuery, a couple of handy effects are provided, to really make your web site stand out. To put this to the test, change the click that you added earlier to this:

 $("a").click(function(event){
   event.preventDefault();
   $(this).hide("slow");
 });

Now, if you click any link, it should make itself slowly disappear.

CALLBACK AND FUNCTIONS

A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. The special thing about a callback is that functions that appear after the “parent” can execute before the callback executes. Another important thing to know is how to properly pass the callback. This is where I have often forgotten the proper syntax.

Callback without arguments

For a callback with no arguments you pass it like this:

 $.get('myhtmlpage.html', myCallBack);

Note that the second parameter here is simply the function name (but not as a string and without parentheses). Functions in Javascript are ‘First class citizens’ and so can be passed around like variable references and executed at a later time.

Callback with arguments

“What do you do if you have arguments that you want to pass?”, you might ask yourself.

Wrong

The Wrong Way (will not work!)

 $.get('myhtmlpage.html', myCallBack(param1, param2));

This will not work because it calls

myCallBack(param1, param2)

and then passes the return value as the second parameter to $.get()

Right

The problem with the above example is that myCallBack(param1, param2) is evaluated before being passed as a function. Javascript and by extension jQuery expects a function pointer in cases like these. I.E. setTimeout function.

In the below usage, an anonymous function is created (just a block of statements) and is registered as the callback function. Note the use of ‘function(){‘. The anonymous function does exactly one thing: calls myCallBack, with the values of param1 and param2 in the outer scope.

$.get('myhtmlpage.html', function(){
  myCallBack(param1, param2);
});

param1 and param2 are evaluated as a callback when the ‘$.get’ is done getting the page.

A basic introduction to jQuery and the concepts that you need to know to use it.

Posted by: Dhiraj kumar

10 Tips for Writing Awesome jQuery Plugins

Introduction

I’ve been developing and studying plugins, particularly in jQuery for quite sometime and through this process I have learned a lot about what works and what doesn’t work. There are a ton of great plugins out there that look great on the surface but are sometimes very frustrating to work with behind the scenes. So many plugins if only had a little extra effort could be taken from good to great and become much more widely used.

These are some simple tips that I have put together that will help any developer write truly great plugins. There are some things that may not seem quite as obvious at first, but they are there not only to develop your jQuery plugins, but to help maintain and expand on them in the future as well.

It is also important to note that having a solid structure and guideline to follow for you plugin speeds up development significantly as it takes away any time required to think about how you should start your project. You will already know and will only need to write the core code of your plugin and not worry about any of the other details.

1. Plugins Should Work Out of the Box

This is my biggest frustration when using plugins out there so I have made it the first point. Your plugin should just work, there should be no extra setup or structure to define. There should at the minimum be a basic default that just works and should not require anything more than an initialization.

$("#container").DG_Tooltip();

A good example would be a jQuery slideshow plugin that has an interface for slides and a next/prev button. I’ve seen plugins that will ask you to set up a div with a proper id and class and then ask you to reference it through the plugin function. Things like this should be built in directly and should be provided as options that can be toggled on or off.

2. Always Provide Default Settings

It will be quite rare that your plugin will contain absolutely no configurable settings. This follows from the first point as you should always try to find as many settings as you can and provide a set of defaults for them as well. This will definitely increase the chances of any developer using your plugin and increases that chance that they will spread the word about it.

var defaultSettings = {
    mode            : 'Pencil',
    lineWidthMin    : '0',
    lineWidthMax    : '10',
    lineWidth       : '2'
};
settings = $.extend({}, defaultSettings, settings || {});

The code above is the standard way to set your default settings and extend them with any settings developers may pass in.

3. Keep All Naming Unique

When creating your plugin you should always be mindful of keeping any reference to the plugin absolutely unique. This goes for classes, ids and the plugins name itself. This requires absolutely no extra effort and will ensure that you avoid any conflicts with existing JavaScript and CSS code.

$("#container").tooltip();     //bad    
$("#container").DG_Tooltip();   //good

In the above example we keep the name unique for our plugin by prepending it with a “DG_” to differentiate it from any generic names that might otherwise exist. I also follow this unique naming convention with the CSS and will make sure even generic terms like “tab” or “holder” all contain the keyword.

DG_Paint_button
DG_Paint_holder

I also like to add the underscore just to make sure there is no chance of any id or class name conflicts, giving me more confidence that my jQuery plugin will succeed.

4. The Standard Plugin Layout in a Nutshell

This is a pretty standard piece of jQuery code that you will see most good plugins having, it has all the important pieces you will need for developing, maintaining and updating your plugin. Following a structure takes away a lot of the guess work and lets you focus on developing the plugin.

var defaultSettings = {
    //settings
};
$.fn.DG_Paint = function(settings)
{
    //check for setters/getters
    
    return this.each(function()
    {
        var elem = $(this);
        //run some code here
        
        elem.data("DG_Paint", DG_Paint);
    }
    //classes/prototyping
}

There are five key points to note here:

  1. Default settings go outside of the plugin, it does not need to be instantiated each time.
  2. Setters and getters aren’t always required but should be checked for before running the main each loop.
  3. Return each element to not disrupt the jQuery method chaining flow.
  4. Store any data for the element using .data(), we may need this later for setters and getters.
  5. Finally setup any Classes/Prototypes outside and after the main loop.

5. Keep Your Code Organized

Although this one seems quite obvious I will quickly run through it as I have seen some odd setups in far too many plugins. It’s always a good idea to keep a simple file structure for your files that is self explanatory.

./images/
./includes/
./themes/
./DG_Paint.js
./DG_Paint.min.js
./DG_Paint.css
./DG_Paint.min.css

It’s quite clear with the following setup, which files need to be included and where I can find other plugin files or jQuery libraries should I need to take a look at them.

6. Use Class Prototyping

This is a pretty big topic on it’s own so I will only briefly mention it here. Basically there are two main reasons for prototyping your functions.

  1. Not having to instantiate a separate copy of each method is much more efficient and runs faster.
  2. It saves a ton of memory by only having references to each object method and not having a copy of each one.
function Canvas(settings)
{
    this.canvas = null;     
    this.ctx = null;
}
Canvas.prototype = 
{
    generate: function()
    {
        //generate code
    }
}

It also serves to organize your code and makes it much more reusable. In the above example only the Canvas object gets instantiated for each new object while the prototyped functions are only referenced.

7. Provide Setters and Getters

Providing setters and getters is not a requirement but I find it’s a good option to provide your developers should they need it. All we’re doing here is allowing modifications to the plugin after it has been called. The most basic setup follows:

if(typeof option === 'object'){
    settings = option;
}else if(typeof option === 'string'){
    if(
        this.data('DG_Paint_canvas') &&
        defaultSettings[option] !== undefined
    ){
        var canvas = this.data('DG_Paint_canvas');
        if(settings){
            canvas.settings[option] = settings;
            return true;
        }else{
            return canvas.settings[option];
        }
    }else return false;
}

All we’re doing here is checking if an option is set rather than some settings. If two parameters are provided it means we are setting, if one parameter is set it means we are requesting the specified option.

8. Test in All Browsers

This is absolutely crucial for the survival of your plugin. Developers may not catch glitches in your code, but their users most certainly will and if there are a lot of complaints that lead back to your plugin it will simply be replaced.

This step can always be tiring as after completing a plugin you feel you just want to launch it. Make sure you always hold back on this urge and spend the extra day to test your plugin thoroughly with as many scenarios as you can think of. This will not only fix up any simple bugs but also may shine some light on some simple improvements.

9. Packaging for Release

Once your plugin is all polished and ready for release take the time to do the next three simple steps.

  1. Write some documentation for the trickier parts, not only for other developers that may be looking at your code but for yourself as well.
  2. Version your plugin either by the file names or in the documentation somewhere. It doesn’t matter where as long as developers can see what version they are using and check for updates.
  3. Finally provide minified versions of your code, this only takes a few minutes and adding it will make developers using your plugin happy and coming back for more.

Sometimes it’s the simple steps that can really make a difference, in the end the developers will make or break your jQuery plugin so make sure you keep them as happy as possible.

10. Upload Your Plugin

There are plenty of services out there for this, but two I prefer are Github and Google code.

You man not always want to upload your jQuery plugins for public use, especially if it’s an internal project for work, but likewise keep your plugins in their own repository and outside of the main codebase. This ensures your plugins get maintained with proper versioning and documentation.

However if your plugin is indeed for public use, services as the above mentioned Github and Google code are fantastic as they provide areas for issue reporting, activity feeds and download counters.

This lets you interact with the users of your plugin to see how well your plugin is doing from a total downloads point of view. These services are extremely easy to setup and provide a lot of value.

Conclusion

Following these tips should pretty much cover the core of your jQuery plugin lifecycle. It also provides a more standard format for you to follow as well as providing a familiar strucure that developers are used to. Wheter you are developing plugins for fun or profesionally the more your plugin gets used the more gratifying it feels.

Posted by: Dhiraj kumar