HTML onmousedown Event Attribute

Description

The onmousedown HTML event attribute specifies a JavaScript function to be called when the mouse button is pressed down on the element.

The onmousedown event is fired before the onclick event. This means that if the user presses and releases the mouse button quickly, only the onmousedown event will be fired. However, if the user holds down the mouse button for a while, both the onmousedown and onclick events will be fired.

The onmousedown event can be used to implement a variety of features on a web page, such as:

  • Dragging and dropping elements
  • Playing a sound effect when a button is clicked
  • Changing the cursor style when the user hovers over an element
  • Displaying a tooltip when the user hovers over an element

Here is an example of how to use the onmousedown event attribute:

<button onmousedown="myFunction()">Click Me!</button>

The myFunction() function will be called whenever the user presses and releases the mouse button on the button.

To prevent the default behavior of the onmousedown event, you can call the preventDefault() method on the event object. This can be useful if you want to implement your own custom behavior for the event.

Here is an example of how to prevent the default behavior of the onmousedown event:

<button onmousedown="event.preventDefault(); myFunction()">Click Me!</button>

The event.preventDefault() method will prevent the default behavior of the onmousedown event, which is to focus the element that the event was fired on.

Syntax

<element onmousedown="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html> 
<html>
<head>
<title>onmousedown and onmouseup event</title>
<style>
div {
width: 100px;
height: 50px;
border: 1px solid black;
color: black;
text-align: center;
}
</style>
</head>
<body>
<p>Click on an element to demonstrate the script:</p>
<div id="code" onmousedown="mouseDown()" onmouseup="mouseUp()">&spades; &clubs; &hearts; &diams;<br>&diams; &hearts; &clubs; &spades;
</div>
<script>
function mouseDown() {
document.getElementById("code").style.backgroundColor="orange";
}
function mouseUp() {
document.getElementById("code").style.backgroundColor="purple";
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onmousedown Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 13th October 2023