HomeJavascriptDetect Mouse / Touch Hold Javascript

Detect Mouse / Touch Hold Javascript

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to detect mouse / touch hold. To build this project, we need HTML and Javascript.
 
This is going to be a quick yet easy-to-follow tutorial. If you are looking for more such tutorials to improve your javascript skills, you can check out this playlist here. This playlist consists of about 100+ javascript projects.

Video Tutorial:

If you are interested to learn by watching a video tutorial rather than reading this blog post you can check out the video down below. Also, subscribe to my youtube channel where I post new tips, tricks and tutorials every alternate day.

Project Folder Structure:

Before we start coding, let us take a look at the project folder structure. We create a project folder called – ‘Detect Mouse/Touch Hold’. Inside this folder, we have two files – these files are index.html and style.css. The first file is the HTML document, and the second one is the stylesheet. I have included the javascript code in the body element itself.

HTML:

We begin with the HTML code. First, copy the code below and paste it into your HTML document. The HTML code consists of a div with the class container. Inside this div, we have another div on which we will detect the mouse hold.

Next, we have a p tag to display if the mouse is being held down or released.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Detect Mouse/Touch Hold</title>
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div id="div-ref">Hold Mouse Here</div>
      <p id="result">Demo Text Here</p>
    </div>
    <!-- Script -->
    <script>
      //Create Initial References
      let divRef = document.getElementById("div-ref");
      let result = document.getElementById("result");
      let isMouseHold = true;
      let timeoutref;
      let deviceType = "";

      //Events Object
      let events = {
        mouse: {
          down: "mousedown",
          up: "mouseup",
        },
        touch: {
          down: "touchstart",
          up: "touchend",
        },
      };

      //Detect if the device is a touch device
      const isTouchDevice = () => {
        try {
          //We try to create Touch Event (It would fail for desktops and throw error)
          document.createEvent("TouchEvent");
          deviceType = "touch";
          return true;
        } catch (e) {
          deviceType = "mouse";
          return false;
        }
      };

      isTouchDevice();

      //Function on mouse down
      divRef.addEventListener(events[deviceType].down, (e) => {
        e.preventDefault();
        isMouseHold = true;
        //Mouse down will be considered mouse hold if it is being held down for more than 1500ms
        timeoutref = setTimeout(function () {
          //If mouse is being held down do this
          if (isMouseHold) {
            result.innerText = "Mouse is being held down";
          }
        }, 1500);
      });

      //Function on mouse up
      //If mouse is released do this
      divRef.addEventListener(events[deviceType].up, function () {
        //Clear the timeout
        clearTimeout(timeoutref);
        result.innerText = "Mouse hold is released";
      });
    </script>
  </body>
</html>

CSS:

You can skip the CSS code since I have used it to make the output more presentable.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #fec04f;
}
.container {
  height: 31.25em;
  width: 31.25em;
  background-color: #151515;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  border-radius: 0.5em;
  padding: 0 1.5em;
  text-align: center;
  box-shadow: 0 2em 4em rgba(84, 58, 11, 0.4);
}
#div-ref {
  font-size: 1.6em;
  height: 12em;
  width: 12em;
  background-color: #ffd68b;
  border-radius: 50%;
  display: grid;
  place-items: center;
  user-select: none;
  font-weight: 300;
  line-height: 1.8em;
}
p {
  font-size: 1.2em;
  width: 100%;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 0.8em 0;
  color: #ffffff;
  border-radius: 0.5em;
}

Javascript:

We implement the functionality using javascript. Now copy the code below and paste it into your script file. We add the logic to our project in the following steps:

  1. Create initial references.
  2. Create events object.
  3. Detect if the device is a touch device
  4. Function on mouse down.
  5. Detect if it is mouse hold.
  6. Function on mouse up.

That’s it for this tutorial. If you face any issues while creating this code, you can download the source code by clicking on the download button below. Also, if you have any queries, suggestions or feedback you can comment on them below.
Happy Coding!

Previous articleMCQ – 31/10/22
Next articleMCQ – 2/11/22
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

six + 6 =

Most Popular