Sunday, July 31, 2011

toggleSlide() and while loops.

I came across a problem tonight

That I thought I'd share a solution to. I was mysql_fetch_array()ing in a while loop to output a bunch of data in seperate divs, and since it was getting bulky and cluttered I decided to add a toggleSlide() so I could collapse them individually.

So I decided to supply an argument in the form of the entry id returned by the loop. I appended the id to the end of the divs in the loop and to the argument of my slide() function using a PHP echo. And this is where I hit a snag.

When you give toggleSlide() an argument and put it in the onclick selector, it accumulates your clicks. This must have something to do with the + sign you need to use when you add the argument. What this means is that

Function slide(arg) {
$('document').ready(function() {
$('#button'+arg).onClick(function() {
$('#slider'+arg).toggleSlide();
});
});

Will have an odd and unexpected effect. The first click won't have an effect at all, the second click will slide up and then back down, the thid click will move three times and so on. The trick here is to add an unbind() command to the button element. So

Function slide(arg) {
$('document').ready(function() {
$('#button'+arg).onClick(function() {
$('#slider'+arg).toggleSlide();
$('#button').unbind('click');
});
});

Will have your loop returned divs sliding around nicely!

Just to clarify, the div returned by your loop would look like this:

<div id="button<?php echo $id; ?>" onclick="slide(<?php echo $id ?>)"><img src="someimage.png" /></div>
<div id="slider<?php echo $id; ?>">Some content</div>

Look at me, gettin all tutorialicious and junk.

No comments:

Post a Comment