15 Selected jQuery Snippets

Share this article

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

	 a.toggleClass('blueButton');

2. Page section AutoScroll

jQuery.fn.autoscroll = function(selector) {
  $('html,body').animate(
    {scrollTop: $(selector).offset().top},
    500
  );
}

//Then to scroll to the class/area you wish to get to like this:
$('.area_name').autoscroll();

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

jQuery.fn.center = function () {
	this.css('position','absolute');
	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() {
            $(this).html(
                $(this).html().replace(regexp,”")
            );
        });
        return $(this);
    }
})(jQuery);

	//usage:
	$('p').stripHtml();

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

jQuery('a.popup').live('click', function(){
	newwindow=window.open($(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(){
	newwindow=window.open($(this).href);
	jQuery(this).target = "_blank";
	return false;
});

8. Add HTML to an element

$('#lal').append('sometext');

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 < = 6 )),
	Detect FireFox 2 and above (if ($.browser.mozilla && $.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:
$('.someClasses:test').doSomething();

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").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]);
        }
    });
});

12. Parse XML with jQuery

function parseXml(xml) {
	//find every Tutorial and print the author
	$(xml).find("Tutorial").each(function()
	{
	$("#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;
    if(!cookiesEnabled)
	{
        //cookies have not been enabled
    }
$.fn.replaceUrl = function() {
        var regexp = /((ftp|http|https)://(w+:{0,1}w*@)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%@!-/]))?)/gi;
        this.each(function() {
            $(this).html(
                $(this).html().replace(regexp,'<a href="$1">$1</a>)
            );
        });
        return $(this);
    }

	//usage

	$('p').replaceUrl();
Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week