Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery toggle content inside element

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...

like image 393
grhmstwrt Avatar asked Oct 30 '22 15:10

grhmstwrt


2 Answers

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;
    }
});
like image 148
Nealime Avatar answered Nov 12 '22 16:11

Nealime


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");
});
like image 41
Buzinas Avatar answered Nov 12 '22 15:11

Buzinas