5

I'm trying to swap out content within a button that toggles a nav collapse.

I currently have the following code;

<button class="navbar-toggle collapse in" data-toggle="collapse" id="menu-toggle-2"> <i class="fa fa-expand" aria-hidden="true"></i> Expand</button>
//in js script
$("#menu-toggle-2").click(function(e) {
    e.preventDefault();
    $("#page").toggleClass("toggled-2");

});

I want to be able to change the content within to be;

<i class="fa fa-compress" aria-hidden="true"></i> Collapse

This needs to be toggled however, so when you click collapse, it changes back to its original state

Can't seem to figure it out...

3 Answers 3

1

This is probably what you are looking for: https://jsfiddle.net/oaftwxt2/

var clicked = 0;

$("#menu-toggle-2").click(function(e) {
    e.preventDefault();
    $("#page").toggleClass("toggled-2");

    if(clicked == 0){    
        $(this).html('<i class="fa fa-compress" aria-hidden="true"></i> Collapse');
        clicked = 1;
    }else{
        $(this).html('<i class="fa fa-expand" aria-hidden="true"></i> Expand');
        clicked = 0;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the firstElementChild to get the <i> and then change its className according to the actual className, so it will toggle between the two classes you want:

$("#menu-toggle-2").click(function(e) {
  e.preventDefault();
  var i = this.firstElementChild;
  i.className = i.className === 'fa fa-expand' ? 'fa fa-compress' : 'fa fa-expand';
  $("#page").toggleClass("toggled-2");
});

7 Comments

Watch out for .className you might wanna use .hasClass(class) instead
There is no need to use jQuery for that, since I can do it with vanilla JS as easy as.
And what happens if I somewhere else do: my_i_el.className += ' shit-happends'
Also note that firstElementChild is first supported in IE9 developer.mozilla.org/en-US/docs/Web/API/ParentNode/…
That will not happen with a font awesome icon.
|
0

This is how I would do it:

$(".navbar-toggle").click(function () {
    if ($(this).text().trim() == "Expand") {
        $(this).find("i").removeClass("fa-expand").addClass("fa-compress");
        $(this).contents()[2].data = "Collapse";
    } else {
        $(this).find("i").removeClass("fa-compress").addClass("fa-expand");
        $(this).contents()[2].data = "Expand";
    }
});

Here is the JSFiddle demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.