MouseDown Event
The mousedown event is triggered when a pointing device button (such as a mouse button) is initially pressed down over an element. It does not handles release of the button.
Syntax:
<!-- First way to implement -->
<HTMLElement onclick = "function(){}"></HTMLElement>
<!-- Second way to implement -->
selectedElement.addEventListener('click', callbackFunction(){})
Example: The below code example implements the mousedown event in JavaScript .
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
Mouse Down Event Example
</title>
<style>
.button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<button id="myButton" class="button">
Click Me
</button>
<script>
const button =
document.getElementById("myButton");
button.addEventListener("mousedown",
function (event) {
alert
("Mouse button pressed down over the button!");
});
</script>
</body>
</html>
Output:
Difference Between the Click & Mousedown Events
The mousedown and the click event in JavaScript occur when the mouse button is pressed. But the click event handles the button press as well as the button release while mousedown only handles the button click. Some of the important differences between them are listed below.
Contact Us