I have a problem to show and hide some div.
The only thing i have is a span with a class. Where we need to click on, to show or hide the div below the parent h2
I can’t add some classe’s to the h2 or div (this come from some cms, where we can’t add a css class), so we need to do it with some jquery.
<div>
<h2>
<span class="h2toggle">Heading (This shows an hide the div below)</span>
</h2>
<div>
<p>Some text</p>
<p>More text</p>
</div>
</div>
<div>
<h2>
<span class="h2toggle">Heading 2 (This shows an hide the div below)</span>
</h2>
<div>
<p>Some text 2</p>
<p>More text 2</p>
</div>
</div>
Now i have something like the following code.
But now, when the page will be loaded. The div around “some text” & “more text” will we hidden.
But you can see that it is not hidden from the beginning. It’s sliding up.
It should be hidden ( the div with text ) from the beginning. Without seeing any change to the page.
After that the page is loaded, it must be possible to toggle on the headings.
(function ($) {
$(function () {
$('.h2toggle').each(function () {
$(this).parent('h2').addClass('h2toggle');
$(this).removeClass('h2toggle');
$(this).parent().siblings(':not(h2):visible').slideUp()
});
$('.h2toggle').click(function () {
$(this).siblings(':not(h2):visible').slideUp()
$(this).siblings(':not(h2):hidden').slideDown()
});
});
})(jQuery);
demo using ternary operators:
DEMO FIDDLE
And it will act as a beautiful Accordion! (If other content is opened.. close it!)
In this case, how ternary operators work:
… And you’ll get the smallest script to get an accordion!
Happy coding!