10 jQuery snippets every designer should know

jQuery is used on thousands upon thousands of web pages. It’s one of the most common libraries to insert into pages, and it makes DOM manipulation a snap.

Of course, part of jQuery’s popularity is its simplicity. It seems we can do almost anything we like with this powerful library.

For all the options open to us, there are some snippets we tend to come back to time and time again. Today I’d like to give you 10 snippets that everyone, newbies to gurus, will use time and time again.

 

1) Back to top button

// Back To Top
$('a.top').click(function(){
$(document.body).animate({scrollTop : 0},800);
return false;
});

//Create an anchor tag
<a class=”top” href=”#”>Back to top</a>

As you can see using the animate and scrollTop functions in jQuery we don’t need a plugin to create a simple scroll to top animation.

By changing the scrollTop value we can change where we want the scrollbar to land, in my case I used a value of 0 because I want it to go to the very top of our page, but if I wanted an offset of 100px I could just type 100px in the function.

So all we are really doing is animating the body of our document throughout the course of 800ms until it scrolls all the way to the top of the document.

 

2) Checking if images are loaded

$(‘img’).load(function() {
console.log(‘image load successful’);
});

Sometimes you need to check if your images are fully loaded in order to continue with your scripts, this three line jQuery snippet can do that for you easily.

You can also check if one particular image has loaded by replacing the img tag with an ID or class.

 

3) Fix broken images automatically

$('img').error(function(){
$(this).attr('src', ‘img/broken.png’);
});

Occasionally we have times when we have broken image links on our website and replacing them one by one isn’t easy, so adding this simple piece of code can save you a lot of headaches.

Even if you don’t have any broken links adding this doesn’t do any harm.

 

4) Toggle class on hover

$(‘.btn').hover(function(){
$(this).addClass(‘hover’);
}, function(){
$(this).removeClass(‘hover’);
}
);

We usually want to change the visual of a clickable element on our page when the user hovers over and this jQuery snippet does just that, it adds a class to your element when the user is hovering and when the user stops it removes the class, so all you need to do is add the necessary styles in your CSS file.

 

5) Disabling input fields

$('input[type="submit"]').attr("disabled", true);

On occasion you may want the submit button of a form or even one of its text inputs to be disabled until the user has performed a certain action (checking the “I’ve read the terms” checkbox for example) and this line of code accomplishes that; it adds the disabled attribute to your input so you can enable it when you want to.

To do that all you need to do is run the removeAttr function on the input with disabled as the parameter:

$('input[type="submit"]').removeAttr("disabled”);

 

6) Stop the loading of links

$(‘a.no-link').click(function(e){
e.preventDefault();
});

Sometimes we don’t want links to go to a certain page or even reload it, we want them to do something else like trigger some other script and in that case this piece of code will do the trick of preventing the default action.

 

7) Toggle fade/slide

// Fade
$( “.btn" ).click(function() {
$( “.element" ).fadeToggle("slow");
});

// Toggle
$( “.btn" ).click(function() {
$( “.element" ).slideToggle("slow");
});

Slides and Fades are something we use plenty in our animations using jQuery, sometimes we just want to show an element when we click something and for that the fadeIn and slideDown methods are perfect, but if we want that element to appear on the first click and then disappear on the second this piece of code will work just fine.

 

8) Simple accordion

// Close all Panels
$('#accordion').find(‘.content').hide();
// Accordion
$('#accordion').find(‘.accordion-header').click(function(){
var next = $(this).next();
next.slideToggle('fast’);
$(‘.content’).not(next).slideUp('fast’);
return false;
});

By adding this script all you really need to on your page is the necessary HTML go get this working.

As you can see in this snippet I firstly closed all the panels in our accordion and then on the click event I made the content that is linked to that header slide toggle , and all the other ones slide up. It’s a simple method for a quick accordion.

 

9) Make two divs the same height

$(‘.div').css('min-height', $(‘.main-div').height());

Sometimes you want two divs to have the same height no matter what content they have in them, this little snippet enables just that; in this case it sets the min-height which means that it can be bigger than the main div but never smaller. This is great for masonry like websites.

 

10) Zebra stripped unordered list

$('li:odd').css('background', '#E8E8E8’);

With this little snippet you can easily create zebra striped unordered lists, this places the background you define on every odd list item so that you can place the default one for the even ones in your CSS file. You can add this snippet to any type of markup, from tables to plain divs, anything you want to be zebra stripped.

 

Conclusion

These are the pieces of jQuery code I find myself using again and again in my projects. I hope you bookmark this page and come back whenever you need one of these snippets.

What jQuery snippets do you rely upon? Do you have better code for these scenarios? Let us know in the comments.

Featured image/thumbnail, useful image via Shutterstock.

  • mohsen_shafiee

    #2 is very good

  • willblackmore

    Number 2 isn’t reliable in quite a few browsers. There are issues with caching in the more modern ones all kinds of issue with older IE’s.

    This is a better solution:
    http://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached

  • jony

    #4 and #10 are possible just with CSS, why use JS?

    This is why “Designers” shouldn’t use JS…

    • http://nodws.com/ Nodws

      Agree.

      AND if you are illiterate to JS you shouldn’t use jquery.

    • http://www.webdesignerdepot.com/ Benjie — WebdesignerDepot

      4) and 10) are possible in CSS unless you need to support IE8.

      As most people are still being asked to support IE7, and IE8 is likely to be a requirement for some time, it’s worth noting.

    • rglazebrook

      #4 is possible with CSS, but it does help if you need to support hover states on things other than links in IE8 or earlier. However, it could be written more succinctly as:

      $(‘.btn’).hover(function() { $(this).toggleClass(‘hover’) });

      #10 is completely useless. Instead of writing CSS in JavaScript, just write CSS:

      li:odd { background: #e8e8e8; }

      Unless, of course, you’re again attempting to support an older browser that doesn’t recognize :odd. In which case, I would still argue for using a polyfill to add :odd support (like Selectivizr), or writing this JS instead:

      $(‘li:odd’).addClass(‘odd’);

      And then modifying your CSS to this:

      li:odd, li.odd { background: #e8e8e8; }

  • ergecsenturk

    This is also a good way to make sure all images and everything else are fully loaded. $( window ).load(function() { // Run code });

    • Will

      Images aren’t loaded at that point.

  • junius

    $(‘img’).load(function() {
    console.log(‘image load successful’);
    });

    Doesn’t work if images are cached, it’d be more efficient to use a 3rd party plugin like this one :
    https://github.com/desandro/imagesloaded

  • http://www.yearlyglot.com/ Randy the Yearlyglot

    Why on earth would a person construct Javascript functions to zebra-stripe a list or to add a hover effect on links? This stuff has been standard CSS for like 10 years.

    • designcouch

      Hover, or sure – but zebra striping? No way has it been standard that long bc nth-child is only now gaining universal acceptance in all browsers. Some designers have to consider support (which Jquery has) vs availability; just because a CSS element is available in the latest and greatest browser doesn’t mean we can use it in production sites.

    • Kyle Sowards

      …no it hasn’t. And using :hover on anything but an anchor breaks in older versions of IE. His example was a class. He could have very well use “foo” instead if that helps you get a better picture.

    • http://www.webdesignerdepot.com/ Benjie — WebdesignerDepot

      Only if you’re using IE9 and up.

      Personally I’d treat it as progressive enhancement and let people using IE8 go without the zebra-stripe. But it depends how essential your client deems it.

  • designcouch

    Your very last one can be done with pure CSS using nth-child, just so you know :)

    • Sara Vieira

      I know some of this can be done with CSS, and the more you do it over JS the better but there are times where you need a JS solution for some reason mainly backwards compatibility, its always good to know alternatives

      • designcouch

        4 & 10 are widely supported using CSS methods now. Backwards compatibility is moot.

      • http://www.webdesignerdepot.com/ Benjie — WebdesignerDepot

        People are still being asked for IE7 support. Occasionally I hear of someone being asked to support IE6. IE8 support is pretty much a universal requirement, and IE8 doesn’t support nth-child.

        Although as I’ve said above, I’d personally let IE8 users suffer the lack of zebra striping before I coded it in JS.

      • Joost Brommert

        With Selectivizr it is possible to use css3 pseudo-classes in IE 6-8: http://selectivizr.com/. With this little script you’re ready for the future and still supporting old browsers.

      • designcouch

        Personally, I believe if you’re still providing support for IE7, you’re doing your client a disservice. IE7 exists only in XP, and Microsoft is officially deprecating XP as of April of this year. That means that any new vulnerabilities opened up after April will stay open and unfixed. If your client asks for IE7 support, instead of smiling and doing it, you should be politely declining and informing them of the importance of upgrading to at least Windows 7. Just my two cents.

        Totally agree on your second point – if it’s a graceful degradation, there’s not really a point to doing it in JS.

      • http://www.webdesignerdepot.com/ Benjie — WebdesignerDepot

        Honestly, I’m more likely to decline and inform them of the importance of upgrading to MacOS ;)

        But seriously, it’s not the client’s machine that’s the issue. If their site stats show significant IE7 usage amongst their customers then you have to take that into account.

      • designcouch

        I’m not overly concerned with the client’s machine. My point is that if we as web designers continue to make websites work in IE7, then those still using it will have less incentive to switch. Call it a modern “social responsibility” if you will.

      • Sara Vieira

        It’s not as much as we think actually , just yesterday I was asked to resolve a bug that a a client had , he sent me a screenshot showing the bug and he was seeing the website in IE7.
        It’s not a common request but it’s something that still happens unfortunately.

  • Aurelio De Rosa

    Hi Sara. The first snippet is incorrect as documented by an issue in the jQuery API repository (https://github.com/jquery/api.jquery.com/issues/417). It’ll run the handler two times which is incorrect. The handler should be attached to document body instead.

    • http://www.webdesignerdepot.com/ Benjie — WebdesignerDepot

      Thanks for pointing that out, we’ll correct it.

      • Aurelio De Rosa

        Hi Benjie — WebdesignerDepot. Thank you for taking the time to correct it, but the correction is wrong as well. It’s not

        $(‘document.body’)

        but

        $(document.body)

        Note the missing quotes.

  • Bryan Gruhlke

    In many of these examples the use of .prop() is more appropriate than .attr(). Older versions of jQuery used attr(), but newer (I believe since around version 1.7) should use prop() instead.

  • Владимир Шевченко

    Hi, #1 $(‘body, html’) <= deprecated, try use $(document)

    • Sara Vieira

      It will be updated, thank you

  • Lindsey

    Can’t you do many of these with CSS3 now?

  • igmuska

    what’s with the backtick?

  • sp

    Love your site! I find myself coming back everyday keep it going! Thanks!

  • Bryan Garaventa

    There is something important to keep in mind regarding the accordion, if implemented in such a manner, it will be inaccessible to blind screen reader users. There are several ways to do so accessibly, one such is documented at
    http://whatsock.com/tsg

  • http://time2hack.com/ Pankaj Patel

    I like the #6 and #9.

  • wws

    Amateur advises :(

  • Bastien DONJON

    Some snippet are not updated with the best practices.

    #1 – Back to top button

    Correction with ‘on’ function :

    // Back To Top
    $(‘a.top’).on(‘click’, function(){
    $(document.body).animate({scrollTop : 0},800);
    return false;
    });

    #5 – Disabling input fields

    Correction with ‘prop’ function :

    $(‘input[type=”submit”]’).prop(“disabled”, true);

    • http://dandigangi.me/ Dan DiGangi

      Please read the jQuery documentation. The ‘click’ method is a shortcut alias to the ‘on’ method.

  • Will

    you really shouldn’t use #2 . even jquery doesn’t recommend it

    • http://dandigangi.me/ Dan DiGangi

      Do you have a link to that?

      • Will

        Let me Google that for you … of right, the official documentation!! /s http://api.jquery.com/load-event/

      • http://dandigangi.me/ Dan DiGangi

        I didn’t assume it’d be on the .load page. Chill.

  • http://dandigangi.me/ Dan DiGangi

    Love the image fix!

    – Dan DiGangi

  • Whizbrains

    Very useful one. Images are very important for the website presence in user’s mind and it should load properly every time. Thanks for sharing this scripts.

    http://www.whizbrains.com

  • Paul Mccain

    Great Information
    It will definitely help me out to make my site even better.
    Thanks
    From
    http://senseitejsinghbahadur.in/

  • Malyw

    “.hover” is deprecated in jQuery from version 1.8- http://bugs.jquery.com/ticket/11731
    Use instead:
    var hoverClass = ‘hover’,
    $btn = $(‘.btn’)
    .on(‘mouseenter’, function(){
    $btn.addClass(hoverClass);
    })
    .on(‘mouseleave’, function(){
    $btn.removeClass(hoverClass);
    });

  • designcouch

    Totally understand that you can’t always stand on principle, but I’m in the position where I can, so I choose to. My clients trust my input because I’ve proven myself to be right whenever I put my foot down – and luckily, none of them have any products dependent on IE7 or 8.

  • André Alves

    People shouldn’t give solutions for browsers (er… IE<9) that don't support CSS3. If the user is dumb enough to use that browser, so (s)he must see it like crap.
    That's evolution.

  • http://dandigangi.me/ Dan DiGangi

    Agreed. Have to be careful with those.

  • Hojat Shahmohammadi

    All are Very Nice

  • manoj

    thanks! thats cool Sara!

  • reper

    Sorting numerical values:
    var sorted = array.sort(function(x, y) { return x – y; });

    Not really jQuery, but still very useful.

  • Scott Pringle

    Surely a lot of these would be better done with just CSS? Number 4 especially, I’d argue even number 10 if you’ve dropped IE8 support. Some I use a lot, but those 2 seem redundant…

  • http://julienjolly.com/ Julien Jolly

    Interesting article. Be careful with the quotes and the apostrophes (‘ -> ‘, “ -> ” )