How to Detect Mouse Button Release with jQuery mouseup

This article provides a practical guide on how to detect when a user releases a mouse button on a webpage using the jQuery mouseup() method. You will learn the basic syntax, see code examples for standard implementation, and discover how to identify which specific mouse button (left, middle, or right) was released.

Understanding the jQuery mouseup() Method

The mouseup event fires when a mouse button is released while the cursor is positioned over a target DOM element. In jQuery, you can attach an event handler to this action using the .mouseup() method or the modern .on("mouseup", handler) syntax.

Basic Syntax and Example

To attach a release event to an element, select the element using jQuery and pass a callback function to .mouseup().

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jQuery mouseup Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

  <button id="action-btn">Click and Release Me</button>
  <p id="status-text">Waiting for action...</p>

  <script>
    $(document).ready(function() {
      $("#action-btn").mouseup(function() {
        $("#status-text").text("Mouse button was released!");
      });
    });
  </script>

</body>
</html>

Alternatively, you can use the .on() method, which is the recommended practice in modern jQuery for binding events:

$("#action-btn").on("mouseup", function() {
  console.log("Mouse button released.");
});

Detecting Which Button Was Released

By passing the event object into the callback function, you can determine which specific mouse button was released using the event.which property.

  • 1: Left mouse button
  • 2: Middle mouse button (scroll wheel click)
  • 3: Right mouse button
$("#action-btn").on("mouseup", function(event) {
  switch (event.which) {
    case 1:
      console.log("Left mouse button released.");
      break;
    case 2:
      console.log("Middle mouse button released.");
      break;
    case 3:
      console.log("Right mouse button released.");
      break;
    default:
      console.log("Unknown mouse button.");
      break;
  }
});

mouseup() vs. click()

While click() requires both a mousedown and a mouseup to occur sequentially on the same element, mouseup() triggers immediately upon the release of the button regardless of where the initial press occurred, provided the release happens within the targeted element. This makes mouseup() essential for drag-and-drop mechanics, drawing applications, and custom UI components that require precise mouse tracking.