2

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?

asked Aug 18, 2011 at 23:17
1
  • $() is a function which returns a jQuery object. That object now has the jQuery functions on it. Commented Aug 18, 2011 at 23:21

2 Answers 2

4

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.

answered Aug 18, 2011 at 23:18
Sign up to request clarification or add additional context in comments.

1 Comment

It's to reduce confusion about what's a "jQuery" variable and what's not that I employ the convention of prefixing jQuery variables with $. 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.
0

slides is already 'jQuery'ed: notice that it's defined using the $ sign. so there's no need to wrap it with a $ again.

answered Aug 18, 2011 at 23:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.