I'd like to present here some useful jQuery snippets which I use for my daily work with this library. I hope you find them useful.
Exit from a loop #1
$('li', '#nav').each(function() {
var $li = $(this);
if($li.attr('id') == 'current') {
$li.addClass('current');
return false;
}
});
Exit from a loop #2
$.getJSON(flickrURL, function(data) {
$.each(data, function(i, item) {
// ...
return i < 5; // returns the first 6 images
});
});
Get the current jQuery version
alert('jQuery ' + jQuery.fn.jquery);
Get the current image in a slideshow
var next = ($('img:first', '#slideshow').next().length) ? $('img:first', '#slideshow').next() : $('img:first', '#slideshow');
Reverse the order of an element set
var set = $('li', '#test');
var arr = $.makeArray(set);
var rev = arr.reverse();
Working with Wordpress
(function($) {
$.isHome = function() {
if(!$('body').hasClass('home')) {
return false;
}
return true;
};
$.isPage = function() {
if(!$('body').hasClass('page')) {
return false;
}
return true;
};
$.isSingle = function() {
if(!$('body').hasClass('single')) {
return false;
}
return true;
};
})(jQuery);
Multiple events on the same element
$('#test').bind('click mouseover', function(event) {
var evtType = event.type;
switch(evtType) {
case 'click':
handleClick(event);
break;
case 'mouseover':
handleHover(event);
break;
default:
break;
}
});
Attaching methods to elements
$('#test').data('data', {method: function(element) {
$(element).addClass('data');
}}).data('data').method('#test');