« About me

riches designer, developer, gamer

November 13, 2012 jQuery, Rant, Snippets

64 Useful jQuery Snippets

This list is a useful combination of frequently used functions, useful to know snippets and ways to use jQuery (with some JavaScript thrown in) effectively.

The syntax highlighter can be a bit temperamental at times, so if the code doesn’t work, check there are no extra html entities – and of course leave comments below.

1. An AJAX Call On Click
This snippet will bind a click to the element with id “button”. The click function then fires an AJAX call. The request is sent to the URL string “/ajax/test.html”, the response is placed in the object called “data”, since the response type hasn’t been specified it will default to text. The resulting data is then added inside the element “result” using the html function to ensure it is added and rendered as HTML, using the text option “text(data)” would add the result as plain text.

$("#button").on("click", function(e){
    $.ajax({
        url: '/ajax/test.html',
        success: function(data) {
            $('#result').html(data);
        }
    });
});

2. Prevent a form submitting on errors
This snippet will bind the submit of the form with the id of “myform”, if you only have one form on the page you could simply use just “form”.

The submit function will first create a local variable called errors. Next for each matching input, textarea and select box it finds, it will check if the length of the value is equal to zero. If it is, it will add the class of “error” and increment the error variable.

Finally it will check if the error variable is still set to zero, if it is it returns true allowing the form to submit, if not it will prevent the default action of the form and return false, preventing the form from submitting providing JavaScript is enabled of course ;-)

You would remove the error class based on validation for the input separately.

$("#myform").submit(function(e) {
    e.preventDefault();
    var errors = 0;
    $("#myform input, #myform textarea, #myform select").each(function(index, element) {
        if($(this).val().length == 0) {
            $(this).addClass("error");
            errors++;
        }
    });
    if(errors == 0) {
        return true;
        $("#myform").submit();
    } else {
        return false;
    }
});

3. Toggle a set of Checkboxes on or off
For each checkbox with the class of “checkbox”, (you could also use “input[type=check]” to match it), it will set the checkbox to the opposite to what it is currently set to by using the exclamation modifier.

$(".checkbox").each(function(index, element) {
    $(this).attr('checked', !$(this).attr('checked'));
});

4. Perform an action when a specific keyboard key is hit
This one is quite a simply one. The bind is place on the “keydown” event of the element, we capture the whole event into an object in this example called “e” so we can interogate it.

Inside the function, we check the “keycode” of the event, in this case we check for the key code of the down arrow and perform a specific action. You can change the key code to whatever you want (just Google the key code for the key you are after) or add more. Be aware that some operating systems may pass different codes for special keys.

$('input').keydown(function(e){
    if (e.keyCode == 40) {
        console.log("you sunk my battleship");
    }
});

5. Move multiple background images with the mouse to create depth
This snippet binds to the mouse moving and captures the coordinates. In then makes these values into a percentage before multiplying them by minus 1 to ensure the backgrounds flow in the correct direction for prospective (you don’t have to do this if you want to inverse the effect.)

Separate values are created using different divisions to create different speeds of movement. The values are then applied to separate elements changing the position of their background images, this creates the effect.

$(document).mousemove(function(e) {
    var x = ((e.pageX/$(window).width())*100)*-1;
    var y = ((e.pageY/$(window).height())*100)*-1;
    var pos = (x/80*-1)+"% "+(y/80*-1)+"%";
    var pos2 = (x/3+60)+"% "+(y/3+60)+"%";
    var pos3 = (x/5+30)+"% "+(y/5+30)+"%";
    var pos4 = (x/2+60)+"% "+(y/2+60)+"%";
    $("#background").css("background-position",pos);
    $("#midground").css("background-position",pos2);
    $("#foreground").css("background-position",pos3);
    $("#flare").css("background-position",pos4);
});

6. Go old skool and make text alternate colours
First setup your on and off styles.

.off {color:blue;}
.on {color:red;}

Then, just toggle the classes at a set interval. The element must start with one of the classes for this to work. You can change the timeout depending on how trippy you want the effect to pie and how quick you want your browser to crash.

setInterval(function() {
    $(".on").toggleClass('on off');
}, 1000);

7. Stop the screen scrolling when a popup is open
This one is more CSS than jQuery, but here you go. Create a class that hides all overflow. When your popup appears ensure it is fixed or absolutely positioned and fits within the window (best to use percentages).

.fix {
overflow:hidden;
}

Then just call this snippet any way you like to toggle this class on the body to stop the window being scrolled and call it again to allow it to be scrolled.

$(body).toggleClass("fix");

8. Fade between images
First up, you’ll need some HTML for the images

<div id="wallpaper">
<img src="/one.jpg" id="w1" rel="1" />
<img src="/two.jpg" id="w2" rel="2" />
<img src="/three.jpg" id="w3" rel="3" />
</div>
#wallpaper img {
position:fixed;
top:0px;
left:0px;
}

This function will first count how many images there are to derive a total. Text it will determine the current image which is visible and pinch its position from the rel attribute (you could pragmatically do this however this way means they don’t have to be in the order they are written).

Next the function determines the next image to show by adding one and checks there is a next image to show, if not resets to 1. Finally it fades between the current image and the next image. For this to work the images will need to be position on top of each other as shown in the CSS.

function animateWallpaper() {
    var total = $("#wallpaper img").length;
    var liveWallpaper = $("#wallpaper img:visible").attr("rel");
    var next = parseInt(liveWallpaper)+1;
    if (next > total) {
        var next = next-total;
    }
    $("#w"+liveWallpaper+", #w"+next).fadeToggle(5000);
}
var timer = setInterval("animateWallpaper()", 15000);

9. Action when user stops moving over a target (hints)
Sometimes you want to be able to fire an action or show a hint if a user stops moving over a target for a set period of time, here’s the snippet.

This function will monitor the movement of the mouse over the element with the id box. It uses a timer for this, so when the user stops moving their mouse over the element upon which they have been moving it, the function “thread” is fired. This function clears all existing timeouts with the same name and counts for two seconds before firing the event; in this case it makes the box black.

$('#box')[0].onmousemove = (function() {
    var onmousestop = function() {
    $('#box').css('background-color', 'red');
}, thread;
    return function() {
        $('#box').css('background-color', 'black');
        clearTimeout(thread);
        thread = setTimeout(onmousestop, 2000);
    };
})();

10. Make links look active based on the current page URL
Sometime you may not want to add in active classes by hand, but instead have these dynamically set based on the pages URL. This could also be used to deactivate links that lead back to the page you are on.

var url = document.URL;
$('a[href="'+url+'"]').addClass('active');

11. Make links offsite automatically open in a new window
This snippet will add in a target of “_blank” if your site isn’t found in the href. Of course this only works if you use full links, although could be modified to do both full and relative.

var site = location.protocol + '//' + location.host;
$('a').not(':contains(site)').click(function(){
    this.target = "_blank";
});

12. Test if an image is loadable and load it
Checking if an image can be loaded is quite simple using jQuery, just attempt a load via the standard methods. This snippet will check if the image can be loaded then add it to a specific element. In this case a new tag has been created, however this can be changed to existing images.

var imgsrc = 'http://placekitten.com/200/300';
$('<img />').load(function () {
    console.log("image loaded!");
}).error(function () {
    console.log("couldn't load image");
}).attr('src', imgsrc);

13. Alphabetically order a list of values
It far nicer to have a list ordered alphabetically.

<ul>
	<li>cloud</li>
	<li>sun</li>
	<li>rain</li>
</ul>
<!-- becomes -->
<ul>
	<li>cloud</li>
	<li>rain</li>
        <li>sun</li>
</ul>

The jQuery to sort the list. Currently it just looks at a single ul, but changing the “ul” selector in both places will allow you to target the list you require.

var items = $('ul li').get();
items.sort(function(a,b){
    var keyA = $(a).text();
    var keyB = $(b).text();
    if (keyA < keyB) return -1;
    if (keyA > keyB) return 1;
    return 0;
});
var ul = $('ul');
$.each(items, function(i, li){
    ul.append(li);
});

14. Write a custom selector to save time
Creating your own selector is very easy, and useful to do if there is something you are regularly looking for. This snippet will create a selector that filters what you select to only those that contain integers over ten, the example colours it red.

$.extend($.expr[':'], {
    //name of your special selector
    gtTen : function (a){
        //Matching element
        return parseInt($(a).html()) > 10;
    }
});

$(document).ready(function() {
    $('td:gtTen').css('background-color', '#ff0000');
});

15. Quick way to check if an element exists
Doesn’t get quicker than this.

if ($("#elementid").length) {
    // exists
}

16. Open the print dialogue
This will work for the majority of people including those without printers.

$('.print').click(function(e){
    window.print();
    preventDefault(e);
    return false;
});

17. Animate an object from left to right
Animation in jQuery is a powerful feature, as a primer this is a short snippet on how easy it is to move an object from the left to the right of the screen. This snippet will animate a sprite one hundred percent from the left. If this object is position relatively it will be 100% of what ever its held within, if absolutely 100% of the screen.

$("#sprite").animate({
    left: "+=100%"
}, 2000);

18. A digital clock
This snippet creates a 12 hour time based on the client machines local time. It will then add this string to the element with the id of “clock”.

function clock() {
    var currentTime = new Date;
    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();
    currentMinutes = (currentMinutes &amp;&amp; lt; 10 ? "0" : "") + currentMinutes;
    currentSeconds = (currentSeconds &amp;&amp; lt; 10 ? "0" : "") + currentSeconds;
    var timeOfDay = currentHours &amp;&amp; lt;
    12 ? "AM" : "PM";
    currentHours = currentHours &amp;&amp; gt; 12 ? currentHours - 12 : currentHours;
currentHours = currentHours == 0 ? 12 : currentHours;
    var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
$("#clock").text(currentTimeString);
}

myCounter = setInterval(function () {
    clock();
}, 1000);

19. Slide content in and out
Sometimes is nice to be able to slide additional content in and out if a user clicks a more info button, slide toggle is perfect for this.

In this snippet given that you bind an event to the read more button, slide toggle will allow you to slide in and out the extended content based on the faux id placed in the href value. Slide toggle is useful as it will show or hide content based on its current state.

This is some content, <a href="#content1">read more</a>
<p class="hidden" id="content1">More content</p>
var target = $(this).attr('href');
$(target).slideToggle("slow");

20. Clone an element
In this snippet, clicking an image within an element with the id of “clonebox”, the image will be cloned and added to the end after all other images. Cloning can be useful for such things as form elements, where users can add additional information.

$("#clonebox img").on("click", function(e) {
    $("#clonebox img:first").clone().appendTo("#clonebox");
});

21. Loop through an array
In this snippet, an array is created of cat names, then using jQuery’s each function, the names are appended to the element with the id of “litterbox” preceded with the number of its position in the array (plus one, as for users having a position of zero would be confusing). A comma is appended if there are more array elements to add and a fullstop if not.

var cats = ["Mr Moggles", "Mindy", "Patch", "Socks", "The Destroyer", "Lily", "Alfie", "Bob"];
$.each(cats, function (index, value) {
    $("#litterbox").append(index + 1 + ". " + value);
    if (!(index == len - 1)) {
        $("#litterbox").append(", ");
    } else {
        $("#litterbox").append(".");
    }
});

22. Automatically link Twitter mentions
Although barely jQuery this little snippet will match whole words that start with an @ sign and convert them to links to twitter using the username in question. Using the replace feature of JavaScript the Regular Expression used could be changed to match all sorts of things.

var text = $("#content").html();
text.replace(/\B@([\w-]+)/gm, '<a href="http://twitter.com/$1" target="_blank">@$1</a>');

23. Bad at CSS? Use jQuery to make all column heights match
This simple snippet will loop through all of the elements with the class of “col”. It will set the “max” variable to the highest height it finds. One the each loop has finished it then sets all of the columns to this height.

var max = 0;
$(".col").each(function(){
    if ($(this).height() > max) {
        max = $(this).height();
    }
});
$(".col").height(max);

24. Get named access to all of the URL parameters
This snippet again doesn’t use a great deal of jQuery, but does give you quick access to variables in the URL. In this example the snippet logs the contents of the “id” value in the URL.

$.params = function(name){
    var results = new RegExp('[\\?&amp;]' + name + '=([^&amp;#]*)').exec(window.location.href);
    if (!results) { return 0; }
        return results[1] || 0;
    }
console.log($.params ('id'));

25. Disable the enter key
Similar to binding specific keys, you can also prevent certain keys from performing their normal action. In this case you can prevent the enter key (key code 13) from doing anything within a form. Of course “form” can be switches to anything you like, just for laughs try assigning it to “body”.

$("form").keypress(function(e) {
    if (e.which == 13) {
        preventDefault(e);
        return false;
    }
});

26. Validate someones age
Often you will want to age gate certain content. You would need to also perform this check server side, but in a user friendly manner you can also check their age while they complete a form. This snippet will fire when the element with the id of “checkage” is clicked, and will look for values in elements with the id’s of “day”, “month” and “year”. In this example if the age is found to be less that 18 and alert is triggered.

$("#checkage").on("click", function(){
    var day = $("#day").val();
    var month = $("#month").val();
    var year = $("#year").val();
    var age = 18;
    var mydate = new Date();
    mydate.setFullYear(year, month-1, day);
    var today = new Date();
    today.setFullYear(today.getFullYear() - age);
    if ((today - mydate) < 0){
        alert("Sorry, only persons over the age of " + age + " may enter this site");
    } else {
        alert("Welcome in!");
    }
});

27. Highlight text nodes on a page that contain a specific string
Sometimes it would be useful to the user to highlight full text nodes that contain a specific term. In this example the function is run for the term “jquery” and the results stored in a variable called matches, then each of these matches is given a yellow highlight.

$.fn.egrep = function(pat) {
    var out = [];
    var textNodes = function(n) {
    if (n.nodeType == Node.TEXT_NODE) {
        var t = typeof pat == 'string' ?
        n.nodeValue.indexOf(pat) != -1 :
        pat.test(n.nodeValue);
        if (t) {
            out.push(n.parentNode);
        }
    } else {
        $.each(n.childNodes, function(a, b) {
            textNodes(b);
        });
    }
};
this.each(function() {
    textNodes(this);
});
    return out;
};

var matches = $('body').egrep(/jquery/i);
for (var i = 0; i < matches .length; ++i) {
    void($(matches [i]).css('background', 'yellow'));
}

28. Detect browsers
Although no browser detection can be fail-safe, using jQuery makes it super easy to find the browser and its version, then you can do as you please with the information.

if( $.browser.safari ) {
    console.log("any version of safari");
}

if ($.browser.msie && $.browser.version > 6 ) {
console.log("IE7 and above");
}

if ($.browser.msie && $.browser.version < = 6 ) {
console.log("What the hell, IE6 or below");
}

if ($.browser.mozilla &amp;&amp; $.browser.version >= "3.5" ) {
console.log("Firefox 3.5 or higher");
}

29. Parse XML
Parsing XML in jQuery is so easy you’ll wonder how you lived without it. In this example “xml” is a variable that contains all of the XML data. The powerful each function then finds each instance of book and logs its attribute named “author”.

$(xml).find("book").each(function() {
    console.log($(this).attr("author"));
});

30. Reload all Iframes
Using the jQuery each function, this snippet will refresh each iframe on the page.

$('iframe').each(function() {
    this.contentWindow.location.reload(true);
});

31. Delay Fading
The delay function can be used to create delays between fading, in this example the element will start of hidden while the delay is running for 3 seconds, fade in over 1 second, again delay while visible for 5 seconds before fading out over 1 second. This sort of action could be useful for informative messages. Of course a mix of effects can be used with delay.

$("#element").delay(3000).fadeIn(1000).delay(5000).fadeOut(1000);

32. Dynamically Change the stylesheet
Assuming your style sheet is the second one one on the page (after your reset style sheet of course) targeting the screen as its media type, this small snippet will change it.

$('link[media='screen']:nth-child(1)').attr('href', 'ie.css');

33. Animate Anchor Movement
Sure anchors are cool, they jump straight to the relevant matching id of anchor name on the page, but how about animating them?

This code will target all anchors, that is, links that start with a hash, and then animates to that point on the page over 1 second. If you fancy the anchor to be more middle of the page you could always divide the height of the window by two and add this to the top offset…

$('a[href^="#"]').on('click', function () {
    var anchor = $(this).attr('href');
    $('html,body').animate({scrollTop: $(anchor).offset().top}, 1000);
});

34. Disable the right click context menu
Sometimes if designing a web app, the context menu can really break the flow, other times you may want to replace the context menu. Although this won’t work in every browser, this snippet will try to prevent the context menu from showing.

$(document).bind('contextmenu', function(e) {
    e.preventDefault();
    return false;
});

35. Remove the Default Text from Input Boxes
Often you will want to blank the default text currently in the box so the user can type their input, and if they leave the input with a blank value put it back in. This snippet does that for every element with the class of “swap” and which has a value to begin with.

swap_val = [];
$(".swap").each(function(i){
    swap_val[i] = $(this).val();
    $(this).focusin(function(){
        if ($(this).val() == swap_val[i]) {
            $(this).val("");
        }
    }).focusout(function(){
        if ($.trim($(this).val()) == "") {
            $(this).val(swap_val[i]);
        }
    });
});

36. Find the Closest
Sometimes you will simply want to find the closest item to a given selector, maybe to manipulate it, highlight it or even remove it. In this snippet when a strong element is clicked (that’s bold to you old skoolers) it will add the class “highlight” to the closest strong element it finds.

$("strong").click(function(){
    $(this).closest("strong").addClass(".highlight");
});

37. Get Siblings
Sometimes you just want to select all of the siblings of a specific element, well there is already a function for that.

$("#mydiv").siblings().css('background-color', 'red');

38. Remove an Option from a Select List
If you need to remove a specific option from a select list this is easy achieved in jQuery. Its worth noting that its better to remove than hide them, as not all browsers will actually hide an option within a select list.

In this snippet the option with a value of “cat” will be removed.

$("#mylist option[value='cat']").remove();

39. Zebra Tables Rows
Often to make tables more readable you will want to alternate the row colours. Using jQuery selectors its easy to target odd or even rows. In this snippet odd rows are added a class of “odd”, the “odd” class can be any style you want, a subtle green “DAD” is always nice.

$("tr:odd").addClass("odd");

40. Count Direct Children
Often its advantageous to now how many direct children there are of a given element; often because of logic or calculation. This snippet shows how quickly you can accomplish this, the variable “rugrats” will contain the integer of direct children.

var rugrats = $("#foo > div").length

41. Check if Cookies Are Enabled
Did you know JavaScript can read and write cookies? No? Shame on you. This snippet checks if cookies are enabled by created one and then checking to see if it was created, of course this all goes to pot if JavaScript is disabled.

A date is first created, then 60 seconds of lead time added. A cookie is created with the formatted date string as the expire date. Next a check is performed to see if “cookietest” exists, if it wasn’t created the condition matches and you can perform you logic.

$(document).ready(function() {
    var dt = new Date();
    dt.setSeconds(dt.getSeconds() + 60);
    document.cookie = "cookietest=1; expires=" + dt.toGMTString();
    var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
    if(!cookiesEnabled){
        //cookies are not enabled
    }
});

42. Move Options Between Two Select Lists
Often you will want lists to dynamically change given certain criteria. In the snippet below buttons with the ids of both “add” and “remove” will add the selected option from list one to list 2 and the remove option will remove the selected option from list 2 and add it to list 1.

$(document).ready(function() {
    $('#add').click(function() {
        !$('#select1 option:selected').appendTo('#select2');
    });
    $('#remove').click(function() {
        !$('#select2 option:selected').appendTo('#select1');
    });
});

43. Get the Current URL
Often valuable information, getting the current URL is a JavaScript affair but still very useful.

$(document).ready(function() {
    var fullurl = window.location.pathname;
});

44. Get a Users IP Address
There are lots of APIs out there that can determine a users IP address based on the material passed in simply requested a page. This function uses the jSON IP app found at appspot to provide an IP address of your user. Remember IP addresses are not very accurate and a better suited for determining a broad location such as state or if you speak English – county.

This snippet posts a call to the address expecting JSON as the response and then alerts the IP address value from the response.

$.getJSON("http://jsonip.appspot.com?callback=?",function(data){
    alert( "Your ip: " + data.ip);
});

45. Make a Number Pretty and Separate it with Commas
Although this should be done server side, if you are really stuck you can do this in JavaScript. The snippet below will the delimiter as set in the “delimiter value”, and add it in every third place. Changing some like 103459 to 103,459.

var delimiter = ',';
$('#result').html()
.toString()
.replace(new RegExp("(^\\d{"+($this.html().toString().length%3||-1)+"})(?=\\d{3})"),"$1" + delimiter).replace(/(\d{3})(?=\d)/g,"$1" + delimiter);

46. Count Lines in a Textarea
Useful for formatting or checking if a user is angry, counting the number of new lines in a textarea can be useful information. The following snippet splits the value of the textarea text into a array by both new lines and carriage returns and then sets the variable “total” to the number if items in this array.

var text = $("#textareaId").val();
var lines = text.split(/\r|\r\n|\n/);
var total = lines.length;

47. Validate a Credit Card Number
Credit card numbers must conform to a specific algorithm known as the Luhn-10. This function will validate against the number passed to it “ccnum” reversing this process until it errors. The function will return true or false depending on whether the number is valid or not. Of course this function only checks the number, all other checks will have to be handled separately, and of course this should be done for user indication not validation.

function isCreditCard(ccnum){
    if (ccnum.length > 19)
        return (false);
        sum = 0; mul = 1; l = ccnum.length;
        for (i = 0; i < l; i++){
            digit = ccnum.substring(l-i-1,l-i);
            tproduct = parseInt(digit ,10)*mul;
            if (tproduct >= 10) {
                sum += (tproduct % 10) + 1;
            } else {
                sum += tproduct;
            }
            if (mul == 1) {
                mul++;
            } else {
                mul–;
            }
    }
    if ((sum % 10) == 0) {
        return (true);
    } else {
        return (false);
    }
}

48. Add wmode Cross-Browser to Embed Code
Although embedding Flash is rather superseded now with HTML5 video, having Flash embedded without a wmode value set can cause it to float above all objects. This cross-browser script will add the wmode attribute and tag to all the embed tags it finds. It will also wrap embed code that doesn’t have an outer tag (such as object) inside a div to try and prevent the tag from breaking other elements and the ability to style is easier.

("embed").attr("wmode", "opaque");
var embedTag;
$("embed").each(function(i) {
    embedTag = $(this).attr("outerHTML");
    if ((embedTag != null) &amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp; (embedTag.length > 0)) {
        embedTag = embedTag.replace(/embed /gi, "embed wmode="opaque" ");
        $(this).attr("outerHTML", embedTag);
    } else {
        $(this).wrap("<div></div>");
    }
});

49. Check if Action was Native
Sometime it can be useful to tell whether a specific event was native event (such as a user clicking an anchor) or triggered (such as a bind to an anchor that override the default action).

In this snippet whenever an anchor is clicked, it will check to see if additional client variables were passed, if they were is sets the “jstrigger” values to false and if not sets it to true. Its up to you how you use this information, an example could be to react differently depending on if a click was performed by the user it triggered from a function.

$('a').click(function(event, triggered) {
    if (triggered) {
        var jstrigger = false;
    } else {
        var jstrigger = true;
    }
});

50. Display the First Feedburner Entry
jQuery is very good at searching strings. This example performs an AJAX “get” of a specified Feedburner feed, in this case the PS3 Attitude feed. Next it will find the relevant information from the first instance of tags matching the string “pubDate”, link tag, and description tag and set the corresponding elements with the ids “date”, “title” and “description” to be populated.

A quick way to display fresh information from a syndication source.

$(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "http://feeds.feedburner.com/ps3attitude",
        success: function(data){
            $("#date").text($(data).find("item:first>pubDate:first").text());
            $("#title").html("<a href='"+$(data).find("item:first>link:first").text()+"'>"+$(data).find("item:first>title:first").text()+"</a>");
            $("#description").html($(data).find("item:first>description:first").text());
        }
    });
});

51. Exclude the Current Element
Sometimes you want to select everything apart from the current element that has been clicked, changes or any other event you have bound. The snippet below first puts all anchors in a jQuery variable, then the click function explicitly states not to target “this” referring to the relevant source of the event – useful for example if you want to highlight all other links.

var $allAnchors = $("a");
$allAnchors.click(function() {
    $allAnchors.not(this).css("color", "red");
});

52. Provide Fallback if CDN fails
Its great to be able to use a CDN to serve up your jQuery; it ensures speed and reliability, but often it would be nice to have a fallback, you know, just in-case.

Good’ol JavaScript to the rescue! The below snippet includes the jQuery via CDN and then uses JavaScript to check if jQuery exists, if it doesn’t it includes a local copy of jQuery instead.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='/javasript/jquery.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>

53. Konami Code
If you don’t know what the Konami code is, shame on you and move to 54.

var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
$(document).keydown(function(e) {
kkeys.push( e.keyCode );
if (kkeys.toString().indexOf(konami) >= 0 ) {
$(document).unbind('keydown',arguments.callee);
// do something awesome
$("body").addClass("konami");
}
});

54. Password Strength
As a more complicated snippet, the code below binds to the element with the id of “pass”. It will perform a number of regular expressions and length checks. Based on the length and complexity (uppercase, lowercase and non alphanumeric characters) it will populate the element with ID “passstrength” a word describing the passwords strength, this being “strong”, “medium” or “weak”. If the password has less than 6 characters it will add the message “more characters”.

$('#pass').keyup(function(e) {
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
    $('#passstrength').html('More Characters');
} else if (strongRegex.test($(this).val())) {
    $('#passstrength').className = 'ok';
    $('#passstrength').html('Strong!');
} else if (mediumRegex.test($(this).val())) {
    $('#passstrength').className = 'alert';
    $('#passstrength').html('Medium!');
} else {
    $('#passstrength').className = 'error';
    $('#passstrength').html('Weak!');
}
return true;
});

55. Persistent Headers on Tables
Often when scrolling you would like for the table header to say static while the user is scrolling down the table or even pieces of content to remain static. The below function will target elements that have the class “persist-area” and ensure the element inside with class “floatingHeader” remains static at the top of the area until the user has scrolled pass.

It achieves this by cloning the header after the user has scrolled passed it and adds the class of “floatingHeader”. This class fixes to the top of the section using “position:fixed” and remains there until the table has been scrolled completely through at which point its hidden. All of this is achieving by performing caluclations on the offset of the sections, to determine how far down the section is from the top of the page, how tall it is and when the height and offset of the section is scrolled pass hides the header.

.floatingHeader {
position: fixed;
top: 0;
visibility: hidden;
}
function UpdateTableHeaders() {
$(".persist-area").each(function() {
var el = $(this),
offset = el.offset(),
scrollTop = $(window).scrollTop(),
floatingHeader = $(".floatingHeader", this)

if ((scrollTop > offset.top) &amp;amp;amp;amp;&amp;amp;amp;amp; (scrollTop < offset.top + el.height())) {
floatingHeader.css({
"visibility": "visible"
});
} else {
floatingHeader.css({
"visibility": "hidden"
});
};
});
}

$(function() {
var clonedHeaderRow;
$(".persist-area").each(function() {
clonedHeaderRow = $(".persist-header", this);
clonedHeaderRow
.before(clonedHeaderRow.clone())
.css("width", clonedHeaderRow.width())
.addClass("floatingHeader");
});

$(window)
.scroll(UpdateTableHeaders)
.trigger("scroll");
});

56. Make the whole item clickable
Often you will create menus in a list. If a user clicks the list instead of the anchor inside (especially if you have lots of padding) it would be nice to still execute the link (you could also use CSS to do this).

In this snippet “find” is used to located the anchor inside the element clicked and the link is opened using “window.location”.

$("ul li").click(function(){
//get the url from href attribute and launch the url
window.location=$(this).find("a").attr("href"); return false;
});

57. Makes Images Grey Scale
Want to make your pictures gray scale without having to open up PhotoShop, jQuery and some HTML5 can do that.

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 = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}

//Make all images on page Greyscale!
$('img').each(function(){
var el = $(this);
el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").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);
});

58. Shorten Links With Bit.ly
Often its useful to be able to shorten links, here’s a function that will do just that.

function get_short_link($url)
{
$bitly_login="yourloginname";
$bitly_apikey="yourapikey";
$api_call = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&amp;amp;longUrl=".$url."&amp;amp;login=".$bitly_login."&amp;amp;apiKey=".$bitly_apikey);
$bitlyinfo=json_decode(utf8_encode($api_call),true);
if ($bitlyinfo['errorCode']==0)
{
return $bitlyinfo['results'][urldecode($url)]['shortUrl'];
}
else
{
return false;
}
}

59. Refresh an image

Sometimes its useful to update an image with client-side technology to ensure its the latest version, by appending a random number to the end you can easily achieve this.  The snippet below will add a random number to the end of every single image source on the page.

$("img").attr('src', $("img").attr('src') + '?' + Math.random());

60. Remove selected text with a double click

In some circumstances you may want a user to be able to delete selected text by double clicking the selection, this can easily be made to happen.

function clearSelection()  {<br />    if(document.selection &amp;&amp; document.selection.empty) {<br />           document.selection.empty();<br />  } else if(window.getSelection) {<br />    var sel = window.getSelection();<br />          sel.removeAllRanges();<br />}<br />}<br /><br />$(element).bind('dblclick',function(event){<br />    //do something<br />    clearSelection();<br />});

61.  Easy sequential fade
Using jQuery’s each command you can sequential fade in images (well increase their fade time) with jut a simple piece of math.

The below snippet works by using the curren index of the each loop. It will times the index number (starting at one) by a thousand. So the first image will wait 1 second to fade in, the second image 2 seconds and so on…this creates a faux delayed fade effect.

$("img").each(function(i) {<br />$(this).delay(i*1000).fadeIn();<br />});

62. Cancel an AJAX request
Did you know much like timers, you can also cancel AJAX events, the below snippet will abort the request assigned to the object called “reg”,this can be used in any way you see fit – its useful to combine it with a page on unload event.

var req = $.ajax({<br />type:     "POST",<br />url:     "someurl",<br />data:     "id=1",<br />success: function(){<br />//something<br />}<br />});<br />//Cancel the Ajax Request<br />req.abort()

63. Detect iPad orientation 
Using the built in orientation change in the Safari browser for iPad, you can detect the change from landscape to portrait and vice-versa and make changes appropriately.

window.onorientationchange = detectIPadOrientation;
function detectIPadOrientation () {
    if ( orientation == 0 ) {>
alert ('Portrait Mode, Home Button bottom');
} else if ( orientation == 90 ) {
alert ('Landscape Mode, Home Button right');
} else if ( orientation == -90 ) {
alert ('Landscape Mode, Home Button left');
} else if ( orientation == 180 ) {
alert ('Portrait Mode, Home Button top');
}

64. Specifically detect Apple devices
Using the built-in navigator user agent you can detect the presence of iPhone, iPod or iPad. This isn’t 100% reliable but in nearly all cases will work fine.

jQuery(document).ready(function($){
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
// mobile code here
}});

Well that’s it from me.

1 to “64 Useful jQuery Snippets”

  1. yogasukma says...

    thanks for the awesome collection.. really saves my time.. :)

Leave a comment