I keep seeing codes like this:
$(document.documentElement).keyup( function(event) {
var slides = $('#slides .pagination li'),
current = slides.filter('.current');
switch( event.keyCode ) {
case 37: // Left arrow
if ( slides.filter(':first').is( current ) ) {
slides.filter(':last').find('a').click();
} else {
slides.eq( slides.index(current) - 1 ).find('a').click();
}
break;
case 39: // Right arrow
if ( slides.filter(':last').is( current ) ) {
slides.filter(':first').find('a').click();
} else {
current.find('+ li').filter(':first').find('a').click();
}
break;
}
});
For a line like this: current = slides.filter('.current');, .filter() is a jquery method, right? Then shouldn't it be current = $(slides).filter('.current');.
Does it work the way it is done in the code? Why?
2 Answers 2
slides is a jQuery object so you don't need to wrap it in $() like you do with a DOM object.
So slides.filter('.current') works like $('#slides .pagination li').filter('.current'). It's important to keep track of whether your objects are jQuery selectors, jQuery objects, and/or DOM objects.
Some people like to name their jQuery objects like var $slides as a mental note.
1 Comment
$. So, if I had written it, you'd have said var $slides = $('#slides .pagination li'); current = $slides.filter('.current');. I think this adds useful clarity, but maybe it's just the rebel Perl hacker in me.slides is already 'jQuery'ed: notice that it's defined using the $ sign. so there's no need to wrap it with a $ again.
$()is a function which returns a jQuery object. That object now has the jQuery functions on it.