Quantcast

More jQuery and General Javascript Tips to Improve Your Code

Fri, Nov 6, 2009

Development, Javascript

web-design-tutorial

This post pick up on my previous post “jQuery and General Javascript Tips to Improve Your Code” and provides additional nice to know tips for jQuery developers. jQuery is popular for a reason and widely used by nearly everyone from huge companies to bloggers. Even though jQuery is so simple to use and get started with there are great features provided to us that a lot of people is not aware of. I guess that the vast majority of jQuery users tend to look for plugins that solve the challenges at hand and it is often the right strategy. But when it fails it is nice to know that you may be able to do it yourself. Learn the tricks and see where it takes you!

#1 Test and improve you jQuery selector skills

This jQuery selector Lab is really cool and can be used free online and you can even download the lab and use it off-line. There’s a test page with most of the combination of html fields you can imagine and then a very long list of predefined selectors you can try. If that is not enough you can also type in your own selectors.

web-design-tutorial

#2 Test if a jQuery collection contains any elements

If you need to test if a jQuery collection contains any elements you can simply try accessing the first element like this:

if($(selector)[0]){...}
// or you may use
if($(selector).length){...}

Let look at an example:

//ex. if you have this html on a page
<ul id="shopping_cart_items">
  <li><input class="in_stock" name="item" type="radio" value="Item-X" />Item X</li>
  <li><input class="unknown" name="item" type="radio" value="Item-Y" />Item Y</li>
  <li><input class="in_stock" name="item" type="radio" value="Item-Z" />Item Z</li>
</ul>
<pre escaped="true" lang="javascript">...
//The condition in this if statement will evaluate to true because we have two
// input fields that match the selector and the <statement> will be executed
if($('#shopping_cart_items input.in_stock')[0]){<statement>}

#3 Loading latest jQuery version from jquery.org

You can actually load the latest jQuery version using this code:

<script src="http://code.jquery.com/jquery-latest.js"></script>

This is handy if you quickly want to try out an idea for a script with the latest version. As you may know you can also load jQuery from ajax.googleapis.com as shown in #1 - Load the framework from Google Code here.

#4 Use Callback to synchronize Effects

If you want to ensure that events occur one after the other you should use callbacks. Functions allow us to register a callback once the operation is over like this: slideDown( speed, [callback] ) ie. $('#sliding').slideDown('slow', function(){... Try try the example below here.

<style>
 div.button    { background:#cfd; margin:3px; width:50px;
   text-align:center; float:left; cursor:pointer;
   border:2px outset black; font-weight:bolder; }
 #sliding      { display:none; }
</style>
<script>
 
$(document).ready(function(){
// Use jQuery to change look of div once clicked and the event to
//start off the slide effect
 $("div.button").click(function () {
   //div.button will now look like a pushed down button
   $(this).css({ borderStyle:"inset", cursor:"wait" });
   //The hidden #sliding will now slide down and use callback to start the
   //slideup once it completes
   $('#sliding').slideDown('slow', function(){
     $('#sliding').slideUp('slow', function(){
       //once the slide up is over the callback change css for button back
       $('div.button').css({ borderStyle:"outset", cursor:"auto" });
     });
   });
 });
});
</script>

#5 Use Events to control DOM Elements and Custom Objects

One of the most useful parts of jQuery is it’s ability to attach events to objects within a web page. When these events are triggered you can then use a custom function to do pretty much whatever you want with the event.There is a wide range of Events that are supported by jQuery and you will be able to create your own as well. Binding events to page elements doesn't get much easier and elegant here a few examples.

//Bind click event to a paragraph and write click coordinates to the page
$("p").bind("click", function(e){
  var str = "( " + e.pageX + ", " + e.pageY + " )";
  $("span").text("Click at coordinates: " + str);
});
 
//Binding multiple events is also simple and
$("p").bind("mouseenter mouseleave", function(e){
  //toggleClass adds the specified class if it is not present, removes
  //the specified class if it is present.
  $(this).toggleClass("mouse-over");
});

Not only can you bind events to DOM elements as simple as just illustrated. With jQuery you can actually bind a custom event to ANY object. Here is an example.

}
function shoppingCart() {
  // Do general shopping cart stuff here...
};
 
var myShoppingCart = new shoppingCart('personalShoppingCart');
jQuery(myShoppingCart).bind('addItem', function() {
  // Custom event handling for adding items to the shopping cart...
});
 
// Trigger custom event:
jQuery(myShoppingCart).trigger('addItem');
);

#6 Learn to use Custom Selectors

On top of standard CSS selectors jQuery allow you to define custom selectors that makes your code even more simple.

$.expr[':'].mycustomselector= function(element, index, meta, stack){
    // element- is a DOM element
    // index - the current loop index in stack
    // meta - meta data about your selector
    // stack - stack of all elements to loop
 
    // Return true to include current element
    // Return false to explude current element
};
 
// Custom Selector usage:
$('.someClasses:test').doSomething();

Lets take a look at an example. This custom selector will return elements in the scope specified with attribute "rel":

$.expr[':'].withRel = function(element){
  var $this = $(element);
  //simply returning elements where rel is not empty
  return ($this.attr('rel') != '');
};
 
$(document).ready(function(){
//Using the custom selector is simple and the collection returned support chaining
// as illustrated here to apply some css to the returned elements
 $('a:withRel').css('background-color', 'green');
});
...
<ul>
  <li>
    <a href="#">without rel</a>
  </li>
  <li>
    <a rel="somerel" href="#">with rel</a>
  </li>
  <li>
    <a rel="" href="#">without rel</a>
  </li>
  <li>
    <a rel="nofollow" href="#">a link with rel</a>
  </li>
</ul>

#7 Make entire Elements click-able

A lot of menus are created using simple <li> lists and css. It would be nice for the website usability if navigation was provided for the entire <li> and not just for the link text. jQuery makes this possible in a pretty simple way by taking the href (url) from the embedded link.

<ul>
  <li><a href="home">home</a></li>
  <li><a href="home">about</a></li>
  <li><a href="home">contact</a></li>
</ul>
...
//selector select all li within the ul and then we make them clickable.
$("ul li").click(function(){
  //get the url from href attribute and launch the url
  window.location=$(this).find("a").attr("href"); return false;
});

#8 Preloading images

Generally it is a good idea to preload images if they are used in javescripts.

<pre>//Define function that preloads a defined list
//of images (arguments for the function).  
 
jQuery.preloadImages = function(){
  /Loop through the images
  for(var i = 0; i<arguments.length; i++){
    jQuery("<img>").attr("src", arguments[i]);
 
  }
}
// You can use usage the script this way:
$.preloadImages("images/logo.png", "images/logo-face.png", "images/mission.png");

#9 Disable right-click contextual menu

As with other things we have been doing for years using javascript jQuery makes it simpler and more elegant.
Of cause you can use this for much more. You may do something when the contextmenu event is fired.

<pre>
<pre>$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
})

#10 Make code simpler using group queries

A useful way to make the code simpler and easier to read is by grouping the queries for elements that need the same treatment.

// Don't do it like this as it takes up unnecessary space and takes time to write
$('div.close').click(doSomething);
$('button.close').click(doSomething);
$('input.close').click(doSomething);
 
// Simply use group queries in the selector if you have to
//apply same operation to them all
$('div.close, button.close, input.close')
    .click(doSomething);

11. Test your code well

jQuery comes with a unit test framework called QUnit. Writing tests is quite easy and allow you to confidently modify your code while ensuring that it still works as expected. Here is how it works:

<pre>//Separate tests into modules.
module("Module B");
 
test("some other test", function() {
  //Specify how many assertions are expected to run within a test.
  expect(2);
  //A comparison assertion, equivalent to JUnit's assertEquals.
  equals( true, false, "failing test" );
  equals( true, true, "passing test" );
});

web-design-tutorial

Tip! JavaScriptBank.com: provide thousands of free JavaScript codes, free JavaScript tutorials, free JavaScript training videos

Related posts

  1. jQuery and General Javascript Tips to Improve Your Code I have published several articles describing the many benefits...
  2. 10 Useful jQuery Techniques to Improve Your Code jQuery is known for making things that where hard...
  3. 30+ jQuery Plugins to Improve Usability and Look and Feel of HTML Forms Forms are essential for communication online and they are...
  4. jQuery 1.4 Released: Sneak Peek on New Features and Enhancements jQuery 1.4 was just released! First of all a...
  5. 15 jQuery Plugins Giving Web Interfaces Drag ‘N Drop Capabilities Like most others with a great interest in web...

Please subscribe to tripwire magazines rss feed

Please remember to share this post!

7 Comments For This Post

  1. Christophe Says:

    using http://code.jquery.com/jquery-latest.min.js url is better than http://code.jquery.com/jquery-latest.js in production

  2. Tutorial Lounge Says:

    very professional techniques for web developers.

  3. JavaScript Countdown Timer Says:

    very cool & good tip, thank you very much for sharing.

    Can I share this post on my JavaScript library?

    Awaiting your response. Thank

  4. Tutorials Says:

    I found your site on a tutorial directory. We recently launched tutorialgrad.com. It’s similar to those other tutorial sites only easier for you. All you have to do is submit your RSS Feed once, we do the rest. We will check your feed for tutorials and post them daily, all with direct links to your site (we don’t frame your content). If you are interested please check it out and let us know what you think.

  5. tutorial-city Says:

    You can also test your code at http://jslint.com/

  6. rodman Says:

    wow this is such a useful tutorial, thanks for sharing on your blog! I know good tutorials aren’t easy to come by these days, but following this was so easy and it’ll be useful on my website

  7. SMiGL Says:

    Excellent tips

25 Trackbacks For This Post

  1. Tweets that mention More jQuery and General Javascript Tips to Improve Your Code | tripwire magazine -- Topsy.com Says:

    [...] This post was mentioned on Twitter by Louis Gubitosi, Blueprint DesignBlog and Meng To, Web Design. Web Design said: More jQuery and General Javascript Tips to Improve Your Code: This post pick up on my previous post “jQu.. http://bit.ly/2O6NDJ [...]

  2. uberVU - social comments Says:

    Social comments and analytics for this post…

    This post was mentioned on Twitter by webdesignblog09: More jQuery and General Javascript Tips to Improve Your Code http://bit.ly/38BqPx...

  3. More jQuery and General Javascript Tips to Improve Your Code … | PhotoShopped Says:

    [...] Continue reading here: More jQuery and General Javascript Tips to Improve Your Code … [...]

  4. More jQuery and General Javascript Tips to Improve Your Code … Says:

    [...] More jQuery and General Javascript Tips to Improve Your Code … SHARETHIS.addEntry({ title: "More jQuery and General Javascript Tips to Improve Your Code [...]

  5. jQuery & JavaScript Tips to Improve your Code « Code On Fire Says:

    [...] a nice post on TripWire Magazine on improving your JavaScript coding, especially in  [...]

  6. More jQuery and General Javascript Tips to Improve Your Code | tripwire magazine « Netcrema – creme de la social news via digg + delicious + stumpleupon + reddit Says:

    [...] More jQuery and General Javascript Tips to Improve Your Code | tripwire magazinetripwiremagazine.com [...]

  7. Cómo pre-cargar imágenes con jQuery | emenia.es Says:

    [...] Trip Magazine, More jQuery and General Javascript Tips to Improve Your Code Comparte este artículo en tu red [...]

  8. More jQuery and General Javascript Tips to Improve Your Code | Design Newz Says:

    [...] More jQuery and General Javascript Tips to Improve Your Code [...]

  9. ????????????jQuery?(????)javascript?Tips | yuxu's notebook Says:

    [...] magazine?More jQuery and General Javascript Tips to Improve Your Code?????????jQuery?????javascript?Tips????????? [...]

  10. tj mapes » Blog Archive » What I’m Reading (weekly) Says:

    [...] More jQuery and General Javascript Tips to Improve Your Code | tripwire magazine [...]

  11. jQuery Kullan?m?n?z? Geli?tirmek için Öneriler – 2 | CETURK Says:

    [...] Çelik kurtmancelik.wordpress.com Kaynak: http://www.tripwiremagazine.com/ajax/developer-toolbox/more-jquery-and-general-javascript-tips-to-im... Etiketler: JQuery, Kurtman [...]

  12. jQuery Kullan?m?n?z? Geli?tirmek için Öneriler – 2 « KurtMan Çelik Says:

    [...] Çelik kurtmancelik.wordpress.com Kaynak: http://www.tripwiremagazine.com/ajax/developer-toolbox/more-jquery-and-general-javascript-tips-to-im... ?ununla etiketlendi:jQuery bir yorum yaz?n « jQuery Kullan?m?n?z? Geli?tirmek [...]

  13. ??????? » [Web] ???? Says:

    [...] More jQuery and General Javascript Tips to Improve Your Code [...]

  14. links for 2009-11-09 « toonz Says:

    [...] More jQuery and General Javascript Tips to Improve Your Code | tripwire magazine (tags: jquery hack tutorial) [...]

  15. 20+ Awesome jQuery Compilations of Plugins, Tutorials and Cheat Sheets | Programming Blog Says:

    [...] More jQuery and General Javascript Tips to Improve Your Code [...]

  16. ??jQuery?????????-jQuery???? | ?Go Says:

    [...] ????:More jQuery and General Javascript Tips to Improve Your Code ????:????jQuery?????????(?Go) ????: ??:?Go——?????/????/?????/??????????????? ????:http://blog.bingo929.com/jquery-javascript-tips-to-improve-code.html ????????????????????????? [...]

  17. 14???jQuery????? | ???? Says:

    [...] ????:More jQuery and General Javascript Tips to Improve Your Code ????:????jQuery?????????/?GO [...]

  18. 14?js?jQuery???????? - Hobo's Blog Says:

    [...] equals( true, false, "failing test" );equals( true, true, "passing test" );}); ????:More jQuery and General Javascript Tips to Improve Your Code ????:????jQuery?????????/?GO AKPC_IDS += "5444,";Popularity: [...]

  19. More jQuery Tips to Improve Your Code | jQuery Wisdom Says:

    [...] is nice to know that you may be able to do it yourself. Learn the tricks and see where it takes you Web Site Share and [...]

  20. uberVU - social comments Says:

    Social comments and analytics for this post…

    This post was mentioned on Twitter by smile_bug: More jQuery and General Javascript Tips to Improve Your Code: http://tinyurl.com/yhdxqu5...

  21. Tony Miller's blog » jQuery and JavaScript Tips Says:

    [...] http://www.tripwiremagazine.com/2009/11/more-jquery-and-general-javascript-tips-to-improve-your-code... [...]

  22. 10 Useful jQuery Techniques to Improve Your Code | Programming Blog Says:

    [...] If you find this post useful I will recommend that you take a look at these previous posts: [...]

  23. 10 Useful jQuery Techniques to Improve Your Code | Afif Fattouh - Web Specialist Says:

    [...] More jQuery and General Javascript Tips to Improve Your Code [...]

  24. 20/01/2010 : jQuery day | Dev | My Daily Top RSS Selection Says:

    [...] More jQuery and General Javascript Tips to Improve Your Code This post pick up on my previous post “jQuery and General Javascript Tips to Improve Your Code” and provides additional nice to know tips for jQuery developers. jQuery is popular for a reason and widely used by nearly everyone from huge companies to bloggers. [...]

  25. More jQuery and General Javascript Tips to Improve Your Code … | Drakz Free Online Service Says:

    [...] is the original post: More jQuery and General Javascript Tips to Improve Your Code … Share and [...]

Leave a Reply