In this tutorial we will see how to create Simple Click and Hold Effect Using JavaScript. For this we have used the onmouseup and onmousedown events with .className property and getElementById() method.
Table of Contents
HTML Code
HTML Code is given below, This code contains HTML Button with onmouseup and onmousedown events. These events will execute JavaScript functions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Click and Hold Effect Using JavaScript</title>
</head>
<body>
<button onmouseup="mouseUp()" onmousedown="mouseDown()" id='btn'>Click Me</button>
</body>
</html>
onmousedown event
The onmousedown event occurs when mouse button is pressed over HTML element. In this example onmousedown event will execute a JavaScript function as soon as mouse button is pressed over HTML Button.
onmouseup event
The onmouseup event occurs when mouse button is released over HTML element. In this example onmouseup event will execute a JavaScript function as soon as mouse button is released over HTML Button.
CSS Code
CSS Code is given below, in this code we have used two CSS classes to change the padding of button in a specific duration of time to create the click and hold effect.
#btn {
padding: 10px 20px;
background-color: #22438C;
color: #fff;
}
.hold {
padding: 100px 200px !important;
transition-duration: 3s;
}
.release {
padding: 10px 20px !important;
transition-duration: 1s;
}
JavaScript Code
Take a look at the JavaScript code, this code is further explained below.
<script>
function mouseDown()
{
document.getElementById("btn").className = "hold";
}
function mouseUp()
{
document.getElementById("btn").className = "release";
}
</script>
Demo
getElementById() method
getElementById() method is used to target or select the HTML element. In this example it is used to target button element to change it's class name.
.className property
The .className property is used to set or return the class name of the selected HTML element. In this example the .className property will set the class of html button to "hold", as soon as mouse button is clicked over it.
While class of button is set to "release" as soon as the mouse click is released.
This will create Click and Hold effect which is very simple to understand.
Video Tutorial
Watch video tutorial on how to create Simple Click and Hold Effect Using JavaScript.