2

I have an anchor tag which hides or shows a div but I've been unable to change it's text and icon.

How do I change the text AND icon tag, as currently it parses the icon tag out as regular text.

Anchor tag:

<a class="collapse-info btn"><i class="icon-arrow-up icon-white"></i> Hide Info</a>

I need the class to go from "icon-arrow-up icon-white" to "icon-arrow-down icon-white" and back during toggles.

Javascript (jquery)

$('.collapse-info').toggle(function() {
$('.server-info').slideUp();
$(this).text('Show Info');
}, function () {
$('.server-info').slideDown();
$(this).text('Hide Info');
});

Was trying something like $("#collapse-icon").toggleClass('icon-arrow-down'); but that won't work since the anchor text is overwritten after the initial toggle.

Thanks for any help.

MCG
  • 583
  • 4
  • 8
  • 18

2 Answers2

3

Try this - DEMO

$('.collapse-info').toggle(function() {
    //$('.server-info').slideUp();
    $(this).find("i").removeClass("icon-arrow-up").addClass("icon-arrow-down");
    this.childNodes[1].nodeValue = "Show Info";
}, function () {
    //$('.server-info').slideDown();
    $(this).find("i").removeClass("icon-arrow-down").addClass("icon-arrow-up");
    this.childNodes[1].nodeValue = "Hide Info";
});
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
  • Thanks works great. Was not aware of childnodes but great to know! – MCG Feb 17 '13 at 23:22
  • Sorry to bring this question back from the dead but I can't seem to figure out what I changed to my code to cause the button to disappear on load. http://jsfiddle.net/wdD7B/ I've tried to comment out certain parts but I can't pinpoint the reason. – MCG Mar 13 '13 at 21:37
  • that's jQuery changed smth ( have no time to go through the changelog ), but if you use 1.8.3 instead of 1.9 it just works - http://jsfiddle.net/wdD7B/1/ – Zoltan Toth Mar 14 '13 at 21:31
0

first of all, the <i> tag is used for italic text and not icons.
now to answer your question, i'm assuming you have some kind of background image assigned to your <i> tag that you'd like to change.
why don't you assign the class to the <a> tag itself, instead of an element inside the a tag. then changing the html of the a tag won't cause you a problem.
your js would then look like the following:

$('.collapse-info').toggle(function() {
  $('.server-info').slideUp();
  $(this).text('Show Info');
  $(this).addClass('icon-arrow-down').removeClass('icon-arrow-up');
}, function () {
  $('.server-info').slideDown();
  $(this).text('Hide Info');
  $(this).addClass('icon-arrow-up').removeClass('icon-arrow-down');
});
clem
  • 3,345
  • 1
  • 22
  • 33
  • Thanks for the suggestion but unfortunately it seems twitter bootstrap (my framework) decided to use for their icons so not much of a choice there: http://twitter.github.com/bootstrap/base-css.html#icons – MCG Feb 17 '13 at 23:17