Home > front end >  How to make a div disappear when someone uses a touch screen device?
How to make a div disappear when someone uses a touch screen device?

Time:03-30

I'm trying to make an div which follows your cursor but I want it to like, disappear if someone uses a touch screen device. Is it possible to do this with only CSS or plain JAVASCRIPT?

<!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>
    <style>
      *,
      *::after,
      *::before {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100vh;
        overflow: hidden;
        background: #111;
      }

      #box {
        position: fixed;
        z-index: 824809238;
        border-radius: 50%;
        width: 50px;
        height: 50px;
        border: 3px solid dodgerblue;
        top: var(--y);
        left: var(--x);
        transform: translate(-50%, -50%);
        filter: drop-shadow(0px 0px 10px rgba(255, 255, 255, 0.5));
        animation: animate 2s linear infinite;
      }

      @keyframes animate {
        0% {
          filter: hue-rotate(0deg);
        }

        100% {
          filter: hue-rotate(360deg);
        }
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
    <script>
      let box = document.getElementById("box");

      window.addEventListener("mousemove", (e) => {
        box.style.top = `${e.clientY}px`;
        box.style.left = `${e.clientX}px`;
        box.style.opacity = "1";
      });

      window.addEventListener("mouseout", () => {
        box.style.transition = "opacity 0.5s ease";
        box.style.opacity = "0";
      });
    </script>
  </body>
</html>

This is my code but I have no idea how to make it disappear with touch screen devices as I said.

Any Ideas?

CodePudding user response:

Use touchstart/touchend events:

    window.addEventListener("touchstart", () => {
      box.style.display = 'none';
    })
    window.addEventListener("touchend", () => {
      box.style.display = 'block';
    })
  • Related