The following are 10 useful jQuery code snippets. Before using the code, you need to import the jQuery class library to the web page and add the code to the following DOM ready function:
$(document).ready(function() { // add your snippets here });
1. display warning information for IE6 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 the hasJS class to the body tag when Javascript is available
$('body').addClass('hasJS');
3. Click it to clear the content in the input box.
<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 after clicking
<p><a href="#how-to" class="toggle">How to write a good article?</a></p><div id="how-to"> 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 the printer dialog box
<a href="#" class="print">Print this page</a>$('a.print').click(function(){ window.print(); return false;});
6. Add "hover" class to table data
$('table').delegate('td', 'hover', function(){ $(this).toggleClass('hover');});
7. If rel is set to "external", open a link in a new window.
<a href="http://www.google.com" rel="external">Google</a>$('a[rel=external]').attr('target', '_blank');
8. Add an odd row class to differentiate table rows (change the background color of table parity rows to achieve the effect of partition branches)
$('tr:odd').addClass('odd');
9. Check whether the div exists on the page
if ( $('#myDiv').length ) { // do something with myDiv}
10. Select/not select all check boxes
<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;});