Mystic
Mystic

Reputation: 157

Changing div class with JS

Im trying to collapse a panel with a button id="collapsible" which works, and then i need to change the class of the panel below id="gamewindow" to fill the entire screen, so with bootstrap i need to change col-md-9 to col-md-12 and this is the part that isnt working.

My html :

<div class="collapse in" id="collapsible">
....
</div>
<div id="gamewindow" class="col-md-9">
....
</div>

My JS :

if( $("#xs-check").is(":visible") )
    $("#collapsible").removeClass("in");
    $("#gamewindow").removeClass("col-md-9");
    $("#gamewindow").addClass("col-md-12");

my button

<button class="btn btn-link" data-toggle="collapse" data-target="#collapsible">Toggle Stats</button>

What am i doing wrong?

Upvotes: 0

Views: 390

Answers (2)

Lahar Shah
Lahar Shah

Reputation: 7644

Put that JavaScript code inside jQuery document ready function like below.

Then instead of removing and adding classes. use toggleClass. I am using col-xs as output screen is smaller here.

$( document ).ready(function() {
    //Put your code here that you want to execute on load    

   if( $("#xs-check").is(":visible") ) {
       $("#collapsible").removeClass("in");
       //Remove: $("#gamewindow").removeClass("col-md-9");
       //Remove: $("#gamewindow").addClass("col-md-12");
       $("#gamewindow").toggleClass("col-xs-12 col-xs-9");
    }

});

Below is Working example how to toggle 9 and 12 classes. I am not sure how exactly you want but you can get idea from this working example.

//Change ID as per your requirements 

$( "#btn_ID" ).click(function() {  
   $("#gamewindow").toggleClass("col-xs-12 col-xs-9");
});
#gamewindow, #collapsible {
  border: 1px solid black
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<button id="btn_ID" class="btn btn-link" data-toggle="collapse" data-target="#collapsible">Toggle Stats</button>

<br />

<div class="collapse in" id="collapsible">
    Collapsible
</div>

<div id="gamewindow" class="col-xs-12">
    <p>
      Content  
    </p>
</div>

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You've a correct code just try to wrap you code by ready function and add {} to your if statement :

$(function(){
    if( $("#xs-check").is(":visible") )
    {
        $("#collapsible").removeClass("in");
        $("#gamewindow").removeClass("col-md-9");
        $("#gamewindow").addClass("col-md-12");
    }
})

NOTE : Make sure that the $("#xs-check").is(":visible") will be achieved.

Hope this helps.

Upvotes: 0

Related Questions