All -
I seem to have an interesting issue in addressing a requirement where clicking a button not only shows/hides a div below it (hence the ID value on the button), but also must change the text within the button as well as an Alloy icon to go from icon-collapse to icon-collapse-top (see more here: http://nickpiesco.github.io/alloy-ui-font-awesome-cheatsheet/)
HTML
<div class="button-holder">
<button class="btn btn-primary toggle-hidden" id="1">Expand
Options <span class="icon-collapse"></span></button>
</div>
JS
$(".hidden-group").hide();
$(".toggle-hidden").click(function(e) {
event.preventDefault();
var text = $(this).text();
$(this).text(
text == "Minimize Options" ? "Expand Options" : "Minimize Options");
$(this).find("span").toggleClass( "icon-collapse" );
$(this).find("span").toggleClass( "icon-collapse-top" );
$("#hidden-" + e.target.id).toggle(250);
});
The problem is, if I comment out the .text() replacement code (which works), the .toggleClass() code will begin to work again. With the .text() code, the text replacement will cause the tag to go away when investigating in Chrome developer tools. After toggling a few times, it will look like this, no span included:
<button class="btn btn-primary toggle-hidden" id="1">Minimize Options</button>
I've tried seeing if I can just add the span into the text replace code, but then you'll just get the actual text in the button.
Is there a way to prevent .text() replacement from removing the span after it as well (which causes an image to be at the end of this button)? Other thoughts or suggestions are also welcome.
You can keep a copy of the span before replacing the text and then you can append it latter. Something like
$(".toggle-hidden").click(function(e) {
e.preventDefault();
var text = $(this).text();
var $span = $(this).find("span");
$(this).text(
text == "Minimize Options" ? "Expand Options" : "Minimize Options");
$(this).append($span);
$(this).find("span").toggleClass("icon-collapse");
$(this).find("span").toggleClass("icon-collapse-top");
$("#hidden-" + e.target.id).toggle(250);
});