Top useful Javascript & jQuery snippets

Check this amazing collection of the top most used jQuery snippets that you need to know about! These jQuery snippets will help you in your website development to build powerful and responsive web pages. These jQuery snippets will definitely help you in your daily client-side coding.

Embed the latest jQuery version in your page

Just copy/paste this code and start using the last version of jQuery in your project.

< script src="http://code.jquery.com/jquery-latest.js">
< script>
$(document).ready(function(){
// jQuery Code Here
});

You can either paste this code in your header or you can add it at the end of your body. The advantage of putting it in the end of the body is that your CSS Styles will be load first and therefore the page will be displayed faster.

Value swap (usually for search fields)

Whenever you have a search field and you want it to defaultly display a value “search…” and have that value empty out on focus.

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

This jquery will create an array for every input field that has the class swap, such as:

The value “Swap Me!” will be erased when you click in the input field, and it will come back in if you don’t enter anything.

Live Event Binding

jQuery captures an onclick event with the .click() method, but if you created a new element with ajax or with jQuery this new element will not be bound by the regular click() method. Using live function with a click property will apply itself to all new elements, and will only bind once to all.

$(".element").live("click", function(){
// do something on click
});

The code above will bind the click event to every (existing and new) element that has the class “element”.

Partial Page Refresh every N seconds

The script below will refresh the div with ID “refresh” every 5 minutes. Inside your div you should have tags, otherwise it doesn’t seem to work with pure text.

setInterval(function() {
$("#refresh").load(location.href+" #refresh>*","");
}, 300000); // seconds to wait, miliseconds

Each Element

It is common to loop through a set of elements, for example in a validation form where you want to check each input field before submitting.

$("input").each(function (i) {
//do something with each and pass i as the number of the element
});

You can cycle through elements such as li’s in a chosen unordered list, or all the input fields as the example above. Use the i to get the number of the current element, and of course the $(this) to do something to the element it’s going through.

Find an element close by with jQuery 1.4+

From jQuery 1.4 on we have the new awesome feature of the closest() method which will find the element closes to the current one. Forget the old method of searching through the parents and children to get to the element needed.

$("li").click(function(){
$(this).closest(".me").addClass("smile");
});

The code above will find the closes class “me” to the li that was clicked on and add class “smile” to it. Now you can see how beneficial this can be!

Check if an element contains a certain class or element

This method will find if a an element contains another element (id, class or whatever) and apply the style or whatever you want to it.

$("input").has(".email").addClass("email_icon");

In the above example jQuery will look through all inputs that have the class “email” and add the class “email_icon” to it.

Creating the zebra stripe effect on UL/OL or Tables

Creating a strip effect on tables or ordered/unordered lists can add to readability. Here below is the quick and easy method in jQuery.

$("tr:odd").addClass("odd"); // for tables
$("li:odd").addClass("odd"); // for lists

Automatically open an external link in New Window

Tired of having to add target=”_blank” every time you don’t want your visitors to navigate away from your page? Let jquery do the work!

$('a').each(function() {
var a = new RegExp('/' + [removed].host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});

Now every a href in your page will open in a new window if it doest not link to your own website!

Refresh the src of an image

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

Check if an image is loaded or not

 var imgsrc = 'img/image1.png';
 $('').load(function () {
 alert('image loaded');
 }).error(function () {
 alert('error loading image');
 }).attr('src', imgsrc);

And if a set (example : 10 images) of images are loaded

 var totalimages = 10;
var loadedimages = 0;
$("").load(function() {
++loadedimages;
if(loadedimages == totalimages){
//All 10 images are loaded
}
});

Remove selected text after mouse double click event

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

Validate email address:

 var email = [email protected]'
if(!(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email)))
alert('Invalid Email');

Order a element using jQuery

Quick way to sort a list with jQuery.

  • Mercedes-Benz
  • BMW
  • Audi
  • Volkswagen
 var items = $('.to_order 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 = $('.to_order');
$.each(items, function(i, li){
ul.append(li);
});

Passing parameters to a function called with setTimeout

 timeout = setTimeout(function(){myFunction(param)},time);

In the myFunction we have a parameter called “param”.

Disable right mouse click

 $(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});

Fade out an image, and fade in another one (replacing the previous one)

 $('imageelement').fadeOut(function() {
$(this).load(function() {
$(this).fadeIn();
}).attr('src', AnotherSource);
});

Write your own selectors

 //extend the jQuery functionality
$.extend($.expr[':'], {
//name of your special selector
moreThanAThousand : function (a){
//Matching element
return parseInt($(a).html()) > 1000;
}
});
$(document).ready(function() {
$('td:moreThanAThousand').css('background-color', '#ff0000');
});

Run a function 5 times with intervals of 20 seconds

 var count = 0;
function myFunction() {
count++;
if(count > 5) clearInterval(timeout);
//do something
}
var timeout = setInterval(myFunction, 20000);

Check if an element exists

 if ($("#elementid").length) {
//it does!
}

Cancel an ajax request

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

Smooth scrolling to an anchor

jQuery lets developers easily create stunning visual effects. A simple, but nice effect is smooth sliding to an anchor. The following snippet will create a smooth sliding effect when a link with the topLink class is clicked.

 
$(document).ready(function() {
	$("a.topLink").click(function() {
		$("html, body").animate({
			scrollTop: $($(this).attr("href")).offset().top + "px"
		}, {
			duration: 500,
			easing: "swing"
		});
		return false;
	});
});

Fade in/out on hover

Another very cool effect is the fade in/fade out on mouseover. The code below set opacity to 100% on hover, and to 70% on mouseout.

 
$(document).ready(function(){
    $(".thumbs img").fadeTo("slow", 0.7); // This sets the opacity of the thumbs to fade down to 70% when the page loads

    $(".thumbs img").hover(function(){
        $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
    },function(){
        $(this).fadeTo("slow", 0.7); // This should set the opacity back to 70% on mouseout
    });
});

Equal column height

In a column based website, you often need all columns to have the same height. This snippet calculate the height of the higher column and automatically adjust all other columns to this height.

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

Get url parameters

Getting url parameters is pretty easy using jQuery. Check the snippet below:

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

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
$('object').prepend('');

Center an element

A function to place an element in the center ofthe page.

 
jQuery.fn.centerElement = function () {
  this.css ("position", "absolute");
  this.css ("top", ($ (window). height () - this.height ()) / 2 + $ (window). scrollTop () + "px");
  this.css ("left", ($ (window). width () - this.width ()) / 2 + $ (window). scrollLeft () + "px")
  return this;
}
$('#item').centerElement();

Source: tympanus.netcatswhocodejquery4uweb.enavu

This entry was posted in JS and tagged , , .

Leave a Reply

Your email address will not be published. Required fields are marked *