jQuery toggle class got me stumped

I've read other post on this but it's still not working the way I want. It does apply the class, but the content of that class is not being applied. What's going wrong?

$(document).ready(function() {
  $('button').click(function() {
    $(this).toggleClass("active");
  });
});
.topBar {
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

.topBar span {
  margin-right: 34%;
}

.topBar button,
span {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.topBar button:hover,
span:hover {
  background-color: #ddd;
  color: #333;
}

.topBar button {
  background-color: #333;
  border: none;
}

.active {
  background-color: red;
}
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="//stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

<div class="topBar">
  <span>Code Player</span>
  <div class="topButtons">
    <button id="html">HTML</button>
    <button id="css">CSS</button>
    <button id="javascript">JavaScript</button>
    <button id="output">Output</button>
  </div>
</div>

View On Codepen

Upvotes: 2

Views: 26

Answers (1)

showdev
showdev

Reputation: 29168

This seems to be a matter of CSS specificity.

The selector .topBar button has a higher specificity than .active, so its definitions take precedence and the background-color of .active is overwritten.

If you change .active to .topBar .active, it will have a higher specificity.

$(document).ready(function() {
  $('button').click(function() {
    $(this).toggleClass("active");
  });
});
.topBar {
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

.topBar span {
  margin-right: 34%;
}

.topBar button,
span {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.topBar button:hover,
span:hover {
  background-color: #ddd;
  color: #333;
}

.topBar button {
  background-color: #333;
  border: none;
}

.topBar .active {
  background-color: red;
}
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="//stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

<div class="topBar">
  <span>Code Player</span>
  <div class="topButtons">
    <button id="html">HTML</button>
    <button id="css">CSS</button>
    <button id="javascript">JavaScript</button>
    <button id="output">Output</button>
  </div>
</div>

Upvotes: 1

Related Questions