I am almost finished reading Learning jQuery 1.3 by Karl Swedberg, Jonathan Chaffer ; I’d like to share some useful methods and code snippets that may come handy to web designers when it is time to handcoding our beautiful layouts.
Reference: jquery.com
First of all let’s add JQuery to our page:
<script type="text/javascript" src="jquery.js"></script>
Launching code:
$(document).ready(function(){
// Your code here
});
These are the methods I find more useful:
- the .noConflict() method enables the use of multiple JS libraries (like Prototype)
- the .addClass and .removeClass
$(document).ready(function(){ $('#your_id').addClass('your_class'); }); - the negation pseudo-class:
$('#your_id li:not(.your_class)').addClass('your_class'); - the :eq custom selector – selects the third item from a matched set of div selectors with a ‘my_class’ class
$('div.my_class:eq(2)') - the :nth-child custom selector – matches elements which are the indexth child of their parent element
$('tr:nth-child(index)').addClass('your_class'); - the :odd and :even custom selectors:
$('tr:odd').addClass('your_class'); - the :contains() selector:
$('td:contains(name)').addClass('your_class'); - form selectors: :text, :checkbox, :radio, :button, :enabled, :checked, :selected
Shorthand events:
- .click()
- .toggle and .toggleClass()
$(document).ready(function() { $('#my_id').click(function() { $('#my_id .button').toggleClass('my_class'); }); }); - .hover
$(document).ready(function() { $('#my_id .button').hover(function() { $(this).addClass('my_class'); }, function() { $(this).removeClass('my_class'); }); }); - .css
$(document).ready(function() { $('#my_id').css('border', '1px solid #000') }); -
.hide and .show
$(document).ready(function() { $('p').hide(); });
This in particular is very useful as it can perform actions in alternation.
