We can use the jQuery mouseup method to run a function when a user clicks their mouse and then releases it. To do this we can add a function call to the mouseup() method.

$("#div1").mouseup(function() {
  //The user has clicked their mouse and released it in #div1
});

Another way this can be done is to use the .on() method:

$("#div1").on("mouseup", function() {
  //The user has clicked their mouse and released it in #div1
});

We will stick with the first method as we find it to be easier to read.

The jQuery mouseup() method is very similar to the mousedown() method, the main difference being that the mousedown() method will trigger when you click DOWN on the mouse, while the mouseup() method will only trigger AFTER you click AND release the mouse. We will show this in the example below.

An Example of Using the jQuery mouseup Method

In this example, we will have 2 divs set up next to each other. Both divs will be empty. We will add some CSS to float the divs next to each other and display the text in the center.

Here is the HTML setup:



jQuery mouseup - Click AND release the mouse
jQuery mousedown - Click down on the mouse

When the user moves their mouse into each div and clicks, we will generate a random color and then change the background color of the div.

In the first div, we will be showing how the jQuery mouseup() works. In the second div, we will show how the mousedown() method works.

Here is the JavaScript code:

//This function below will generate a random color
function genRandomColor() {
  var letters = '0123456789ABCDEF';
  var randomColor = '#';
  for (var i = 0; i < 6; i++) {
    randomColor += letters[Math.floor(Math.random() * 16)];
  }
  return randomColor;
}
$("#div1").mouseup(function() {
  $('#div1').css("background-color", genRandomColor());
});
$("#div2").mousedown(function() {
  $('#div2').css("background-color", genRandomColor());
});

The final code and output for this example of using the jQuery mouseup() method is below:

Code Output:

jQuery mouseup - Click AND release the mouse
jQuery mousedown - Click down on the mouse

Full Code:



jQuery mouseup - Click AND release the mouse
jQuery mousedown - Click down on the mouse

Hopefully this article has been useful to help you understand how to use the jQuery mouseup method.

Categorized in:

jQuery,

Last Update: February 26, 2024