Best Practices for jQuery Developers


Following are some of the best practices that you could follow while working with jQuery:

  • Plugins:
    • Please avoid unnecessary use of plugins
    • If a plugin is being used, respect the authors work and ensure that the plugin file is reused with the license comments intact
    • If you are writing a reusable functionality in the code, always move it into a jQuery plugin format, to be reused across the site
  • Coding:
    • Use jQuery CDN (google or Microsoft or jQuery) as much as possible for script registration, if its fine with clients. To be on the safer side, you could have a fallback code as well:
      <!– Grab Google CDN jQuery. fall back to local if necessary –> 

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js“></script> 

<script>!window.jQuery && document.write(‘<script src=”js/jquery-1.4.2.min.js”><\/script>’)</script>

  • Avoid unnecessary upgrades of jQuery, unless there are features, which you require or some plugins require. Stick to one version from the beginning. (ex. 1.5.1)
  • Avoid writing event handler attributes (onclick etc.), instead use live or bind methods to attach the respective event handlers.
  • Avoid mixing javascript code with jQuery code.
  • Cache any jQuery selector, if reused in multiple statements.
    Ex. Avoid $(“#x”).val(); $(“#x”).attr(“align”,”right”); Use var $x = $(“#x”); $x.val();$x.attr(“align”,”right”);
  • Ensure that you place ready function in your code. $(document).ready(function(){});
  • Use find method, instead of building a complex jQuery selector.

//Fine in modern browsers, though Sizzle does begin “running”

$(‘#someDiv p.someClass’).hide(); 

// Better for all browsers, and Sizzle never inits. 

$(‘#someDiv’).find(‘p.someClass’).hide(); 

  • Avoid misusing $(this).
    Ex. Use this.id instead of $(this).attr(‘id’)
  • Keep your code safe, by using noConflict() method or by passing jQuery.
    Ex. (function($){})(jQuery); or by wrapping it in a ready method.
  • Avoid declaring new jQuery selectors within foreach, instead declare them outside and reuse it inside the loop.
  • Use $.ajax instead of $.get or $.getJSON, because internally they call $.ajax.
  • Use JSON formats for communications.
  • Ensure that you move your jQuery codes to a separate javascript file, instead of inline scripts.
  • Compress javascript files for better performance.
  • Combine multiple css() calls or attr() calls into one. In case of attributes, you could also pass them as shown below: 
$(‘</a>’, {

    id : ‘myId’, 

    className : ‘myClass’, 

    href : ‘mytest.html’ 

});

  • Debugging:
    • Use Developer Toolbars and Inspectors to debug your code from client side. You do not need to perform deployments and builds to debug your jQuery code(s).
  • jQuery Cheat Sheet:
    • Always keep a jQuery cheat sheet handy with you to know about the list of functions available for you. Download here

Below are some more useful links you could check out:

Some words of caution:

  • $.ajax has issues in making cross domain AJAX calls. As a solution, you can get a patched version of $.ajax from the net.
  • Avoid http request on https sites. Your user will be prompted with a nagging security popup, which on rejection can break your request.
  • Avoid loading multiple jQuery versions.
  • Majority of the jQuery plugins are browser compatible, but NOT ALL. Read the plugin documentations carefully and use them judiciously.

This might appear to be a drop from the ocean. But it will guide them in the right direction.

div with 100% height


With div design catching up, we end up having issues with the stretching div to the max height. Most of the time this is noticed in the footer section, which has to always stretch to the edge of the browser scroll.

I came across of a browser compatible solution to this problem and thought of sharing it here.

Check the footer section in the image below:

 The red line on the left give away the clue. That particular div is responsible for pushing the Footer down.

I am attaching the HTML here:

<style>
html{
height: 100%;
border: 0;
padding: 0;
margin: 0;
}
body{
height: 100%;
margin: 0;
padding: 0;
border: 0;
}

#spacer{
display: block;
height: 95%;
float: left;
width: 2px; /* 1px would be enough this is for display only */
font-size: 1px; /* to make sure width is not overridden */
padding: 0;
margin: 0;
background-color: red; /* visual effect only */
}

#contentwrap{
display: block;
width: 99%; /* to suit but leave room for spacer */
text-align: center;
padding: 0;
margin: 0;
}

#content{
margin: 0;
padding: 0;
border: 1px solid blue;
}

#footer{
clear: both;
height: 5%;
border-top: 1px solid green;
padding: 0;
margin: 0;
}
</style>
<div id=”spacer”></div>
<div id=”contentwrap”>
<div id=”content”>
<p>Header</p>
</div><!– content –>
</div><!– contentwrap –>
<div id=”footer”>footer</div>

Hope this helps!!

Pixel by Pixel Testing


Recently one of my clients came up with a wonderful spec that really held me speechless. Each and every minute details were so crisp and clear that both the developers and testers had to do graveyard shifts. One of them was the Pixel level testing that was requested. I am sharing some of my thoughts on that there.

Tools that i would recommend:

1. Browser Developer Toolbars (IE Developer Toolbar; FireBug; Web Developer Toolbar for Safari, Chrome, Opera; Firebug for Chrome…)

2. JRuler [Download here]

3. CoolRuler [Download here]

4. MeasureIt [Download here]

As a developer, you should make use of the Developer Toolbar, especially the “Layout” section. Most of them come with inbuild rulers and color pickers as well. There are tons of other rulers and add-ons and extensions available in different browsers. Feel free to check them as well. But none of them were upto the mark as my CoolRuler. I have been using that for almost 3 years now… its pretty cool too… 🙂

Wrap text through CSS


Wrapping text through CSS is quite a necessary evil when your Analyst come up with jargons that stretches 15-20 charactors… 😉

So here’s the deal. If you need to wrap text through CSS, you can use the CSS selector defined below:

Wrap words through CSS

/* In CSS */
.wrapword{
 white-space: -moz-pre-wrap !important;  /* Mozilla, since 1999 */
 white-space: -pre-wrap;      /* Opera 4-6 */
 white-space: -o-pre-wrap;    /* Opera 7 */
 white-space: pre-wrap;       /* css-3 */
 word-wrap: break-word;       /* Internet Explorer 5.5+ */
}

/* In HTML */
<td class=”wrapword”> … </td>

Hope this helps!

How to get the javascript version?


Javascript is evolving. With newer version, more commands, new functionalities gets added. To get to know the version of javascript your browser supports, just save the following code as html and load it in your browser:

<script type=”text/javascript”>
var jsver = 1.0;
</script>
<script language=”Javascript1.1″>
jsver = 1.1;
</script>
<script language=”Javascript1.2″>
jsver = 1.2;
</script>
<script language=”Javascript1.3″>
jsver = 1.3;
</script>
<script language=”Javascript1.4″>
jsver = 1.4;
</script>
<script language=”Javascript1.5″>
jsver = 1.5;
</script>
<script language=”Javascript1.6″>
jsver = 1.6;
</script>
<script type=”text/javascript”>
document.write(‘<p><b>Javascript version ‘ + jsver
+ ‘ supported<\/b><\/p>’);
</script>

Most of the times, you can expect the following results:

Javascript version 1.6 supported

Browser and javascript version supported are as below:

Firefox, Netscape 7/8, Mozilla, and Opera 7+ all support version 1.6

Netscape 6 supports version 1.5

Opera 6 supports version 1.4

Netscape 4.5, Opera 5, and Internet Explorer 6 support version 1.3

Netscape 4 supports version 1.2

Changing scroll bar color in Gecko Browsers


Although this is not recommended by W3C, out of popular interest, i feel like posting the solution to this problem. The problem, being the fact that IE went ahead and allowed people to customise its scrollbars, while the gecko browsers like Firefox, Opera does not allow user styles to custom browser styles. 

For IE scrollbar settings, you can use the following properties:

scrollbar-arrow-color
scrollbar-base-color
scrollbar-dark-shadow-color
scrollbar-face-color
scrollbar-highlight-color
scrollbar-3dlight-color
scrollbar-shadow-color
scrollbar-track-color

For Gecko-browsers, you can use the FlexiScroll. Its free for commercial use:

http://www.hesido.com/web.php?page=customscrollbar

Hope this helps!!

How to enable javascript in various browsers – help file


This is a help reference for those sites, which are javascript critical. You can use this in a page to which you redirect in your javascript disabled scenario.

Microsoft Internet Explorer
1. On the Tools dropdown menu, click Internet Options, and then click the Security tab.
2. Click on the earth «Internet» icon, and then the Custom Level button.
3. Scroll to the bottom of the Settings list, and locate the section named Scripting.
4. Under the subsection Active Scripting, click Enable. Click OK.
5. Answer Yes to the confirm box that pops up. Click OK.
6. Reload the page, by clicking the reload button or pressing F5 in the keyboard or select the url in the address bar and click enter key in the keyboard.

Firefox
1. Go to the «Edit» drop-down menu and click on «Preferences…».
2. In the «Category» list, click on «Advanced».
3. Click on «Scripts & Plugins».
3 Click the «Activate Javascript for» option, and then click okay.
4. Reload the page, by clicking the reload button or pressing F5 in the keyboard or select the url in the address bar and click enter key in the keyboard.

Netscape Navigator
1. Go to the «Edit» drop-down menu and click on «Preferences…».
2. In the «Category» list, click on «Advanced».
3 Click the «Enable Javascript for Navigator» option, and then click okay.
4. Reload the page, by clicking the reload button or pressing F5 in the keyboard or select the url in the address bar and click enter key in the keyboard.

Safari
1. Click the Settings (gear symbol) icon in the browser and go to “Preferences”. or press (Ctrl + ,) in your keyboard.
2. Go to the “Security” tab.
3. Check the “Enable Javascript” check box.
4. Close the popup window.
5. Reload the page, by clicking the reload button or pressing F5 in the keyboard or select the url in the address bar and click enter key in the keyboard.

You can use this content in the page, to which you redirect under noscript scenarios. Hope this helps.