Button click to fade in and out content with jQuery

Example of button click to fade in and out content with toggle state using jQuery.

button click to show and hide contentCodePen example.

Firstly a couple of functions:

The fade out and remove the element function:

function fadeRemove(element, length) {
  $(element).fadeOut(length, function () {
    $(this).remove();
  });
}

Check if element exists and remove it:

function alreadyExists(element) {
  if ($(element).length) {
    fadeRemove(element, 400);
  }
}

The main Javascript part, monitor the button clicks and react based on their state:

var btnOneClicked = false;
var btnTwoClicked = false;

$(document).ready(function () {
  $("#btnOne").click(function () {
    if (btnOneClicked) {
      $("#btnOne").removeClass("active");
      fadeRemove("#btnOneCard", 400);
      btnOneClicked = false;
    } else {
      alreadyExists("#btnOneCard");
      $("#btnOne").addClass("active");
      btnOneClicked = true;
      var cardOne =
        '<div class="col-12"><div class="card text-white bg-primary" id="btnOneCard"><div class="card-header">ONE</div><div class="card-body"><h4 class="card-title">btnOne</h4></div></div>';
      $(cardOne).hide().appendTo("#buttons").fadeIn(800);
    }
  });
  $("#btnTwo").click(function () {
    if (btnTwoClicked) {
      $("#btnTwo").removeClass("active");
      fadeRemove("#btnTwoCard", 400);
      btnTwoClicked = false;
    } else {
      alreadyExists("#btnTwoCard");
      $("#btnTwo").addClass("active");
      var cardTwo =
        '<div class="col-12"><div class="card text-white bg-success" id="btnTwoCard"><div class="card-header">TWO</div><div class="card-body"><h4 class="card-title">btnTwo</h4></div></div></div>';
      $(cardTwo).hide().appendTo("#buttons").fadeIn(800);
      btnTwoClicked = true;
    }
  });
});

The two buttons start as normal (not actively clicked), once clicked a card will fade in and the button will obtain the active class. If that button is clicked again then the card fades out and the button returns to normal state i.e the active class gets removed.

Basic HTML layout:

<div class="container">
  <div class="row text-center mt-3" id="buttons">
    <div class="col-12 mb-3">
      <a href="#" id="btnOne" class="btn btn-primary mx-2" role="button">btn One</a>
      <a href="#" id="btnTwo" class="btn btn-success mx-2" role="button">btn Two</a>
    </div>
  </div>
</div>

Video example: