By Sam Deering

15 Selected jQuery Snippets

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

Improve your JavaScript projects with these cool jQuery Snippets. Some of these are supported with jQuery version 1.4.2. These are very useful functions or methods that can assist you for better and faster work.

1. Proper ToggleClass usage

//Toggle class allows you to add or remove a class
	 //from an element depending on the presence of that
	 //class. Where some developers would use:

	 a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton');

	 //toggleClass allows you to easily do this using


2. Page section AutoScroll

jQuery.fn.autoscroll = function(selector) {
    {scrollTop: $(selector).offset().top},

//Then to scroll to the class/area you wish to get to like this:

3. Automatically Hide or Close Elements

//Here's how we used to do it in 1.3.2 using setTimeout
    setTimeout(function() {
  $('.mydiv').hide('blind', {}, 500)
}, 5000);

//And here's how you can do it with 1.4 using the delay() feature (this is a lot like sleep)
$(".mydiv").delay(5000).hide('blind', {}, 500);

4. Center element on screen = function () {
	this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 'px');
	this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');return this;}
	//Use the above function as: $(element).center();

5. Stripping HTML from Element

(function($) {
    $.fn.stripHtml = function() {
        var regexp = /])*>/gi;
        this.each(function() {
        return $(this);


6. Force links to open in a pop-up window

jQuery('a.popup').live('click', function(){$(this).attr('href'),'','height=200,width=150');
	if (window.focus) {newwindow.focus()}
	return false;

7. Force links to open in a new tab

jQuery('a.newTab').live('click', function(){$(this).href);
	jQuery(this).target = "_blank";
	return false;

8. Add HTML to an element


9. Detect Browser

Detect Safari (if( $.browser.safari)),
	Detect IE6 and over (if ($.browser.msie && $.browser.version > 6 )),
	Detect IE6 and below (if ($.browser.msie && $.browser.version = '1.8' ))

10. Define Custom Selector

$.expr[':'].mycustomselector = function(element, index, meta, stack){
    // element- is a DOM element
    // index - the current loop index in stack
    // meta - meta data about your selector
    // stack - stack of all elements to loop

    // Return true to include current element
    // Return false to explude current element

// Custom Selector usage:

11. Show or Erase a Default Value in an input Field

//This snippet will show you how to keep a default value
//in a text input field for when a user hasn't entered in
//a value to replace it

swap_val = [];
    swap_val[i] = $(this).val();
        if ($(this).val() == swap_val[i]) {
        if ($.trim($(this).val()) == "") {

12. Parse XML with jQuery

function parseXml(xml) {
	//find every Tutorial and print the author
	$("#output").append($(this).attr("author") + "");

13. Check if an image has been fully loaded

$('#theImage').attr('src', 'image.jpg').load(function() {
alert('This Image Has Been Loaded');

14. Check if Cookies are Enabled or not

var dt = new Date();
    dt.setSeconds(dt.getSeconds() + 60);
    document.cookie = "cookietest=1; expires=" + dt.toGMTString();
    var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
        //cookies have not been enabled

15. Replace any URL with clickable link

$.fn.replaceUrl = function() {
        var regexp = /((ftp|http|https)://(w+:{0,1}w*@)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%@!-/]))?)/gi;
        this.each(function() {
        return $(this);


Login or Create Account to Comment
Login Create Account
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?