VOLK 14 VOLK 14 - 7 months ago 50
HTML Question

jQuery mouseup event on click and drag

I'm trying to show a

div
when the user click a box. I tried to use this code:

$(document).ready(function(){
$(".hold").mousedown(function(){
$(".box").css("height","200px");
});
$(".hold").mouseup(function(){
$(".box").css("height","0px");
});
});


But the second part of the code, the
mouseup
event doesn't trigger the callback when I click and drag.

How to make it work?

<!DOCTYPE html>
<html>
<head>
<title>click and hold project</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="hold"></div>
<div class="box"></div>

<script src="jquery-2.2.3.min.js"></script>
<script src="app.js"></script>
</body>
</html>

Answer

As @wahwahwah pointed it out, the issue is that when you press the mouse key on the .hold element and then move the mouse somewhere else and leave the key, the given handler on mouseup would NOT be called because it is set on the .hold element.

Technically, the target of the event would be different in that case, hence it won't match the .hold element and eventually the callback functions of mouseup event won't be triggered.

A workaround to this could be to add a pointer to the clicked element at the beginning and then add an event listener on the document element and check whether the event.target is the same as the clicked element.

If they are not the same, we will trigger the .hold element's event manually, as follows:

$(document).ready(function(){
  var mouseTarget;

  $(".hold").on('mousedown', function(){
    $(".box").css("height", "200px");
    mouseTarget = this;
  })
  .on('mouseup', function(){
    $('.box').css("height", "0px");
  });

  $(document).on('mouseup', function(e) {
    if (e.target !== mouseTarget) {
      $(mouseTarget).trigger(e.type);
    }
  });
});
.hold{
  background-color: #000;
  width: 20%;
  height: 10px;
}
.box{
  background-color: #f00;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hold"></div>
<div class="box"></div>

It is worth mentioning that the callback function which is set on the document will be triggered in the bubble phase.