A.J
A.J

Reputation: 1180

Adding content style to an element using JavaScript

I have the following HTML label:

<div class="VINDesc">
    <input class="toggle-box" id="toggle" onclick="sendVinCustomLink()">
    <label class="VINDesc-label" for="toggle">foo?</label>
    <p>NEW TEXT.</p>
</div

The label's css is the following:

.toggle-box + label:after {
    background-color: #3b434a;
    -webkit-border-radius: 2px;
    -moz-border-radius: 2px;
    border-radius: 2px;
    color: #FFFFFF;
    content: "+";
    font-weight: bold;
    height: 12px;
    margin-left: 5px;
    text-align: center;
    padding: 0px 2px;
}

My question is how do I add this style for when I click on it:

.toggle-box:checked + label:after {
    content: "\2212";
}

Everything I tried so far doesn't update the element. I am trying to make the + sign turn into a - on a click.

I added functionality to the sendVinCustomLink() function but it doesn't seem to update the label's appropriate css.

Any idea how this can be done?

EDIT #1:

https://i.sstatic.net/shsfY.jpg

Upvotes: 0

Views: 63

Answers (1)

Aib Syed
Aib Syed

Reputation: 3196

EDIT:

One way to do this is to declare content as a var in your CSS like this:

content:var(--content,"+");

Then target and change the content like this:

div.style.setProperty("--content", "'-'")

Additionally, to answer your other question in comments about toggling the content to its previous "+" state. Simply apply a boolean that you can change for each click like this:

var bool = false;

  if (bool === false) {
    div.style.setProperty("--content", "'-'")
    bool = true;
  } else if (bool === true) {
    div.style.setProperty("--content", "'+'")
    bool = false;
  }

With the above code we are effectively changing the content string based on the boolean we declared as bool. When true we see + and when false we see -.

See the snippet below:

var div = document.querySelector('.toggle-box + label');
var bool = false;

function changer() {
  if (bool === false) {
    div.style.setProperty("--content", "'-'")
    bool = true;
  } else if (bool === true) {
    div.style.setProperty("--content", "'+'")
    bool = false;
  }
}
.toggle-box+label:after {
  background-color: #3b434a;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  border-radius: 2px;
  color: #FFFFFF;
  content: var(--content, "+");
  font-weight: bold;
  height: 12px;
  margin-left: 5px;
  text-align: center;
  padding: 0px 2px;
}
<div class="VINDesc">
  <input class="toggle-box" id="toggle" onclick="changer()">
  <label class="VINDesc-label" for="toggle">foo?</label>
  <p>NEW TEXT.</p>
</div>

Upvotes: 1

Related Questions