Using jQuery the answer is simple. Just mark such buttons with a new class called toggle-text
and use <span>
and <span class="hidden">
to mark the text you want to toggle back and forward between:
<a class="btn btn-primary toggle-text" data-toggle="collapse" href="#collapseExample">
See <span>more</span><span class="hidden">less</span>...
</a>
You can have as many or few <span>
tags as you want and can order them as you want, all that's important is whether or not they're marked with class hidden
.
Now in jQuery you can do:
$('.hidden').removeClass('hidden').hide();
$('.toggle-text').click(function() {
$(this).find('span').each(function() { $(this).toggle(); });
});
The first line is a bit of boiler plate - jQuery and Bootstrap have somewhat conflicting ideas about hidden. This just flips everything you've marked as hidden using the Bootstrap class hidden
to being hidden by jQuery which makes it easier to use the
jQuery visibility functions afterwards.
The next bit is the important stuff - it installs a handler on all elements marked with our new class toggle-text
- this handler toggles the visibility of the <span>
children of the given element when it's clicked.
See everything in action with this jFiddle - http://jsfiddle.net/w3y421m9/1/
Note: the name toggle-text
is completely arbitrary and is just used for marking buttons for which we want this toggle behavior.
This is the first time I've written a question with the intention of answering it. I'm interested to see if someone has a better answer.
To me this solution looks super simple and has the big plus of keeping the button text together with the HTML for the button, without additional button specific CSS or Javascript/jQuery code.
The jQuery is nice in that it doesn't have to be customized on a per-button basis depending on the text you want to display. And you've got a lot of flexibility with mixing text that you do and don't want to toggle, e.g. the following are all equivalent:
<span>Show more...</span><span class=hidden">Show less...</span>
Show <span>more</span><span class=hidden">less</span>...
Show <span class=hidden">less</span><span>more</span>...