Search code examples
javascriptdom-eventsevent-bubbling

Browser event does not bubble


I want to make the drag drop to the element,and I dot not want the parent of this element capture the click or drag event, so I use the bubble model, however the element which I want to drag contain a child who own the same size (width, height, left...) of this element.

For example:

<div id="div_con" style="left: 20px; top: 50px; width: 181px; height: 357px; position: absolute; z-index: 10; cursor: pointer;" class="drag">
    <img src="test.PNG" id="Over_Label_1912694_Img" style="left: 0px; top: 0px; width: 181px; height: 357px; position: relative;">
</div>

div#div_con is the element I want to drag, but since the div#div_con and the img have the same size, so user can never click the div#div_con. Since the img is above it.

So I bind the mouseDown, mouseMove, mouseUp events to the whole document:

document.onmousedown = OnMouseDown;
document.onmouseup = OnMouseUp;

In my opinion,when user click the img under the div#div_con, the mouseDown event will bubble to div#div_con.

Since I just want to drag the div#div_con,so I make a check in the mouseDown handler:

if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag')
{  //do the start the move}

But it does not work.

This is the complete example:

http://jsfiddle.net/5SCwG/


Solution

  • But it is bubbling. That's why document is receiving the event to begin with. The problem you're experiencing is that event.target refers to the object clicked, and event.currentTarget refers to the object listening and neither one of those are your div.

    You will either need to use an event listener on the div directly, or you'll need to get target.parentElement and then use that as _dragElement.

    Check it out.