Search code examples
javascriptdom-eventshovermouseeventaddeventlistener

How to change div background image upon hover and clicking but only leave when clicking back button?


Is it possible to change the background image of a div when hover and click but hold the changed background when clicked and only return to default state when clicking the back button? It should be able to return to default state when hover out if it's not clicked

HTML

<div class="main">
  <a class="backbutton"></a>
  <p>Menu</p>
  <a href="#" class="about">About</a>
  </div>

JS

const tag = document.querySelector(".about");
const bg = document.querySelector(".main");
let backButton = document.querySelector(".backbutton");

const aboutEnter = function () {
  bg.style.background = "cyan";
  backButton.innerHTML = "Back";
};

const aboutLeave = function () {
  bg.style.backgroundColor = null;
  backButton.style.display = "none";
};

const aboutEnterHover = function () {
  bg.style.backgroundColor = "cyan";
};

const aboutLeaveHover = function () {
  bg.style.backgroundColor = null;
};

tag.addEventListener("click", function () {
  aboutEnter();
});

backButton.addEventListener("click", function () {
  aboutLeave();
});

tag.addEventListener("mouseenter", function () {
  aboutEnterHover();
});

tag.addEventListener("mouseleave", function () {
  aboutLeaveHover();
});

Solution

  • Like this?

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <div class="main">
          <a class="backbutton">Remove BG</a>
          <p>Menu</p>
          <a href="#" class="about">About</a>
        </div>
    
        <script>
          let wasClicked = false;
    
          document.querySelector(".main").addEventListener("mouseenter", (e) => {
            if (wasClicked) return;
            e.currentTarget.style.background = "green";
          });
    
          document.querySelector(".main").addEventListener("mouseleave", (e) => {
            if (wasClicked) return;
            e.currentTarget.style.background = "transparent";
          });
    
          document.querySelector(".main").addEventListener("click", (e) => {
            wasClicked = true;
            e.currentTarget.style.background = "green";
          });
    
          document.querySelector(".backbutton").addEventListener("click", (e) => {
            document.querySelector(".main").style.background = "transparent";
            wasClicked = false;
            e.stopPropagation();
          });
        </script>
      </body>
    </html>