Want to add "click and hold" functionality to your website? ️ This comprehensive guide teaches you how to use JavaScript to detect long button presses.
JavaScript method used:
Settimeout
JavaScript events used:
Onmouseup
Onmousedown
Onmouseleave
Check if the button is held down using JavaScript.
First, we'll create a function that executes when the mousedown event occurs on a button. Inside this function, we'll employ the setTimeout method to specify the duration for which the user must hold the button before a particular function is triggered. Within the setTimeout method, we'll insert text, but you can also incorporate a function that you want to execute upon a button hold.
Additionally, we'll implement mouseup and mouseleave events to clear the setTimeout. This is essential because if the user simply clicks the button without holding it for longer than the specified timeout, the setTimeout would still be initiated.
HTML
<!DOCTYPE html>
<html lang="en">
<!-- maketechstuff.com -->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Button hold Detection in JavaScript. | maketechstuff.com</title>
</head>
<body>
<h2 style="text-align: center; padding-top: 250px; color: #fff; font-size: 30px;">Maketechstuff.com</h2>
<div class="box">
<button type="button" class="button">Click & Hold</button>
<div class="output"></div>
</div>
</body>
</html>
CSS
* {
padding: 0px;
margin: 0px;
}
body {
width: 100%;
height: 100%;
background-color: #2196F3;
}
.box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% , -50%);
background-color: #fff;
width: 300px;
border-radius: 3px;
padding: 35px;
box-shadow: 0px 5px 10px -5px #000;
text-align: center;
}
button{
font-size: 40px;
padding: 8px 40px;
background-color: #2196F3;
color: #fff;
border: none;
border-radius: 3px;
cursor: pointer;
transition: 0.1s;
}
button:active{
transform: scale(0.9);
}
.output{
font-size: 30px;
font-weight: bold;
margin-top: 10px;
height: 20px;
}
JavaScript
let button = document.querySelector(".button");
let output = document.querySelector(".output");
button.onmousedown = function () {
let plus_button_hold = setTimeout(() => {
output.innerHTML = "Button is pressed";
}, 2000);
button.onmouseup = function () {
clearTimeout(plus_button_hold);
output.innerHTML = "";
}
button.onmouseleave = function () {
clearTimeout(plus_button_hold);
output.innerHTML = "";
}
}
Output:
That's how you can successfully implement button hold detection using JavaScript! If you have any questions or suggestions, please feel free to leave a comment in the comment section below.
Thanks for reading.
You may like:
- How to rotate a button border on hover using HTML and CSS.
- How to change the button text using JavaScript.
- How to slide text in button using JavaScript.
- How to change background color on click using JavaScript.
- How to create a toggle button using HTML & CSS.
Share your thoughts.