JQuery mousedown() function example

JQuery mousedown() function is used to bind an event handler to the "mousedown" JavaScript event or trigger that event on an element.

Syntax

$(selector).mousedown( handler )
handler - A function to execute each time the event is triggered.
$(selector).mousedown( [eventData ], handler )
eventData - An object containing data that will be passed to the event handler.
This method is a shortcut for .on( "mousedown", handler) in the first variation, and .trigger( "mousedown" ) in the second.
The mousedown event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed. Any HTML element can receive this event.

Examples

Example 1

Show texts when mouseup and mousedown event triggering.
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>mousedown demo</title>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <p>Press mouse and release here.</p>

    <script>
        $("p")
            .mouseup(function() {
                $(this).append("<span style='color:#f00;'>Mouse up.</span>");
            })
            .mousedown(function() {
                $(this).append("<span style='color:#00f;'>Mouse down.</span>");
            });
    </script>

</body>

</html>
Output:
Press mouse and release here.
Try it Yourself - Copy paste code in Online HTML Editor to see the result

Example 2

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#p1").mousedown(function() {
                alert("Mouse down over p1!");
            });
        });
    </script>
</head>

<body>

    <p id="p1">This is a paragraph.</p>

</body>

</html>
Output:
This is a paragraph.
Try it Yourself - Copy paste code in Online HTML Editor to see the result

References

Comments