I have divs created within a while loop displaying a MySQL query. I'd like to hide and show them with .slideToggle. I can't use one class as that would trigger every specific div on the page to slide down.
I thought this would repeat within the while loop and find the closest toggleSectionDyn div id. Obviously not.
<div class="actions"><a href="#" id="toggleButtonDyn">Add</a></div>
<div id="toggleSectionDyn">Some content</div>
<script>
$("#toggleButtonDyn").click(function(){
$(this).closest("#toggleSectionDyn").slideToggle("slow");
return false;
});
</script>
EDIT: live is deprecated. consider using .on()
you want to use .live()
$("#toggleButtonDyn").live('click', (function(){
$(this).closest("#toggleSectionDyn").slideToggle("slow");
return false;
});
from the .live() api
The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree.
Now, upon re-reading, I wonder exactly what your asking. You must also make sure each <div>
must have a unique ID. You may consider you .next('div')
instead of .closest()
Per the discussion in comments, I would use .next('div') look at the modified jsfiddle from yesterdays question http://jsfiddle.net/ycpgD/
also, I would strongly recommend using unique ID's. if they cannot be unique make them classes.
You can target the div you're after, if you refactor a little. (Maybe I'm missing the issue here, but my solution is pretty straight forward).
<div class="actions">
<div><a href="#">Add</a>
<p>Some content</p></div>
<div><a href="#">Add</a>
<p>Some content</p></div>
</div>
$(".actions a").click(function(){
$(this).next('p').slideToggle("slow");
return false;
});
I suppose it depends where you're generating that <a>
. If it's a going to hide the entire MySQL result set, or is it going to show/hide each row one at a time?