5 Awesome JQuery tips and tricks

In the following article, We have compiled a list of 5 absolutely useful JQuery tricks.

Target blank links

Do you use the target=blank attribute on links? If yes, you might know that XHTML 1.0 Strict don’t allow it. A good solution to this problem should be using JQuery to make links opening in new windows:

  this.target = "_blank";

<a href="http://www.lepinskidesign.com.br/" rel="external">lepinskidesign.com.br</a>

Get the total number of matched elements

That what I call a very simple, but very useful tip: This will return the number of matched elements:


Preloading images

When you’re using images in Javascript, a good thing is to preload it before you have to use it. This code will do the job:

jQuery.preloadImages = function()
  for(var i = 0; i<arguments.length; i++)="" {="" jquery("<img="">").attr("src", arguments[i]);

// Usage
$.preloadImages("image1.gif", "/path/to/image2.png", "some/image3.jpg");

Detect browser

Although it is better to use CSS conditional comments to detect a specific browser and apply some css style, it is a very easy thing to do with JQuery, which can be useful at times.

//A. Target Safari
if( $.browser.safari ) $("#menu li a").css("padding", "1em 1.2em" );

//B. Target anything above IE6
if ($.browser.msie && $.browser.version > 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//C. Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//D. Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ) $("#menu li a").css("padding", "1em 1.8em" );

Remove a word in a text

Do you ever want to be able to remove words in a text? Note that the following code can be easily modified to replace a word by another.

var el = $('#id');
el.html(el.html().replace(/word/ig, ""));

Thank you! We hope you like this post.


Please follow and like us:

Leave a Comment

Your email address will not be published. Required fields are marked *