I’m a little confused. Basically, I’ve got 16 span elements on my page which are displaying brands. I want to show only 4 brands at a time, and then set an interval to show the next 4 brands until I reach the end, at which point I’ll reset a counter and start from the beginning again. Here is what I was thinking:
- Display all brand span elements
- Put all of the brand elements into an array
- Count first 4 items (brands) and give them the class of visible
- After 5 seconds, hide all elements with class of visible
- Display the next 4 items in the array
- When the end of the array is reached, reset the counter and start again
Some general advice or help with jquery arrays would be appreciated. I’m looking for the most dynamic and simple solution possible.
Thanks 🙂
Here, it’s a bit hackish though…
Live demo: http://jsfiddle.net/hBrt6/
If you require an explanation of the code, just let me know…
A few explanations:
.get()returns an array of the DOM elements inside the jQuery object.So
gives you an array of all the DIV elements on the page.
Using the property accessor operator
[i]will give you the i-th DOM element from the jQuery object.So
returns the fifth DIV element on the page.
It is important to understand that you cannot invoke jQuery objects on DOM elements itself (or arrays of DOM elements).
So this
throws an error. DOM elements don’t have a
hidemethod.If you want to target a specific element inside a jQuery object and while still retaining a jQuery object, use
.eq().This
works just fine.
Now that you understand this difference, let me explain why I use
get()and[i]in my code: The thing is, I don’t like to store jQuery objects inside variables. Instead I prefer to work with DOM elements and arrays of DOM elements directly.When I need to invoke a jQuery method on some element or array of elements, I just wrap it inside the
$()function first.So this
works just fine.
And when the jQuery method has done the job, I just append
.get()or[0]to “unwrap” the jQuery object = to get my element(s) back.