changing inline css variable using javascript does not reflect on psudo selector content property

61 Views Asked by At

writing text using ::after pseudo selector using content property and it's value comes from inline css variable. now on click of the text I am able to change the css variable value ( can be seen in console) but it is not reflecing on the pag, i.e. not being applied in pseudo selector.

const toggleButton = document.getElementById("toggle");
const textSpan = document.querySelector(".text");

toggleButton.addEventListener("change", (e) => {
  textSpan.style.setProperty("--content", e.target.checked ? "a" : "A");
});
label {
  cursor: pointer;
}

.toggle {
  margin-inline: 1rem;
}

input[type="checkbox"] {
  display: none;
}
.text::after {
  content: var(--content);
  height: 4px;
  width: 4px;
  color: rgb(35, 174, 27);
  position: relative;
}
<label for="toggle" class="toggle">
    <input type="checkbox" name="change_case" id="toggle">
    <span class="text" style="--content: 'A'"></span>
    click to toggle
</label>

what could be the issue here?

2

There are 2 best solutions below

0
CBroe On

It's because you are setting a wrong value for the variable - A != 'A'

The value that you are assigning, needs to be a string value in CSS - so it needs quotes around it, same as the value you originally set in your HTML.

const toggleButton = document.getElementById("toggle");
const textSpan = document.querySelector(".text");

toggleButton.addEventListener("change", (e) => {
  textSpan.style.setProperty("--content", e.target.checked ? "'a'" : "'A'");
});
label {
  cursor: pointer;
}

.toggle {
  margin-inline: 1rem;
}

input[type="checkbox"] {
  display: none;
}
.text::after {
  content: var(--content);
  height: 4px;
  width: 4px;
  color: rgb(35, 174, 27);
  position: relative;
}
<label for="toggle" class="toggle">
    <input type="checkbox" name="change_case" id="toggle">
    <span class="text" style="--content: 'A'"></span>
    click to toggle
</label>

0
user3302090 On

Before Click:

<span class="text" style="--content: 'A'"></span>

After Click :

<span class="text" style="--content: a;"></span>

After Click should be

<span class="text" style="--content: 'a';"></span>

You missing '' (single quote after click)