Suraiz Ahamed
Suraiz Ahamed

Reputation: 43

Hiding button after collapse is toggled using Javascript

I'm trying to hide the "collapsible" button after it is being pressed.

activities.html:

<button class="collapsible"> <i class="fa fa-angle-down"></i></a></button>

Controller.js:

    var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var gallery1 = this.nextElementSibling;
    if (gallery1.style.maxHeight){
      gallery1.style.maxHeight = null;
    } else {
      gallery1.style.maxHeight = gallery1.scrollHeight + "px";
    } 
});
}

I would highly appreciate if someone could help me out of this!

Upvotes: 2

Views: 589

Answers (2)

Rick
Rick

Reputation: 4126

To hide your button and remove the space occupied by the button on the page, use .style.display = 'none' on the button element in the event handler:

var coll = document.getElementsByClassName("collapsible");

for (var i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");    
    
    var gallery1 = this.nextElementSibling;
    
    if (gallery1.style.maxHeight) {
      gallery1.style.maxHeight = null;
    } else {
      gallery1.style.maxHeight = gallery1.scrollHeight + "px";
    }
    
    this.style.display = 'none';
  });
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<button class="collapsible"><a><i class="fa fa-angle-down"></i></a></button>

To keep the space occupied by the button on the page and make it invisible, use .style.visibility = 'hidden':

var coll = document.getElementsByClassName("collapsible");

for (var i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");    
    
    var gallery1 = this.nextElementSibling;
    
    if (gallery1.style.maxHeight) {
      gallery1.style.maxHeight = null;
    } else {
      gallery1.style.maxHeight = gallery1.scrollHeight + "px";
    }
    
    this.style.visibility = 'hidden';
  });
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<button class="collapsible"><a><i class="fa fa-angle-down"></i></a></button>

Upvotes: 4

Rohit.007
Rohit.007

Reputation: 3502

The shortest solution to your problem is

<button class="collapsible" onclick="this.style.display = 'none';">

Upvotes: 2

Related Questions