On a regular click of the child div
, the following code will print the ID of that specific child div
that was clicked.
<div id="parent">
<div id="A" class="child"></div>
<div id="B" class="child"></div>
</div>
<script>
$("#parent").on('click', event => {
$(event.target).text(event.target.id)
})
</script>
However, if you click on one child div
and drag/release in the other child div
then it will print the ID of the parent element.
This does not occur when the click handler is assigned to the children.
$(".child").on('click', event => {
$(event.target).text(event.target.id)
})
Why is the drag action causing the event target to be the parent element in the first example?
http://jsfiddle.net/thz1esfc/
Clarification on why not duplicate of What is event bubbling and capturing?:
I understand event bubbling and capturing is relevant to "why" but just stating that it is event bubbling or capturing does not explain the scenario. It does not explain why mousedown on child element A and mouseup from child element B would cause the parent element to be the event.target
instead of child element A where the click started or child element B where the click is released.
These two seem to try to explain the results but I would like some documentation showing this behavior if possible.
Technically, browser register the CLICK on the parent b/c neither 1st or 2nd does not register complete CLICK (meaning mousedown and mouseup)
It's up to the browser to handle that behavior. On Firefox at least, the click event is lost when you click in one box, and drag to a different box and release.
The ondragover event occurs when a draggable element or text selection is being dragged over a valid drop target. By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.
By a adding an onClick function for the child modal (content div) mouse click events are prevented to reach the 'closeLogin' function of the parent element.
This is happening to you because a click event is technically fired on release of the click and not on the actual click itself. See: https://developer.mozilla.org/en-US/docs/Web/Events/click
You can do mousedown
and it will have a more accurate effect:
$("#parent").on('mousedown', event => {
$('#message').text(event.target.id)
})
#parent {
width: 300px;
height: 300px;
background-color: cyan;
}
.child {
height: 100px;
width: 100px;
background-color: grey;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div id="1" class="child">
</div>
<div id="2" class="child">
</div>
</div>
<p id="message">
</p>
EDIT: comments are asking why when you click and drag to the next child to shows "parent" - this is event bubbling. You'd need to use event.stopPropagation()
to stop that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With