user5594819
user5594819

Reputation:

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>

Upvotes: 3

Views: 2992

Answers (3)

Hashem Qolami
Hashem Qolami

Reputation: 99464

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.

Upvotes: 2

Max Kroshka
Max Kroshka

Reputation: 487

Your code works as it is. Are you trying to drag or expand the box? I only added styles to it.

.hold {
  width: 50px;
  height: 50px;
  background-color: yellow;
}

.box {
  width: 100px;
  background-color: black;
}

Here is fiddle with your code: jsfiddle

Upvotes: 0

reza
reza

Reputation: 1507

try the following

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

jsfiddle link https://jsfiddle.net/w47anse9/

Upvotes: 0

Related Questions