skip to Main Content

HTML

<h1 id="Title">Hover Me</h1>-

CSS

h1::before {  
  transform: scaleX(0);
  transform-origin: bottom right;
}

h1:hover::before {
  transform: scaleX(1);
  transform-origin: bottom left;
}

h1::before {
  content: " ";
  display: block;
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  inset: 0 0 0 0;
  background: hsl(200 100% 80%);
  z-index: -1;
  transition: transform .3s ease;
}

h1 {
  position: relative;
  font-size: 5rem;
}

Im trying to turn this into an effect that turns on/off by clicking the tittle.

I have tried changing it into a class and then making the hover a different one and try to toggle between these two classes

document.getElementById("Title").addEventListener("click", myFunction);

function myFunction() {
  var element = document.getElementById("Title");
  element.classList.toggle("Transform");
}  

2

Answers


  1. Replace the :hover pseudo-class with .Transform to match the element when it has the "Transform" class. Then, toggling the class on click will work.

    document.getElementById("Title").addEventListener("click", 
      e => e.target.classList.toggle("Transform"));
    h1::before {
      transform: scaleX(0);
      transform-origin: bottom right;
    }
    h1.Transform::before {
      transform: scaleX(1);
      transform-origin: bottom left;
    }
    h1::before {
      content: " ";
      display: block;
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      inset: 0 0 0 0;
      background: hsl(200 100% 80%);
      z-index: -1;
      transition: transform .3s ease;
    }
    h1 {
      position: relative;
      font-size: 5rem;
    }
    <h1 id="Title">Click Me</h1>-
    Login or Signup to reply.
  2. Well, @Unmitigated has given you a good solution. But I understanded your question in a different way. so here is my answer based on @Unmitigated code.
    change h1.Transform::before to h1.Transform:hover::before

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