skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. 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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search