This is a collection of some 10 cheeky jQuery snippets. I’m sure you will find them useful, enjoy!

Quick Fire jQuery Snippets!

1. Make all images turn greyscale

This quick function and snippet turns all images on your page from coloured into grey using HTML5 canvas and jQuery.


// Grayscale image using HTML5 canvas method
function grayscale(src){
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var imgObj = new Image();
    imgObj.src = src;
    canvas.width = imgObj.width;
    canvas.height = imgObj.height; 
    ctx.drawImage(imgObj, 0, 0); 
    var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
    for(var y = 0; y < imgPixels.height; y++){
        for(var x = 0; x < imgPixels.width; x++){
            var i = (y * 4) * imgPixels.width + x * 4;
            var avg = ([i] +[i + 1] +[i + 2]) / 3;
  [i] = avg; 
  [i + 1] = avg; 
  [i + 2] = avg;
    ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
    return canvas.toDataURL();

//Make all images on page Greyscale!
    var el = $(this);
").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function() { var el = $(this); el.parent().css({"width":this.width,"height":this.height}); el.dequeue(); }); this.src = grayscale(this.src); });

2. Create element using object literal syntax

This is not the usual way to do things when setting properties on DOM elements so very cheeky!

", { id: "test", name: "test", class: "test-class", css: { width: "100px", height: "100px", backgroundColor: "#fff" } });

3. Tell IE6 User upgrade thier browser

Nicely Tell IE6 Noobs to upgrade thier browser by simply adding this code inside your opening body tag. This is what they see:

Your browser is ancient! Upgrade to a different browser or install Google Chrome Frame to experience this site.

4. Shorten Links with using jQuery

Thanks to James Cridland for this cheeky little URL shortener code snippet. You’ll need a api key to use this one, but don’t worry it’s a completely free service.

function get_short_link($url) 
  $api_call = file_get_contents("".$url."&login=".$bitly_login."&apiKey=".$bitly_apikey);
  if ($bitlyinfo['errorCode']==0) 
      return $bitlyinfo['results'][urldecode($url)]['shortUrl'];
      return false;

//Usage: get_short_link("");

5. Quick Format Currency

This cheeky little snippet solves a complex show currency problem in a simple way which is also works cross browser!

function formatCurrency(num) {
    num = isNaN(num) || num === '' || num === null ? 0.00 : num;
    return parseFloat(num).toFixed(2);

6. Quick Caching Images

This snippet caches an image in the browser and then removes it so when it’s loaded into the DOM it doesn’t show those ugly missing image little red crosses. How cheeky!


//cache the user img
$('img').hide().appendTo('body').one('load', function() {
   console.log('Image: '+$(this).attr('src')+' is cached...');

7. Z-Index Fix for Video Objects

If your having problems with z-index on video elements you can add a wmode parameter. Use this cheeky little snippet to fix that z-index problem! You can use “transparent” instead of “opaque” but the latter is less render intensive.


//specific object
$('#videocontainerid object').prepend('');

//all objects

8. Get last class of an element

This snippet gets the last class of a DOM element so if you had a DOM element with class=”class1, class2, class3″ it would return “class3″. Cool?

var lastElClass = $(element).attr("class").split("").slice(-1);

9. Remove Browser Cookies using JavaScript

This collection of functions/snippets help you delete all browser cookies using JavaScript! Yes using JavaScript, how cheeky!


//Browser cookies are stored in JavaScript here:

//function to delete cookie (change expiry date)
function delCookie(name)
  document.cookie = name+'=; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'

//function to get the keys for each cookie name
function getCookieKeys()
    // Separate key / value pairs
    var cookies = document.cookie.split(";"),
        index, keys = [];
    for(i = 0; i < cookies.length; i++) {
        cookieEntry = cookies[i].split("=");
        // first part of the split string holds the key ...
    return keys;
var cookieKeys = getCookieKeys();

//delete all cookies
for(i = 0; i < cookieKeys.length; i++)

//check they are gone!

10. Suggest one! cheeky?

Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

  • Echt Einfach TV

    awesome, very useful! thank you :)

    • jQuery4u

      Your welcome!: )

  • Pingback: 10 Cheeky Quick jQuery Snippets » PHP Script Blog()

  • piki


  • Travis Layne

    Outstanding post! I have a good one for you: C#-styled string formatting!

    // Code
    String.prototype.format = function () {
    var args = arguments;
    return this.replace(/{(d+)}/g, function (match, number) {
    return typeof args[number] != ‘undefined’ ? args[number] : match;

    // Usage
    “Hello, my name is {0}!”.format(“Travis”);
    // Output: Hello, my name is Travis!

    “Here’s a {0} with {1} arguments! Yes, I said {1}!”.format(“sentence”, 2);
    // Output: Here’s a sentence with 2 arguments! Yes, I said 2!

  • Umair Ulhaque

    Thanks Sam for such a useful collection of snippets, here I would like to add my cheeky I guess some UX folks might be familiar with this approach as it adds a smooth black fadeout when the website is fully loaded.

    So guys all you need to do is making an empty with a class of “fade”

    just after the opening body tag (before all the site containers/wrappers)

    After that, go to your css stylesheet and style the fade class as:

    .fade {

    position: absolute;

    background-color: #000;

    z-index: 1000;

    width: 100%;

    height: 100%;


    And here comes the final cheeky step,

    After referencing the jQuery add the following snippet just before the closing body tag:




    voila! :)

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.