Tuesday, January 13, 2015

Jquery Advanced Best Practices

1. Always Descend From an #id

This is the golden rule of the jQuery selectors. The fastest way to select an element in jQuery is by ID:

or select multiple elements descending from an ID:
$('#content p').hide();

2.Use Tags Before Classes

The second fastest selector in jQuery is the Tag selector ($(‘head’)) because it maps to a native JavaScript method, getElementsByTagName(). The best way is to prefix a class with a tag name (and descend from an ID):

var receiveNewsletter = $('#nslForm input.on');
The class selector is among the slowest selectors in jQuery; in IE it loops through the entire DOM. Avoid using it whenever possible. Never prefix an ID with a tag name. For example, this is slow because it will loop through all <div> elements looking for the ‘content’ ID:

var content = $('div#content'); // VERY SLOW, AVOID THIS
Also, DON’T descend from multiple IDs:

var traffic_light = $('#content #traffic_light'); // VERY SLOW, AVOID THIS

Cache the parent object then run queries on it:

var header = $('#header');
var menu = header.find('.menu');
menu = $('.menu', header);

4. Optimize selectors for Sizzle’s ‘right to left’ model

var linkContacts = $('.contact-links div.side-wrapper');

instead of:

var linkContacts = $('a.contact-links .side-wrapper')

5. Use find() rather than context

var divs = $('.testdiv', '#pageBody'); 

var divs = $('#pageBody').find('.testdiv');

var divs = $('#pageBody .testdiv');

5. Use direct functions rather than their convenience counterparts

For better performance you can use direct functions like $.ajax() rather than $.get(), $.getJSON(), $.post() because the last ones are shortcuts that call the $.ajax() function

6.Use shorcuts 

Consider, below jQuery code lines.

$("#elm").css("display", "none"); //Line 1

$("#elm").css("display", ""); //Line 2

$("#elm").html(""); //Line 3

Above code lines are very common but its unfortunate because some faster and more readable shortcuts available, yet ignored. Find below jQuery code lines that does the exactly same thing but these are more readable and fast.

$("#elm").hide(); //Line 1

$("#elm").show(); //Line 2

$("#elm").empty(); //Line 3

There are many more examples which you can find in your code. For example, to add CSS Class to any element

$("#elm").prop("class", "cssClass");

where the better approach would be,

Another example is of setting height and width,

$("#elm").css("height", "100px"); //Line 1

$("#elm").css("width", "100px"); //Line 2

using in-built jQuery functions,

$("#elm").height(100); //Line 1

$("#elm").width(100); //Line 2

Another common situation is of toggling (show/hide) of element. For example, 

    $("#elm").css("display", "none");
    $("#elm").css("display", "");
where the better approach is,

to be continued . . . .:)

Jquery Best practice - Event Handling

  We usually do this :

$("#longlist li").on("mouseenter", function() {

    $(this).text("Click me!");


  $("#longlist li").on("click", function() {

    $(this).text("Why did you click me?!");


This is fine IF...

If you like using a lot of memory for event handlers
If you don't have many DOM elements
If you don't care about best practices

Best Approach : Event Delegation 

var list = $("#longlist");

  list.on("mouseenter", "li", function(){

    $(this).text("Click me!");


  list.on("click", "li", function() {

    $(this).text("Why did you click me?!");


Simple but thoughtful :)

Try n feel the difference...

JQuery Best Practices - DOM Manipulation

  Usually we folllow like this ..

 // Set's an element's title attribute using it's current text
  $(".container input#elem").attr("title", $(".container input#elem").text());

  // Set's an element's text color to red
  $(".container input#elem").css("color", "red");

  // Makes the element fade out
  $(".container input#elem").fadeOut();

This is fine if ..

If you like repeating yourself
If you do not care about performance
If you don't care about best practices

  Best Approach.. 

  // Stores the live DOM element inside of a variable

  var elem = $("#elem");

  // Set's an element's title attribute using it's current text
  elem.attr("title", elem.text());

  // Set's an element's text color to red
  elem.css("color", "red");

  // Makes the element fade out

cache your selectors in variables :)

Another Example 

 Mostly we prefer doing like this ..

// Dynamically building an unordered list from an array

  var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
  list = $("ul.people");

  $.each(localArr, function(index, value) {

    list.append("<li id=" + index + ">" + value + "</li>");


// Dynamically building an unordered list from an array
  var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
  list = $("ul.people"),
  dynamicItems = "";

  $.each(localArr, function(index, value) {

    dynamicItems += "<li id=" + index + ">" + value + "</li>";



 Append only once instead of doing it every time ..:)

Jst try :) 

JQuery Best Practices - Document ready

Most projects starts like this

$("document").ready(function() {
    // The DOM is ready!
    // The rest of the code goes here

This is fine if

If you know the environments where your code will run
If you do not care about page load performance
If you don't care about best practices

This is better

// IIFE - Immediately Invoked Function Expression

  (function($, window, document) {

    // The $ is now locally scoped

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!


   // The rest of the code goes here!

  }(window.jQuery, window, document));

  // The global jQuery object is passed as a parameter


Tuesday, March 19, 2013

HTML 5 - Navigation with the nav element

One of the new elements for HTML 5 is the <nav> element which allows you to group together links, resulting in more semantic markup and extra structure which may help screenreaders.

HTML5 nav tag defines the section for navigation links in a document. It is not mandatory to place all the links of a document in nav element, but the major navigational links should be placed under it. This element can be used more than one place within a document. But nav element should be placed in such places in a document so that visitors can easily access the navigational links.

Important point need to be remembered:

HTML5 nav element is supported by latest versions of all web browsers. Internet Explorer 8 or earlier versions of Internet Explorer do not support nav element.

How to use it

You are probably used to using something like

<div id="nav">
<li><a.... etc

<ul id="mainNav">
Well, for the sake of your markup, nothing much will change as you will now have something like this

<li><a href="index.html">Home</a></li>
<li><a href="/about/">About</a></li>
<li><a href="/blog/">Blog</a></li>

The specification

In the following example, the page has several places where links are present, but only one of those places is considered a navigation section.

<h1>Wake up sheeple!</h1>
<p><a href="news.html">News</a> -
<a href="blog.html">Blog</a> -
<a href="forums.html">Forums</a></p>
<p>Last Modified: <time>2009-04-01</time></p>

<li><a href="articles.html">Index of all articles</a></li>
<li><a href="today.html">Things sheeple need to wake up for today</a></li>
<li><a href="successes.html">Sheeple we have managed to wake</a></li>

<p>...page content would be here...</p>
<p>Copyright © 2006 The Example Company</p>
<p><a href="about.html">About</a> -
<a href="policy.html">Privacy Policy</a> -
<a href="contact.html">Contact Us</a></p>

There are six items of navigation in the header element there. But only three are in the nav tag. There is no explanation as to what differentiates the first three links with the second three links – both go to different pages and all are in internal to that current site.

See a second example:

<h1>The Wiki Center Of Exampland</h1>

<li><a href="/">Home</a></li>
<li><a href="/events">Current Events</a></li>

<h1>Demos in Exampland</h1>

<li><a href="#public">Public demonstrations</a></li>
<li><a href="#destroy">Demolitions</a></li>

<section id="public">
<h1>Public demonstrations</h1>
<section id="destroy">
<p><a href="?edit">Edit</a> | <a href="?delete">Delete</a> | <a href="?Rename">Rename</a></p>
<p><small>© copyright 1998 Exampland Emperor</small></p>

This is a little more helpful as I find the biggest isse of the <nav> element is deciding which sets of links should be classed as major navigation.

Other Possible Uses

Below are a few more examples of other areas of the site in which you might consider using the <nav> element. It is also important to note that while XHTML 2 <nl> element, this hasn’t been replicated in HTML 5 because navigation does not have to take list form, as we’ll see.

  • Table of Contents
  • Previous/next buttons (or pagination)
  • Menu - developers are using the <menu> element for navigation rather than the <nav> element. We thought it best to clarify that <menu> is to be used for a list of commands and is an interactive element and more likely to be used exclusively in Web Applications.

HTML 5 - The header element

Several new tags or elements have been added in HTML5. The header tag (<header>) is one of them. It is used as header of one or more sections or as a header of the document. HTML5 header tag should be used as a container of introductory contents like <h1> – <h6> tags, table of contents, search form, logo etc. with or without navigational links. More than header element can be used in a HTML5 document and it is generally placed at the beginning of the document or <article> tag.

Important points need to be remembered:

1. <header> and <head> tags are completely different.
2. A <header> tag can’t be placed within <footer> or <address> tag. Also header element can’t be placed within another header element.
3. HTML5 header element is supported by latest versions of all web browsers. Internet Explorer 8 or earlier versions of Internet Explorer do not support header element.

There are few HTML5 header tag examples given below:

Below the header tag is used as document header

1 <header>
2 <h1>This is the heading of the page</h1>
3 With some supplementary information
4 </header>
Below the header element is used as article header

1 <article>
2 <header>
3 <h1>Title of this article</h1>
4 By S Ghosh
5 </header>
6 Contents of the article
7 </article>

In summary <header> give us some great added semantic value in order to describe the head of a section.

An Inroduction to HTML 5

HTML5 is the latest version of Hyper Text Markup Language. The version of this language is 5 and it is still under development. The main aim of HTML5 is to increase the latest multimedia support and to decrease the dependency on client side scripting language like JavaScript and third party plugging like Adobe Flash Player etc. HTML5 can be effectively run on low-powered devices such as smart phones, tablets etc. Several new elements like <video>, <audio>, <canvas> etc. have been introduced in HTML5.

HTML5 is being developed in joint collaboration of the Web Hypertext Application Technology Working Group (WHATWG) and World Wide Web Consortium (W3C). As the development of HTML5 are still going on so it is not yet an official standard. No web browser supports all HTML5 elements yet, but popular web browsers like (Firefox, Chrome, Internet Explorer, Safari, Opera etc.) are adding more HTML5 tags support in their latest versions.
HTML5 and CSS3 have become popular tools that help in building a well-defined website. Each of them have many advanced features of their own but nowadays, they are used in combination with each other by expert web designers, to create refined web pages with semantic accuracy. Let us have a look at some advantages of HTML5 and CSS3.
  • The first benefit you get is that the readable codes are semantically accurate. When a web design is not semantically accurate, it cannot attain a good rank. HTML5 and CSS3 help you to overcome this. The readable codes are very simple and easy to understand.

  • The tutorials in the language help designers in developing a better web page. This paves way for the designers to make use of apt tools or elements in the language for a website.

  • Many websites need some extra plug-ins to view the videos in the web page. In case of  HTML5 and CSS3, the audio and video effects are tagged and viewed without the support of third party plug-ins.

  • Using separate codes for the purpose of updations are important for all types of websites. These codes do not give a proper output at times. In HTML5 and CSS3, as the scripting is not necessary
     for validation you can avoid the usage of confusing complex codes.

  • Many browsers do not support all types of web pages but HTML5 and CSS3 help the designer to develop a web page that is compatible even with previous versions of your browsers.
  • Some elements in HTML5 and CSS3 allow you to handle graphics and photos efficiently. These elements use some procedural methodologies to draw up the graphics directly into the browser.

  • Flash applications are bound to cause problems. HTML5 combined with CSS3 provides you with many alternative features to support media. As CSS3 has enhanced itself with many  features, there are many added elements that bring in the wow factor, when it is used with HTML5.

  • Creating Box Shadow requires numerous images and this process is made simple by using these new technologies. The text shadow is an element added to make the webpage more attractive. This can be carried out using the simple codes in CSS3. It makes the web layout very simple.

  • One of the popular elements in web design is the use of rounded corners for buttons, layout elements, menus and much more. Using the ‘border-radius’ property, you can easily create rounded corners.

  • Many websites have contact forms, that help the clients get in touch with the company. Some forms may not be supported by browsers. There are many types of forms designed with HTML5 and CSS3 which have a unique design and are compatible with all the common browsers.

  • Using these technologies you can have full control over the colors in the templates, thereby eliminating the need to use separate codes for the color theme.