I have about 25 show/hide (toggle) elements on a page like so…
HTML:
<h2><a href="#" class="link1">Headline One</a></h2>
<div class="toggle-item-link1">content</div>
<h2><a href="#" class="link2">Headline Two</a></h2>
<div class="toggle-item-link2">content</div>
JS:
$('[class^=toggle-item]').hide();
//toggle content on click
$('[class^=link]').click(function() {
var $this = $(this);
var x = $this.attr("className");
$('.toggle-item-' + x).toggle();
$(this).text($(this).text() == 'open' ? 'close' : 'open');
So what is happening is that the H2 text (Headline One, Headline Two) is being completely replaced with the text “open/close” depending on the toggle state. What I want to do is add Open/Close text to the actual headline depending on the toggle state.
For example:
Open Headline One / Close Headline One
Open Headline Two / Close Headline Two
I’m just not seeing how to do that here. Any help would be great. Thanks!
Just to keep things simple, I’d put the Open/Close text in a span, and reference that:
Example: http://jsfiddle.net/8TXDM/1/
HTML
jQuery
Also, instead of selecting the
.toggle-item-element from the DOM each time, I’d probably just traverse there.Example: http://jsfiddle.net/8TXDM/2/