Following are 10 Useful jQuery snippets for any website. To use these snippets, you must include jQuery library in your page first and then add the snippets inside DOM ready function as follow:
$(document).ready(function() {
// add your snippets here
});
1. Display Warning Message for IE 6 Users
if ( (jQuery.browser.msie) && (parseInt(jQuery.browser.version) < 7) ) {
$('body').prepend('<div class="warning">You are using an old version of Internet Explorer which is not supported. Please upgrade your browser in order to view this website.</div>');
}
2. Add hasJS class to body tag when Javascript is enabled
$('body').addClass('hasJS');
3. Clear default text in input fields on click
Sample Usage:
<input type="text" name="search" class="search" value="Keywords" title="Keywords" />
$('input[type=text]').focus(function() {
var title = $(this).attr('title');
if ($(this).val() == title) {
$(this).val('');
}
}).blur(function() {
var title = $(this).attr('title');
if ($(this).val() == '') {
$(this).val(title);
}
});
4. Show/hide more content on click
Sample Usage:
<p><a href="#how-to" class="toggle">How to write a good article?</a></p>
<div id="how-top"> How to tips go here. </div>
$('a.toggle').toggle(function() {
var id = $(this).attr("href");
$(this).addClass("active");
$(id).slideDown();
}, function() {
var id = $(this).attr("href");
$(this).removeClass("active");
$(id).slideUp();
});
5. Open Print dialog
Sample Usage:
<a href="#" class="print">Print this page</a>
$('a.print').click(function(){
window.print();
return false;
});
6. Add “hover” class to table data (and change the background color of the class via CSS)
$('table').delegate('td', 'hover', function(){
$(this).toggleClass('hover');
});
7. Open link in a new window if rel is set to external
Sample Usage:
<a href="http://www.google.com" rel="external">Google</a>
$('a[rel=external]').attr('target', '_blank');
8. Add “odd” class to alternate table row (and change the background color of the class via CSS to have stripes effect for table)
$('tr:odd').addClass('odd');
9. Check if div exists on page
if ( $('#myDiv').length ) {
// do something with myDiv
}
10. Check/Uncheck all checkboxes
Sample Usage:
<div class="options"> <ul> <li><a href="#" class="select-all">Select All</a></li> <li><a href="#" class="reset-all">Reset All</a></li> </ul> <input type="checkbox" id="option1" /><label for="option1">Option 1</label> <input type="checkbox" id="option2" /><label for="option2">Option 2</label> <input type="checkbox" id="option3" /><label for="option3">Option 3</label> <input type="checkbox" id="option4" /><label for="option4">Option 4</label> </div>
$('.select-all').live('click', function(){
$(this).closest('.options').find('input[type=checkbox]').attr('checked', true);
return false;
});
$('.reset-all').live('click', function(){
$(this).closest('.options').find('input[type=checkbox]').attr('checked', false);
return false;
});








