Showing posts with label howto. Show all posts

jQuery: How many elements were selected

Anyone who used jQuery, starts with a CSS selector to either attach an event or apply some DOM manipulation. The power of jQuery lies in it’s CSS selector. One of the reasons why jQuery become so popular is probably in the concept shift it made to front-end development. Instead of starting your code with javascript function definitions, you start with DOM element selection and straight to your business requirements manipulating those elements. It abstracted away the problems of code structure and let you get on with your needs by selecting the objects you need.

Sometimes your code might require to identify how many elements were selected by jQuery. It might be to identify if there are any elements on the page or to use the number of elements in some other way. For example to set rowspan on your newly created table row. In this post, you will learn how to find out how many elements were selected and see some examples.

jQuery selector returns an array of elements jQuery object that has .length attribute. So the easiest way is to get the length of returned jQuery object. The size of that object will be equal to the number of selected elements. Also, you can use built in jQuery helper function called .size(). It returns the same value as .length property. So you can use .length or .size() depending on your choice, whichever makes your code more readable.

Examples

Assume we have the following HTML structure:

<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
</div>

Here is how you get the number of selected elements and check if there are any elements on the page.

  1. Check the number of elements:

    $('.container').length;  // returns 1
    $('.item').length;       // returns 2
    
    // Same with .size()
    $('.container').size();  // returns 1
    $('.item').size();       // returns 2
  2. Check if there are any elements:

    if($('.container').size() > 0) {
      // There is an element with class "container"
    } else {
      // There is no element with class "container"
    }

Let's see another example. Consider we have the following mark-up for a shopping cart with several order lines in it.

<div class="shopping-cart">
  <div class="order-line">Product 1 – <span>$4.99</span></div>
  <div class="order-line">Product 2 – <span>$9.99</span></div>
</div>

Business requirement: Show a modal box with special offer, if user has more than 1 products in his/her shopping cart.

if($('.shopping-cart .order-line').length > 1) {
  // Show modal box with special offer
}

Bind jQuery events to tab or window close

This post shows you how to bind JavaScript functions that will fire when user navigates away from your page, closes browser or a tab. Browsers have native JavaScript events on window object: unload and beforeunload. beforeunload is a proprietary event introduced by Microsoft and supported by other browsers, but not all.

Please note, these events will be fired when user navigates away from the current page. This includes when user:

  • closes the browser or a tab;
  • clicks on any link (does not matter if it's to other domain or the current domain);
  • types any URL to the browser bar and leaves the page;
  • clicks browser's page reload, back, forward buttons.

NOTE
You must test your code, because the behavior of how browsers handle unload event has changed even in different versions of the browsers.

Catching browser/tab close event with JavaScript

Since unload is a native JavaScript event, we can get away without using jQuery at all.

window.onunload = function(){
    // do some clean up
    clearLocalStorage();
};

If you are using alert(), confirm() or making AJAX requests here, please see what browsers block them belove.

Subscribing to browser/tab close using jQuery

jQuery introduced $.unload() event shorthand in v1.0 and deprecated it in v1.8. $.unload() is a shorthand for .bind('unload', handler).

$(window).unload(function() {
    // Do some code clean up
});

How browsers handle alert(), confirm() and AJAX requests on unload event?

The document unload event was originally designed to let JavaScript to do some clean up. For example, clear or set cookies, but most of the time it is used to fire alert/confirm box or make an AJAX request to the server. This led to bad user experience and browsers started to block these methods in unload event.

Here is what each browser does:

  • Chromer/Safari (WebKit)
    • alert(), confirm() - blocked (confirm() returns false), AJAX request - not sent.
  • Firefox
    • alert(), confirm() - blocked (throws an internal NS_ERROR_NOT_AVAILABLE exception), AJAX requests - sent on page reload, but not on tab close.
  • IE9
    • alert(), confirm() - not blocked, AJAX requests - not sent.
  • Opera
    • alert(), confirm() - blocked, AJAX requests - not sent.

Browsers that have pop-up window blockers will block all window.open() function calls in unload event handler.

All about jQuery plugin manifest file

As it was described in our previous post “How to prepare your plugin for the new jQuery plugins site” you will need to add a manifest file if you want your plugin to appear on the new jQuery plugins site. In this post we will cover everything you need to know about the manifest file, how to format it and where to put it.

What is a jQuery plugin manifest file?

It is a JSON file (not JavaScript literal) that carries all necessary information about your plugin. Information like: plugin name, description, version, author, homepage, licenses, plugin dependencies, etc. The upcoming plugins.jquery.com site will use this data to populate its’ database and create an individual pages for each plugin.

Manifest file naming conventions

The manifest file’s name must be yourpluginname.jquery.json. For example, jTwitter plugins manifest file name would be named: jtwitter.jquery.json. Please be advised, at first the file name was planned to be package.json (following common.js conventions). However, after some discussions it was changed to *.jquery.json.

There is also a concept of suites. Suites are a way to namespace many plugins in a single repository (e.g. jQuery UI would name their fils: ui.tabs.jquery.json). Suites are created manually by jQuery team.

How to prepare your jQuery plugin for the new plugins.jquery.com site

It’s been over a year since the unfortunate event that whipped out the plugins.jquery.com site’s database. But sometimes unfortunate events lead to better things and that’s the case with the Plugins site. Instead of trying to reinvent the wheel and create a website equally useful for plugin users and plugin developers (while fighting spam, maintaining the servers, etc.), the team decided to embrace the power of existing tools. Now plugin developers will maintain their code on GitHub taking full advantage of all its’ features, while jQuery Foundation concentrates on building a better user experience for “plugin users”.

This means that plugin development and maintenance lifecycles are moving over to more confortable and more suitable for this kind of work GitHub platform.

There seems to be a lot of confusion among “plugin users”, that they’ll need to deal with GitHub and such. “NO” – plugin users will see all necessary information about the plugin on a user friendly plugins.jquery.com website.

Dynamically change <title> using jQuery

In this post I will show how to dynamically change document's title using JavaScript and jQuery. Browsing the web (and StackOverflow) I saw a lot of posts that say you can't do it using jQuery. Actually, there is a jQuery syntax that is basically a wrapper for javascript code (see below).

Note: just to clarify, by document title we mean the text that is displayed in the browser window or a tab.

The best way to change the document title is to use native javascript api document.title.

document.title = "New text set by JavasSript";

The equivalent jQuery code of js code above.

$(document).prop('title', 'New text set by jQuery');

Example

Let's say we need to change the tab title text when a user clicks on a button. Here is a jQuery code to do just that:

<html>
<head>
  <title>Initial page title</title>
  <script src="path-to/jquery.js"></script>
  <script>
    $(document).ready(function(){
      $('#clickme').click(function(){
        document.title = $(this).val();
        // jQuery syntax alternative
        // $("title").text( $(this).val() );
      });
    });
  </script>
</head>
<body>
  <input type="button" id="clickme" name="clickme" value="Click me!" />
</body>
</html>

To conclude, you are better off using document.title, because it is cross-browser and has performs better.

Alternative jQuery syntax has been tested in all major browsers.

Add jQuery to your Greasemonkey script

Greasemonkey is a Firefox add-on that lets you run JavaScript on web pages you specify. Using Greasemonkey you can improve and change the way websites look and behave (see examples of what is possible here). To learn more about it see it's official site, to learn how to include and write your own custom scripts (aka "user scripts") visit coder's manual.

Usually Greasemonkey scripts work with the DOM and jQuery is the best way to do that. So, no wonder you'll want to include jQuery into your custom scripts. Here are 3 ways to include jQuery library into your user script.

If you are targeting for Greasemonkey 0.8.0+ you can use @require. It runs once when the script is being installed, hence downloaded once. This is preferred and most efficient way to add jQuery.

// ==UserScript==
// @name     My jQuery Test
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

// Do your magic here
$(".ads").remove();
If you are developing for older versions of Greasemonkey you have 2 options. Either add the whole jQuery library code into your Greasemonkey script file or dynamically add a <script> tag to the page.

Adding jQuery library right in your custom script

// ==UserScript==
// @name     My jQuery Test
// ==/UserScript==

// include jQuery library
/*!
 * jQuery JavaScript Library v1.6.2
 * http://jquery.com/
 *
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2011, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Thu Jun 30 14:16:56 2011 -0400
 */
(function(a,b){function cv(a){return f.isWindow(a)? ...

One more method to add jQuery

One more way to add jQuery is by attaching <script> tag to the document. You can read more about it and grab the code here.

Don't forget to check if jQuery is already loaded

if (unsafeWindow.jQuery === undefined) {
  // jQuery is NOT loaded
} else {
  // jQuery is already loaded
}

JavaScript to detect iPad visitors

This post gives you a short JavaScript function to detect your iPad users. Without any further ado, a javascript code to detect iPad users:

function isiPad(){
    return (navigator.platform.indexOf("iPad") != -1);
}

You can also detect browser version and some other stuff by parsing user agent string. Here is an iPad Safari’s user agent string for your reference:

Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10

Recently a friend of mine got himself an iPad and I couldn’t not notice how his internet browsing device preferences are changing (PC & iPad). More and more people are using hand held devices namely iPad to browse the internet. So it’s about time to show your iPad visitors some love and display your website designed specifically for iPad.

Let’s see how to do this. There are two way:

  1. Redirect iPad visitors
  2. Apply different CSS file for iPad users

Most of the posts on the internet related to iPad user detection are suggesting and showing you how to redirect (including myself in my previous iPhone & iPod detection post). However, I would recommend the second option, applying different CSS file.

You can apply the same technique described in applying different styling for javascript enabled browser with CSS post and apply different CSS rules for iPad visitors.

Sidenote: If you decide to redirect iPad users rather than apply different CSS style rules, than I would recommend using server side detection and redirection. You can see an example PHP code by David Walsh.

iPhone / iPod detection using jQuery & JavaScript

In this post you will learn how to detect iPhone/iPod using javascript/jQuery, redirect your iPhone users to mobile version of your site using javascript and alternative and better way to redirect your visitors using server-side PHP code snippet.

The latest buzz around jQuery is upcoming jQuery mobile – support for mobile devices. Current jQuery core work fine on iPhone and iPod touch browsers and most of us have created a mobile version of our websites, developed or converted websites for others. Basically, jQuery is already being used on iPhone and iPod touch devices. Without any further ado…

Javascript code to detect iPhone and iPod browsers

// Return boolean TRUE/FALSE
function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}

You might wonder why do we even need to detect if our website is ran on iPhone Safari or normal desktop Safar if jQuery works fine on both. Well, there are Safari specific CSS features that you might want to utilize and you need to know if the current browser is Safari, then you may also want to consider reducing resource consuming features like animations for iPhone version of your site.

Redirecting iPhone & iPod users

You may also use this script to redirect iPhone and iPod users to your website’s mobile version:

// Redirect iPhone/iPod visitors
function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}
if(isiPhone()){
    window.location = "mob.example.com";
}

For example: if your website is www.example.com and you have a mobile version at mob.example.com, then put the following script to your www.example.com.

Redirect iPhone users using PHP

It is better to detect and redirect your iPhone users on the server-side. Here is a PHP code to redirect iPhone users:

// Redirect iPhone/iPod visitors
if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') ||
   strpos($_SERVER['HTTP_USER_AGENT'], 'iPod')){
      header("Location: http://mob.example.com");
}

User agent strings for your reference:

/*
User Agent String for iPhone
    Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko)
    Version/3.0 Mobile/1A543a Safari/419.3
    
User Agent String for iPod Touch
    Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko)
    Version/3.0 Mobile/3A101a Safari/419.3
*/

As final words, I would like to remind you that sometimes your visitors would not like to be redirected to mobile versions of your websites. That’s why your mobile version should always include a link to your non-mobile website. The above scripts can be rewrote to check if user has chosen not to be redirected. Either set cookie or a URL parameter.

How to check loaded jQuery UI version?

In this post I will show how to check currently loaded jQuery UI version on the page. Unlike checking loaded jQuery version ( $().jquery ), checking jQuery UI version is a bit different.

Checking currently loaded jQuery UI version on the page:

// Returns jQuery UI version (ex: 1.8.2) or undefined
$.ui.version

// Alternatively
jQuery.ui.version

You would most probably use it in the if statement:

if($.ui && $.ui.version){
    // jQuery UI is loaded
}
You can also check if jQuery UI is loaded or not:
// Checking if jQuery UI is loaded or not
if($.ui){
    // jQuery UI is loaded
}else {
    // jQuery UI is not loaded
}

Dynamically create iframe with jQuery

This article explains and shows how to dynamically create an iframe in your HTML document’s DOM using jQuery and/or JavaScript. It also gives you an example code. This post is not extensive explanation of how to manage and work with iframes using jQuery. This post simply shows you how to dynamically create iframes using jQuery and JavaScript and serves as a note.

Creating iframe is similar to creating any DOM element. All you need to do is to use jQuery factory like this:

// Create an iframe element
$(‘<iframe />’);

// You can also create it with attributes set
$('<iframe id="myFrame" name="myFrame">');

// Finnaly attach it into the DOM
$('<iframe id="myFrame" name="myFrame">').appendTo('body');

Don’t forget that the iframe source is just an iframe’s attribute. So you can set that just like any other attribute.

// Setting iframe's source
$('<iframe />').attr('src', 'http://www.google.com'); 

UPDATE:

As BinaryKitten point’s out below, with jQuery 1.4 you can do it using the following syntax:

// Set attributes as a second parameter
$('<iframe />', {
    name: 'myFrame',
    id:   'myFrame',
    ...
}).appendTo('body');

Cross-domain RSS to JSON converter [jQuery plugin]

No doubt that Web2.0 is one of the best things that happened in our lifetime (besides the internet itself). When we mention Web2.0 first things that come into our minds are AJAX, rounded corners, clean and light layouts and of course RSS feeds. Nowadays, you either provide an RSS feed or consume it in your web app using AJAX/JavaScript.

The only bad thing is that you can not request cross-site content with AJAX requests. Requesting someone else’s RSS in your JavaScript falls into this limitations. One way to overcome this problem is to apply a server-side proxy workaround. However, there is even better solution and workaround – RSS to JSON conversion.

Basically, using Google Feeds API service and jQuery plugin you can request and get any RSS from different domain converted into the JSON object in your javascript.

Let’s see an example of RSS2JSON converter:

<script src="jquery.js"></script>
<script src="jquery.jgfeed.js"></script>
<script>
$.jGFeed('http://twitter.com/statuses/user_timeline/26767000.rss',
  function(feeds){
    // Check for errors
    if(!feeds){
      // there was an error
      return false;
    }
    // do whatever you want with feeds here
    for(var i=0; i<feeds.entries.length; i++){
      var entry = feeds.entries[i];
      // Entry title
      entry.title;
    }
  }, 10);
</script>

In order to have universal client-side RSS to JSON converter you first need to include jquery.js and Google Feeds API plugin jquery.jgfeed.js. Then use jQuery plugin and Google Feeds API to get reliable and fast RSS to JSON(P) converter.

The code above gets Twitter RSS feeds in JSON format and does whatever it wants with it. Great workaround isn’t it :)

To see jGFeed()’s argument lists and how to use it please read this post.

Create callback functions for your jQuery plugins & extensions

Most of the time custom jQuery plugins and extensions that we create do not use a callback functions. They usually simply work on DOM elements or do some calculations. But there are cases when we need to define our own custom callback functions for our plugins. And this is especially true when our plugins utilize AJAX querying.

Let’s say our custom jQuery extension gets data by making some AJAX request.

$.extend({
  myFunc : function(someArg){
    var url = "http://site.com?q=" + someArg;
    $.getJSON(url, function(data){

        // our function definition hardcoded

    });
  }
});

What is bad in this jQuery code is that the callback function is defined and hardcoded right in the plugin itself. The plugin is not really flexible and its user will have to change the plugin code, which is bad!

So the solution is to define your own custom callback function argument. Here is how it is done:

$.extend({
  myFunc : function(someArg, callbackFnk){
    var url = "http://site.com?q=" + someArg;
    $.getJSON(url, function(data){

      // now we are calling our own callback function
      if(typeof callbackFnk == 'function'){
        callbackFnk.call(this, data);
      }

    });
  }
});

$.myFunc(args, function(){
  // now my function is not hardcoded
  // in the plugin itself
});

The above code shows you how to create a callback function for AJAX load, but if you want to create a simple callback function for your jQuery plugin, for example the one that executes on your own custom events. To achive this you can do the following:

$.extend({
  myFunc : function(someArg, callbackFnk){
    // do something here
    var data = 'test';
 
    // now call a callback function
    if(typeof callbackFnk == 'function'){
      callbackFnk.call(this, data);
    }
  }
});

$.myFunc(someArg, function(arg){
  // now my function is not hardcoded
  // in the plugin itself
  // and arg = 'test'
});

Get URL parameters & values with jQuery

In this post, I would like to share a little jQuery code snippet that makes getting URL parameters and their values more convenient.

Recently, while working on one of my projects, I needed to read and get parameter values from URL string of the current page that was constructed and sent by PHP script. I came across this short and sweet JavaScript code snippet by Roshambo that does just that.

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

The function returns an array/object with your URL parameters and their values. For example, consider we have the following URL:

http://www.example.com/?me=myValue&name2=SomeOtherValue

Calling getUrlVars() function would return you the following array:

{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}

To get a value of first parameter you would do this:

var first = getUrlVars()["me"];

// To get the second parameter
var second = getUrlVars()["name2"];

To make the script syntax to look more jQuery like syntax I rewrote it as an extension for jQuery:

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

Now, if you include the above code in your javascript file, you can get URL parameter values in the following way:

// Get object of URL parameters
var allVars = $.getUrlVars();

// Getting URL var by its nam
var byName = $.getUrlVar('name');

That’s it! You might also find the following jQuery related articles on this blogs interesting:

  1. Cross-domain AJAX querying with jQuery
  2. Javascript for() loop vs jQuery .each() performance comparison
  3. Create jQuery custom selectors with parameters
  4. JavaScript / jQuery password generator

jQuery.noConflict – Resolving conflicts with other javascript libraries that use $() function

One of the reasons that make a software popular is its extensions and plugins. jQuery has plenty of plugins that do almost anything you want, from simple button hide to full blown galleries. Plugins let non developers easily add functionality they need to their websites and there are times when one might include more than one javascript library such as prototype.js, YUI or mootools with jQuery. They all use $ as their main function name. Including second library might brake the behavior of the first one. To resolve such cases jQuery introduces .noConflict() method.

When you call .noConflict() jQuery will return $() to it’s previous owner and you will need to use jQuery() instead of shorthand $() function.

.noConflict() usage example (From jQuery Docs site)

<html>
  <head>
  <script src="prototype.js"></script>
  <script src="jquery.js"></script>
  <script>
    jQuery.noConflict();
    // Use jQuery via jQuery(...)
    jQuery(document).ready(function(){
        jQuery("div").hide();
    });
    // Use Prototype with $(...), etc.
    $('someid').hide();
  </script>
  </head>
  <body></body>
</html>

You can also use the following code snippets to still use $() in your code, but with one drawback, you will not have access to your other library’s $() method.

// Method 1
jQuery(document).ready(function($){
    $("div").hide();
});

// Method 2
(function($) {
    /* some code that uses $ */ 
})(jQuery);

TIP:
Don’t forget that you can always assign jQuery to any other variable name to use it as your shorthand: var $_ = jQuery;

Identifying & locating mouse position in jQuery

While writing the next jQuery tutorial I needed to identify and locate where the mouse was on the page. Tracking mouse position on the page with jQuery is easy. You don’t need to check what browser the script is running like it is used to be with plain JavaScript. To identify where the mouse is in jQuery all you have to do is to read event object’s .pageX and .pageY properties.

Example:

$().mousemove(function(e){
   // e.pageX - gives you X position
   // e.pageY - gives you Y position
});

The above jQuery code is binding a new ‘on mouse move’ event to the current document and triggered every time mouse moves. The coordinates are calculated in pixels from top left corner of the document. See the above code in action.

You may also want to know the coordinates of the mouse relative to some <div> or an element. Since jQuery returns mouse position relative to the document root, by subtracting element’s position from document root you get mouse positions relative to that element. Long story short here is the code to do just that:

$("#someDiv").click(function(e){
    var relativeX = e.pageX - this.offsetLeft;
    var relativeY = e.pageY - this.offsetTop;
});

Don’t forget that you can bind any mouse event to any element and then get mouse positions. You can easily create a draggable object with click and mousemove events by simply setting the CSS top and left values to .pageX and .pageY.

Anyway, that’s how you locate and handle mouse positions in jQuery. As always, you don’t need to worry about cross browser compatibility issues while using jQuery. To learn more see more examples here.

jQuery custom selectors with parameters

My last tutorial on how to create a custom jQuery selector showed you the basics of creating custom filters in jQuery. Now, it is time to get more serious with selectors and create more advanced jQuery selectors – custom jQuery selectors with parameters. To get an idea of what I am talking about think of :contains(someText) selector.

Anyway, let’s create our own jQuery selector that takes arguments. The basic syntax is the same:

$.expr[':'].test = function(obj, index, meta, stack){
    /* obj - is a current 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
    */
};

meta is a parameter we are interested in. meta is an array that carries an information about our selector. Here is what it looks like:

$('a:test(argument)');
//meta would carry the following info:
[
    ':test(argument)', // full selector
    'test',            // only selector
    '',                // quotes used
    'argument'         // parameters
]

$('a:test("arg1, arg2")');
//meta would carry the following info:
[
    ':test('arg1, arg2')', // full selector
    'test',                // only selector
    '"',                   // quotes used
    'arg1, arg2'           // parameters
]

Here as you can see, we can make use of the arrays fourth (meta[3]) value to get a hang of our parameters.

Creating custom jQuery selector with parameters

Now, let’s improve our selector from previous post that selects all links with non empty rel attribute and make it select any element with specified non empty attribute. Here is the code to do just that:

$.expr[':'].withAttr = function(obj, index, meta, stack){
  return ($(obj).attr(meta[3]) != '');
};

See it in action here.

Find & select all external links with jQuery

Selecting all external links and amending them in some way is probably one of the most used jQuery tutorials. By selecting all anchor links on the page and for example adding a CSS class with only one jQuery line shows how jQuery is simple and powerful. Also if you are progressively enhancing your website this is one of the trick you might use.

Actually, I had to select all external links and add an image that indicates it the other day. So, I created a custom jQuery selector called :external that makes finding external links easier for you. (Read “Custom jQuery Selectors” post to learn how to create your own custom selectors)

External links custom jQuery selector code:

// Creating custom :external selector
$.expr[':'].external = function(obj){
    return !obj.href.match(/^mailto\:/)
            && (obj.hostname != location.hostname);
};

// Add 'external' CSS class to all external links
$('a:external').addClass('external');

You can see this code in action here.

You may use the code above to:

  • Add CSS class to all external links
  • Dynamically add an image after the link to indicate that it is an external link
  • Bind a click event to track what links where clicked
  • etc.

Update: The return part was update to take into the account the mailto links as suggested in comments by Phillipp and Karl below.

Custom jQuery selectors

jQuery makes it easy to select elements you need using CSS selectors. It is undoubtedly one of the jQuery features that makes it a great javascript library. On top of standard CSS selectors jQuery introduces some custom selectors that makes your code even more simpler and easier to read.

Examples of custom jQuery selectors are: :header, :even, :odd, :animated, :contains(text), etc.

And the best part is that jQuery lets you create and define your own custom selectors using custom selector creation template below.

jQuery Custom Selector Creation Template:

$.expr[':'].test = function(obj, index, meta, stack){
    // obj - is a current 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
};

// Usage:
$('.someClasses:test').doSomething();

Let’s now create a very simple custom selector using the template above. Let’s say we want a custom jQuery selector that will return elements with nonempty rel attribute.

$.expr[':'].withRel = function(obj){
  var $this = $(obj);
  return ($this.attr('rel') != '');
};

// Usage:
$('a:withRel').css('background-color', 'yellow');

The code above creates a custom selector that will select only elements with not empty rel attributes. Here is the above code’s demo page.

You might also be interested in reading about jQuery custom functions.

UPDATE: Read about creating custom jQuery selectors with parameters.

Tip for jQuery & handheld device developers

This week’s usual “Friday short post” about using jQuery in handheld devices. If you are a developer who is using jQuery in applications that were developed for use in environments with small processing power such as handheld devices, mobile phones, PDA’s, etc. you will find this post useful.

Anyway, back to the topic. For whatever reasons you chose to use jQuery in your application (I would suggest using plain javascript for better performance) jQuery effects such as animation, hide and show, etc. most likely were probably one of the reasons. Unfortunately, jQuery effects are process intensive and in “slow” environments it is recommended to turn them off. Fortunately, jQuery provides you with such a method. It lets you disable all animations and effects by changing jQuery.fx.off setting to true.

// Dissable all effects
jQuery.fx.off = true;

// Shorthand
$.fx.off = true;

Now all your effects such as fadeIn(), fadeOut(), slideDown(), slideUp(), etc. will not be animated. They will simply be hidden and shown immediately (by changing CSS rules display:none; display:block;) to save CPU processing time.

NOTE:
By setting the jQuery.fx.off back to false you enable all animations and effects.

Remove n’th table column - jQuery plugin

My usual short Friday post. Today I would like to share with you a new utility I wrote to work with HTML tables. We already have jQuery functions to add table row, remove table row (on user click), add table row number plugin and now here is jQuery code to remove table column.

jQuery utility to remove table’s n’th column:

$.fn.removeCol = function(col){
    // Make sure col has value
    if(!col){ col = 1; }
    $('tr td:nth-child('+col+'), tr th:nth-child('+col+')', this).remove();
    return this;
};

Just add this code to your javascript file and use it in your jQuery code like this:

// Remove all table's second columns
$('table').removeCol(2);

// Remove table's first column (default)
$('table').removeCol();

The function takes column number to delete as an argument and removes that column. If you don’t supply any column number it removes the first table column by default.