skip to Main Content

How does one use the user’s interaction with an html element to remove a pseudo element? I have an element with a pseudo element, which has 50% width and absolutely positioned. I would like to remove the pseudo element permanently once its parent has been interacted with by the user.

.test {
  position: relative;
  background: blue;
}

.test::before {
  content: "some text";
  background: red;
  width: 50%;
  position: absolute;
}
<div class="test">Lorem ipsum dolor sit.</div>

Using :hover, :active and :focus on the parent doesn’t work. Thanks.

2

Answers


  1. Wihle there are ways to interact with pseudo-elements in JS, a far easier method to do what you require in this case is to associate the psuedo-element with a CSS class, then use JS to add/remove/toggle that class under whatever event you need.

    Here’s a working example of that concept:

    const testElement = document.querySelector('.test');
    
    document.querySelector('button').addEventListener('click', e => {
      testElement.classList.toggle('foo');
    });
    .test {
      color: #FFF;
      position: relative;
      background: #00C;
    }
    
    .foo::before {
      content: "some text";
      background: #C00;
      width: 50%;
      position: absolute;
    }
    <div class="test foo">Lorem ipsum dolor sit.</div><br />
    
    <button>Click me</button>
    Login or Signup to reply.
  2. Unfortunately this cannot be accomplished with pure css. However, this can be easily done with vanilla js, by adding a selected class on click.

    document
      .getElementsByClassName("test")[0]
      .addEventListener("click", (event) => {
        event.target.classList.add("selected")
      }) 
    .test {
      position: relative;
      background: blue;
    }
    
    .test.selected::before {
      content: none;
    }
    
    .test::before {
      content: "some text";
      background: red;
      width: 50%;
      position: absolute;
    }
    <div class="test">Lorem ipsum dolor sit.</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search