skip to Main Content

I’m wondering if there is anyway to make :not(:hover) not trigger on the moment the page is loaded or after a refresh.

I want the button to not be red when the page is loaded, and only be red after the mouse has already hovered over and left at least once.

.test:hover {
  background-color: yellow;
}

.test:not(:hover) {
  background-color: red;
}
<button class="test">hello</button>

codepen

2

Answers


  1. The easiest way i know is to add your test class only after the first hover event.

    I would do that with JavaScript.
    I would add an event listener that when triggered add the CSS class.

    Possibly the event listener would also remove itself from that element so that it don’t trigger more then once

    Here you can find more on the mousehover event

    var element = document.getElementById("abc");
    
    element.addEventListener("mouseenter", () => {
      element.classList.add("test");
    });
    .test:hover {
      background-color: yellow;
    }
    
    .test:not(:hover) {
      background-color: red;
    }
    <button id="abc" class="">hello</button>
    Login or Signup to reply.
  2. You can do something like this. Initially, and when not hovered the button’s background is transparent, and the background of the ::before pseudo-element is shown. That’s initially yellow, so the button appears yellow.

    When the button is hovered, the background of the ::before pseudo-element is instantly changed to red, but the button’s background is changed to yellow which is on top of the pseudo-element, so the button still appears yellow,

    When the button stops being hovered, the button’s background is changed back to transparent, but the ::before pseudo-element’s background color change is delayed almost indefinitely, so the button appears red. Hovering the button will change it to yellow again for the duration of the hover.

    .test:hover {
      background-color: yellow;
    }
    .test {
      background-color: transparent;
      position: relative;
    }
    .test::before {
      content: '';
      position: absolute;
      inset: 0;
      background-color: yellow;
      transition-delay: 10000s;
      z-index: -1;
    }
    .test:hover::before {
      transition-delay: 0s;
      background-color: red;
    }
    <button class="test">hello</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search