Who doesn't like JQuery? This fast and easy to use Javascript framework became very popular in 2008. In the following article, I have compiled a list of 8 absolutely useful JQuery hacks, tips and 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:

$('a[@rel$='external']').click(function(){
  this.target = "_blank";
});

/*
Usage:
<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:

$('element').size();

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").attr("src", arguments[i]);
  }
};

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

Detect browser

Although it is better to use CSS conditionnal 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 wanted 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, ""));

Columns of equal height

This seems to be a highly-requested hack: How to use two CSS columns, and make them having exactly the same height? Happilly Rob from cssnewbie have the solution.

function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

/*
Usage:
$(document).ready(function() {
    equalHeight($(".recent-article"));
    equalHeight($(".footer-col"));
});
*/

Source: Equal Height Columns with jQuery

Font resizing

Font Resizing is a very common feature in many modern websites. Here’s how to do it with JQuery.

$(document).ready(function(){
  // Reset Font Size
  var originalFontSize = $('html').css('font-size');
    $(".resetFont").click(function(){
    $('html').css('font-size', originalFontSize);
  });
  // Increase Font Size
  $(".increaseFont").click(function(){
    var currentFontSize = $('html').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*1.2;
    $('html').css('font-size', newFontSize);
    return false;
  });
  // Decrease Font Size
  $(".decreaseFont").click(function(){
    var currentFontSize = $('html').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*0.8;
    $('html').css('font-size', newFontSize);
    return false;
  });
});

Source: Text Resizing With jQuery

Disable right-click contextual menu

There’s many Javascript snippets available to disable right-click contextual menu, but JQuery makes things a lot easier:

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

Source: Fast Tip: How to cancel right click context menu in jQuery

Related Posts

No related posts.
 

77 Comments

  1. Posted March 12, 2009 at 11:17 am | Permalink

    Nice tips!

    JQuery – my new favourite thing :)

  2. Gaston
    Posted March 12, 2009 at 11:45 am | Permalink

    Very nice.

    I use JQuery since I begin to use javascript and it is really awesome. Easy, lot of plugins …

    Those little tips can be very usefull

  3. Posted March 12, 2009 at 12:39 pm | Permalink

    jQuery really a nice framework. thumbs up

  4. Posted March 12, 2009 at 2:52 pm | Permalink

    nice article… very useful… thnx for sharing …

  5. Posted March 12, 2009 at 2:56 pm | Permalink

    Be nice if someone wrote these tips and tricks for Mootools as well ;)

  6. Posted March 12, 2009 at 2:58 pm | Permalink

    @shakaran: Nice idea, I should think about it for a future post :)

  7. Posted March 12, 2009 at 3:02 pm | Permalink

    @Jean-Baptiste Jung: Wow! I’m willing to read it.

  8. Posted March 12, 2009 at 3:04 pm | Permalink

    Really, its 7 awesome tips as I don’t think right-click should ever be disabled on any site.

    The remove text tip will come in very handy, thanks!

  9. Posted March 12, 2009 at 3:33 pm | Permalink

    superb tricks… simple but effective

  10. Posted March 12, 2009 at 4:16 pm | Permalink

    I just reached a point in a project where I needed a handy way to preload images using jQuery…

    BAM! I was notified of this post.

    The preload function seems wrong though…

    @Tom Kenny I agree about disabling right clicks, not a very nice thing to do…

    Keep up the good work!

  11. Posted March 12, 2009 at 4:22 pm | Permalink

    I agree with you about disabling right click, this isn’t a good thing to do. I inclued this tip in the list for two reasons:
    -This is a good proof of JQuery possibilities
    -MANY people still wanna do this

    Thanks for the great feedback on the article!

  12. Posted March 12, 2009 at 4:37 pm | Permalink

    I appreciate that many people still want to disable right-click but I don’t think we should be encouraging people to do so. We should be discouraging it. :)

  13. Posted March 12, 2009 at 4:47 pm | Permalink

    just learning jquery, simple and powerful (i think)…..

  14. Posted March 12, 2009 at 5:29 pm | Permalink

    Great, nice info, just what i needed!

  15. chris
    Posted March 12, 2009 at 6:06 pm | Permalink

    Awsome job on the preloading, nice and simple. Simple as it is I don’t understand it. in my editor it seems as though the ” are wrong? probably something to do with: i”) – would you mind explaining the code?

    Thanks!

  16. chris
    Posted March 12, 2009 at 6:21 pm | Permalink

    As a followup to my last post, it is exactly as i thought, the code doesn’t work. updated version:

    jQuery.preloadImages = function(){
    jQuery.each(arguments,function(i){
    $(arguments[i]).attr(”src”, arguments[i]);
    });
    };

    still not convinced this works though, any graceful way of testing?

  17. Posted March 12, 2009 at 6:25 pm | Permalink

    There is indeed something wrong with the preloading script.

    Any ideas?

  18. Dylan
    Posted March 12, 2009 at 6:33 pm | Permalink

    The latest version of jQuery has deprecated the $.browser & browser detection. In it’s place is $.support & feature detection.

  19. Posted March 12, 2009 at 7:12 pm | Permalink

    @Adam – The problem is likely that you are using jQuery 1.3+. They removed the @ symbol from the selector engine.

    Also, I really like the equal height thing, but might I suggest passing in just a selector instead of a group? That would allow give you a lot more flexibility. You could still pass in a group if you really wanted to, but now you can just have a selector.

    function equalHeight(selector) {
    var max = 0;
    $(selector)
    .each(function() {
    max = Math.max(max, $(this).height());
    })
    .height(max);
    }

  20. Posted March 12, 2009 at 7:14 pm | Permalink

    I tried writing a quick image preloaded with jQuery awhile ago and ran into a world of problems. Each browser treats image loading differently. FF will queue all the images and load them in order, IE will load a little bit of each one, Safari will choke on the whole thing.

    I ended up writing my own with the least amount of bulk possible that would make it work across all browsers.

    *shameless plug*
    http://blog.152.org/2008/01/javascript-image-preloader.html

  21. Posted March 12, 2009 at 7:59 pm | Permalink

    Overall, nice collection.

    I’ve actually had problems with that equal height columns function every time I’ve tried to use it.

  22. Posted March 12, 2009 at 8:03 pm | Permalink

    As far as the ‘_blank’ target for links, why not give the user full control?

    *another shameless plug*
    http://smple.com/link-control/

  23. Posted March 12, 2009 at 8:43 pm | Permalink

    thanks for the tips, i’m just getting into jquery and it seems like it’ll solve alot of problems for me.

  24. yeah
    Posted March 12, 2009 at 8:51 pm | Permalink

    @tommy

    Never say never. I’ve seen plenty of examples where right clicking was totally disabled. It had more to do with people being able to still high rez images than anything but thats still an example

  25. Posted March 12, 2009 at 10:44 pm | Permalink

    thanks for ur tips

  26. Posted March 13, 2009 at 5:31 am | Permalink

    I think remove text tip is not good.
    it will break HTML structure.
    e.g.
    var el = $(’#id’);
    el.html(el.html().replace(/div/ig, “”));

    I preferr the following code.

    $(’#id’).find(’*').andSelf()
    .contents().not(’[nodeType=1]‘)
    .each(function(){
    this.textContent = this.textContent.replace(/word/ig,”);
    });

  27. dennis
    Posted March 13, 2009 at 6:01 am | Permalink

    You can disable anything you want, encapsulate it in flash, whatever…it’s still a resource and needs to be loaded; if I want it, I can use any number of tools to identify what it’s source is (fiddlerTool, and various other plugins/native browser tools) and snag it… Leave the browsers native functionality in place, theres no way to prevent anyone with a desire from getting what they want. If need be I’ll just rewrite your code from inside the browser to gain the desired item.

  28. ajpiano
    Posted March 13, 2009 at 7:49 am | Permalink

    that preload images script is syntax error city

  29. poppler
    Posted March 13, 2009 at 7:49 am | Permalink

    Update to 1.3. Some of your recommendations are deprecated.

  30. Posted March 13, 2009 at 9:17 am | Permalink

    Very useful! thanks for the tips.

    @heziabrass

  31. Posted March 13, 2009 at 10:04 am | Permalink

    Great Stuff…

    I often use the following:

    Target blank links
    Preloading images

    Regards
    J

  32. Posted March 13, 2009 at 10:27 am | Permalink

    When “removing words” you’ll probably want to check for word boundaries or spaces, otherwise you could be removing it from the middle of longer words. Additionally you’re replacing the entire HTML content meaning that attribute names/values will also be affected. I would suggest traversing through text nodes and replacing text one by one. Or, use $().text() instead of $().html().

    And instead of having to add rel=external manual why not just make the whole process automatic:
    $(’a[href^=http://]:not[href^=http://' + window.location.hostname + ']‘).addClass(’external’);

    One more thing: NEVER EVER DISABLE THE CONTEXT MENU. This severely impairs the usability of your site.

  33. Posted March 14, 2009 at 12:31 am | Permalink

    i like this ” Disable right-click contextual menu” because i don’t want someone copy something from my blog but they can do with another way , thanks for this codes .

  34. Jany
    Posted March 15, 2009 at 8:40 am | Permalink

    Money Academy, hide you precious blog under the rock but keep your hands off my right-click.

  35. Posted March 16, 2009 at 6:48 am | Permalink

    One of the Blog which I read on the regular basis was WP Hacks and Now it would be Cats who Code.. along with WP hacks… By the Way Nice information…. would try it….

  36. Posted March 16, 2009 at 11:54 am | Permalink

    Thanks for the tricks. but, i would like to know where should i put this code so that it can be accessed by the wordpress.

    for ex: the 1st trick target=”_blank”. for this where i need to put that javascript code which checks rel=external and adds target=”_blank”

  37. Posted March 16, 2009 at 7:23 pm | Permalink

    jQuery is interesting. I was trying to play with the coding the other day and found myself in a mess. Your post enlighten me on how jQuery works. :-)

  38. Posted March 16, 2009 at 8:25 pm | Permalink

    In #1 the @ has been deprecated awhile and no longer works in the latest versions. Don’t use it with “rel”, “href” or other attr lookup.

    A nice touch is to add a tool tip that warns about the link leaving the site and/or opening in a new window. Also, you can just look at the href attribute and drop the rel thing. No need to include the rel in the HTML or create it with JS.

    $(’a[href^="http"]‘)
    .attr({
    target: “_blank”,
    title: “This link directs you to an external website and will open in a new window.”
    });

  39. Posted March 16, 2009 at 8:37 pm | Permalink

    for more advanced handling of external links (as well as a way to detect which links are external automatically) have a look at my $.externalify plugin: http://informationarchitech.com/externalify/ (or search the jquery plugins directory)

  40. Posted March 17, 2009 at 3:08 am | Permalink

    Love the font resizing one, magic stuff!

    Although wouldn’t the browser detect one just be easier done in PHP?

  41. Posted March 17, 2009 at 8:17 pm | Permalink

    Nice tips! Very useful and great content on you blog, I think I will come here more ;)

  42. Posted March 17, 2009 at 9:24 pm | Permalink

    Really great post. I bet you got alot of traffic out of it, I know I did when I put a list of Wordpress tips on my site.

  43. Posted March 18, 2009 at 2:33 am | Permalink

    For those of you who noticed the preloading images script is wrong, the correct script is here: http://www.mattfarina.com/2007/02/01/preloading_images_with_jquery

  44. Posted March 18, 2009 at 8:01 am | Permalink

    I hate the disabling of the right click.

    Just goes against the way of the web.

  45. Posted March 23, 2009 at 10:10 pm | Permalink

    I think disabling right click has some uses. Atleast the novice user of computer cannot easily copy material from your blog.

  46. Posted March 24, 2009 at 9:45 pm | Permalink

    Jquery is ultimate tool of today, and learning new tips and tricks is never boring, as every one has its usefulness. Thanks for sharing.

  47. Posted April 8, 2009 at 12:51 pm | Permalink

    just learning jquery, simple and powerful (i think)….

  48. Posted April 13, 2009 at 7:32 pm | Permalink

    Good little collection! Definetly very helpful.

  49. Posted April 15, 2009 at 8:26 am | Permalink

    Jquery is awesome, I am disappointed I have not learned it sooner. This is a great primer to get your feet wet!

  50. Posted April 20, 2009 at 1:31 pm | Permalink

    JQuery really is a superb framework, there’s so much you can achieve with very little effort by using it. The image preloading function is especially useful and something I’m looking into right now.

  51. Posted April 22, 2009 at 11:09 pm | Permalink

    Is Jquery Javascript of Java?

  52. Posted April 24, 2009 at 11:04 am | Permalink

    Great tips. I need to first find out on the Net what is JQuery framework. how does it work.

  53. Posted April 24, 2009 at 4:34 pm | Permalink

    @Future: JQuery is Javascript-Framework

  54. Posted April 27, 2009 at 6:44 pm | Permalink

    Now every good webdesigner should use jquery to work…

  55. Posted May 3, 2009 at 11:28 pm | Permalink

    Nice tips…I’ll try!
    Thanks.

  56. Posted May 8, 2009 at 7:17 am | Permalink

    That columns of equal height just saved my life, very useful,
    Thanks

  57. Posted May 8, 2009 at 1:51 pm | Permalink

    I just learned about jquery recently and known that it is very useful! Should have known about this earlier. Great post by the way!

  58. Posted May 11, 2009 at 8:49 am | Permalink

    Always seeking for good tips and tricks, i found much fresh tips more like Detect browser, thank you providing great source.

  59. Posted May 14, 2009 at 1:07 am | Permalink

    Thanks for the great jquery tips. We recently started using it on several of our client’s websites and are undergoing a redesign ourselves and will be using it on our portfolio page, but I had no idea that it could be used for so many other things like font resizing. I am excited to try some of these out.

  60. Posted May 19, 2009 at 1:38 am | Permalink

    Everything thus far, has gone pretty smooth for me. Thanks for an outstanding job, will keep ya posted.

  61. Posted May 24, 2009 at 6:27 pm | Permalink

    great tips, thanks!

  62. Posted May 29, 2009 at 1:07 pm | Permalink

    Haha these are very simple but useful tips. They could become handy in the future. Thanks a lot!

  63. Posted June 4, 2009 at 6:57 pm | Permalink

    I learned the similar skill 6 years ago while studying Javascript. I can see several application/online applications who are purely built in such technologies. Thanks for sharing the tips.

  64. Posted June 6, 2009 at 12:20 pm | Permalink

    I dont want to say more but it is really a fantastic tips!

  65. Posted June 17, 2009 at 8:38 pm | Permalink

    Can you use JQuery to prevent someone from looking at the browser code?

  66. Posted July 29, 2009 at 10:14 am | Permalink

    Thanks for these nice tips!

  67. avo
    Posted August 23, 2009 at 5:47 pm | Permalink

    Great, very useful tips. Except #1
    “you shouldn’t use target=_blank because xhtml does not allow it, so instead use javascript to insert the not allowed content in the page”
    I can’t quite follow the reasoning of that one :-P

  68. Amol
    Posted September 25, 2009 at 10:59 am | Permalink

    This article is just Awesome

    Thanks and regards,
    Amol A. Bhavsar

  69. Posted October 15, 2009 at 6:13 am | Permalink

    Thanks for the tips you had just what I was looking for.

    I agree with those saying not to disable right clicking. It’s pointless and just creates a pain for those who know how to get around it.

  70. Charlie Epes
    Posted October 26, 2009 at 5:02 pm | Permalink

    Regarding “Removing a Word in a Text”

    Hi:
    Will you tell me where in this code I plug in my “word” or other variables?

    var el = $(’#id’);
    el.html(el.html().replace(/word/ig, “”));

    Thanks-
    Charlie Epes

  71. Posted November 2, 2009 at 3:04 am | Permalink

    thanks for the list! my 2 cents below..

    blocking right click is pretty pointless as there are 100’s of other ways of getting source code. seems so obvious yet I am surprised how many people consider this tip useful.

    image preloading… better use sprites and save traffic

    conditional statements… you mentioned you can use cond. statements to target browsers.. how would you target safari with conditional statements?

    @Avo .. target=”_blank” dosen’t validate to xhtml1.0/aaa and this tip is right on the spot

  72. Posted November 30, 2009 at 10:35 pm | Permalink

    Great information!

    Jquery is awesome, I am disappointed I have not learned it sooner. This is a great primer to get your feet wet!

  73. Posted December 16, 2009 at 9:57 am | Permalink

    Preloading images not working :(

  74. Prabhu
    Posted February 16, 2010 at 3:19 am | Permalink

    i need help… how can i detect browser close event and that time jquery popup confirm box will come… is it possible to make it out…. if any one knows help me to find out solution…
    thanks

  75. Posted March 3, 2010 at 1:55 pm | Permalink

    helped me a lot !

  76. Posted March 3, 2010 at 5:33 pm | Permalink

    Nice tips.Thanks !

  77. Posted March 15, 2010 at 8:19 am | Permalink

    Really cool snippets! Thanks

14 Trackbacks

  1. [...] » 8 awesome JQuery tips and tricks [...]

  2. [...] 从这里参考来的。 [...]

  3. [...] 8 awesome JQuery tips and tricks (tags: webdesign tips javascript jquery) [...]

  4. By Coderies | taggle.org on March 17, 2009 at 8:39 pm

    [...] 8 trucs sympas pour jQuery [...]

  5. [...] 8 awesome JQuery tips and tricks a list of 8 absolutely useful JQuery hacks, tips and tricks. (tags: javascript tutorial webdev jquery tips) [...]

  6. [...] 8 awesome JQuery tips and tricks [...]

  7. [...] 英文原稿:8 awesome JQuery tips and tricks | CatsWhoCode 翻译整理:8 个 JQuery 技巧和窍门 | 芒果 [...]

  8. [...] Tips and Tricks links of JQuery 1. 8 awesome JQuery Tips and Tricks [...]

  9. [...] 英文原稿:8 awesome JQuery tips and tricks | CatsWhoCode 翻译整理:8 个 JQuery 技巧和窍门 | 芒果 [...]

  10. [...] 8 awesome JQuery tips and tricks [...]

  11. By frontend.lt » Nuorodos #2 on September 27, 2009 at 3:11 pm

    [...] 20 jQuery Tips and trics, 8 awesome jQuery tips ir 7 tips for better jQuery code – iÅ¡renku pačius įdomiausius ir naudingiausius [...]

  12. By 10 jQuery snippets for efficient developers on December 14, 2009 at 6:09 pm

    [...] » Source [...]

  13. [...] –> source [...]

  14. [...] jQuery.  This is the one I’m most excited about at the moment.  Because jQuery makes life worth living, I want to be able to allow some (read: a carefully vetted elite group of users who WON’T [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Smashing Network
WordPress Appliance - Powered by TurnKey Linux