Reputation: 1344
I need small ammendment in the following jquery code. (DEMO is here)
If you notice in the demo, Heading One is sliding perfectly up/down as I want but Heading Two and Three are not. The difference is only I added another div around ( "Heading Two" , "Heading Three" ) tag. I know, there needs to be done something with this line $(this).next("p").slideToggle("fast"); but I am not sure how to do that as I am begginer in Jquery.
Following is my code
$(document).ready(function(){
$("p").hide();
$("h3").click(function(){
$(this).next("p").slideToggle("fast")
$(this).toggleClass("active");
});
$('.mylink').click(function(){
$(this).parent('p').prev().trigger('click');
})
});
Please Guide
Upvotes: 1
Views: 867
Reputation: 29251
While not perfect, this will get you the functionality you want:
$(document).ready(function(){
$("p").hide();
$("h3").click(function(){
$(this).closest('.accordion').find("p").slideToggle("fast");
$(this).toggleClass("active");
});
$('.mylink').click(function(){
$(this)
.parent()
.slideToggle('fast')
.closest('.accordion')
.find('h3')
.toggleClass('active');
})
});
Main changing being the use of closest()
to locate the parent .accordion
and use that as a point of reference to find()
your p
element.
Edit: codepen is borked for some reason, here's a jsfiddle
Upvotes: 3
Reputation: 1635
Alright If you need to preserve the structure the .next() has to go. I couldn't figure out a less-messy way to do this, but combine the and it's parent tag and look for sibling
:
$(this).parent().addBack().siblings("p").slideToggle("fast")
And as far as I can tell it works just fine: http://jsfiddle.net/damyanpetev/U3zFR/5/
Upvotes: 0
Reputation: 49843
the problem in your code is you are using a parent div on two and three headings, this works for exmple:
<h3 class="some_class">Heading One</h3>
but not this with your code
<div class="some_class"><h3>Heading One</h3></div>
Upvotes: 0