1

Am toggling few div's on my website which are looped using PHP, now what the issue is am passing div id, but this will make 10 scripts if am looping 10 articles, any better way to pass an id and open the associated div?

http://jsfiddle.net/NbGSB/

<script>
$('#toggle4').click(function() {
$('.toggle4').slideToggle('fast');
    return false;
});
</script>
<a href="#" id="toggle4">Slide Toggle</a><br /><br />
<div class="toggle4" style="display:none; background-color:#4CF;width:100px;height:200px;"></div>

Now what if am having multiple div's? do I need to pass the id always and loop the script too or is there any better way? sorry but am not good with jQuery

2 Answers 2

1

Yes, just give to your articles one class, like a "arcticle-toggle", then slide div after two br-tags: HTML:

<a href="#" class="article-toggle">Slide Toggle 1</a><br /><br />
<div style="display:none; background-color:#4CF;width:100px;height:200px;"></div>

<a href="#" class="article-toggle">Slide Toggle 2</a><br /><br />
<div style="display:none; background-color:#8CF;width:100px;height:200px;"></div>

​JS:

<script>
 $('.article-toggle').click(function() {
  $(this).next().next().next().slideToggle('fast');
 return false;
}
</script>

Fiddle.

Sign up to request clarification or add additional context in comments.

6 Comments

it doesn't work because the selector inside the onclick function is wrong. it is looking for a div inside the toggle link, but the two elements are siblings
@RandomGuy Please fix the code in this answer, so the accepted answer actually works.
Yes, I know, that next().next().next() is not better solution ;)
It's ugly, but at least it works. In this case, you can also use .next('div') instead of .next().next().next().
@Enrico, no, you can not. You can try .next('div') in my Fiddle and realize, that it's not working.
|
1

There are many ways to do it.

Without changing your html you could do it by putting this after all the toggles and divs - just before the </body> tag is usually a good place

<script type="text/javascript">
$('[id^="toggle"]').click(function() {
    $(this).next('[class^="toggle"]').slideToggle('fast');
    return false;
});
</script>

$('[id^="toggle"]') and $('[class^="toggle"]') select all elements whose id and class start with "toggle", respectively.

Comments

Your Answer

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.