Monday, April 23, 2012

Rotate content with jQuery.

After having a few times that I've had to rotate content I decided to simplify some javascript. There are several plugins out there, but they seem to all be much bigger than I think is needed to simply rotate some content. To start with I have a simple layout for the content. A wrapper element with child elements. The example uses divs with a class, however, an unordered list works just as well with a small tweak to the selectors. The javascript is simple. This is not in a plugin, so a only 1 per page is supported with this code, but it should be able to be converted to a plugin pretty simply. Finally the result is a simple item that fades in and out. The rotation doesn't take control of any of the layout of your page, it simple shows and hides the html. I have a few ideas to clean up the code, it could look for the next sibling and show it instead of keeping a counter, and then show the first on when the last one is hidden. I think the selectors for that would be more complicated though and I like the simplicity that this implementation offers.

8 comments:

Anonymous said...

When doing this for for a split second before the first fadeout the divs are all shown.

Also how do I take this to the next level and fetch it from my json source?

Steven Rigney said...

I didn't have a problem with all of them showing before fading out. If you want you can start with all of them hidden. You'll have to tweak the code to show the first one first. If they all start hidden then your page will still jump around a little bit.

If you want ajax, then I would have the setInterval be an ajax call to get the next one, and when that call completes do the fade out and fade in.

jack long said...
This comment has been removed by the author.
jack long said...
This comment has been removed by the author.
jack long said...

When I fade this in using a button, all three divs appear and then it starts on a random one. how do I get it to stop this and start it on the one I want?

Steven Rigney said...

You should be able to use a button to stop and start it if you use the clearInterval() method.

Anonymous said...

Hi, i'm also have a problem the same some user here also.

When doing this for for a split second before the first fadeout the divs are all shown.

cound u tell me how to solve this ?
Thank

Jim Shaffer said...

I would agree with the other users, when the page initially loads, all child elements are visible. I also observed this behavior on this page. Just refresh the page.