0

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 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

damn spent an hour trying to figure out what I did wrong till I saw this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.