zvk
zvk

Reputation: 23

JQuery Selector triggering unexpectedly

I have been trying to learn jQuery to expand my abilities, so I tried emulating the jQuery UI ".draggable()" behavior. The spinet shows the problem directly, I don't understand why the .mousedown event is triggering when I click on #Box, how can I get it to only trigger when clicking on #MyBox?

P.S. This is purely for the purpose of understanding jQuery, I have no intention to use this code anywhere.

var down, x, y

$(document).ready(function(){
  $("#Box").draggable()
  $("#MyBox").mousedown(function(event){
    down = true
    var pos = $(this).offset();
    x = event.pageX - pos.left;
    y = event.pageY - pos.top;
  });
  $(document).mouseup(function(event){
    down = false
  })
  $(document).mousemove(function(event){
    $("span").text("X: " + event.pageX + " Y: " + event.pageY);
    if(down) 
    {
      $("#MyBox").offset({left:event.pageX-x, top:event.pageY-y})
    }
  })
});
* {
  background-color: white;
}

#MyBox {
  position: absolute;
  background-color: blue;
  width: 100px;
  height: 100px;
}

#Box {
  left: 250px;
  position: absolute;
  background-color: red;
  width: 100px;
  height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script
  src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"
  integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E="
  crossorigin="anonymous"></script>
  
  
<div class='test'>
  <span>Drag a box</span>
  <div id='MyBox'/>
  <div id='Box'/>
</div>

Upvotes: 2

Views: 41

Answers (1)

saulotoledo
saulotoledo

Reputation: 1972

You did not close properly the boxes divs. Your browser is doing the job for you and interpreting your code in the following way:

<div class='test'>
  <span>Drag a box</span>
  <div id='MyBox'>
    <div id='Box'></div>
  </div>
</div>

Note that Box is inside MyBox. In a simple way, Box is part of MyBox: if you click in Box you are also clicking in MyBox.

The problem however can be easily solved: div tags should be closed with </div> because the list of self closing tags is limited:

<div class='test'>
  <span>Drag a box</span>
  <div id='MyBox'></div>
  <div id='Box'></div>
</div>

There are ways to prevent the event from propagating to parent elements, but in your case you have the issue presented above in your HTML code.

Upvotes: 1

Related Questions