See JSFddle
Question: Why will unwrapping the jQuery element and applying an event listener work but when I apply the event listener directly to the jQuery element, it doesn't work? See below...
With the following code I am trying to capture the drag distance from the original position. When the user drags more than 120 pixels from the origin, I will print to console that we are "outside of the boundary".
If I add the listener by unwrapping the jQuery element, it works as expected and fires the call:
$btnItem[0].addEventListener("drag", function (e) { self.handleDrag(e); }, false);
If I add the listener to the actual jQuery element, it doesn't fire the call:
$btnItem.on('drag', e=> self.handleDrag(e));
Any ideas as to why unwrapping the jQuery element works but the actual jQuery method doesn't? It seems that jQuery loses the connection with the mouse location.
HTML:
<div style="padding:100px;">
<span id="dragMe" draggable="true">Drag</span>
</div>
CSS:
#dragMe{
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: 400;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
color: #fff;
background-color: #337ab7;
border-color: #2e6da4;
}
Code:
var oPos = [];
function handleDragStart(e) {
oPos = [e.clientX, e.clientY];
e.target.style.opacity = '0.4'; // this / e.target is the source node.
}
function handleDrag(e) {
var nPos = [e.clientX, e.clientY];
var d = Math.sqrt((oPos[0] - nPos[0]) * (oPos[0] - nPos[0]) + (oPos[1] - nPos[1]) * (oPos[1] - nPos[1]));
if (d > 120) {
console.log('outside of the boundary');
}
}
function handleDragEnd(e) {
e.target.style.opacity = '1.0'; // this / e.target is the source node.
}
function jQueryUnWrap(){
var $btnItem = $("#dragMe");
$btnItem[0].addEventListener("dragstart", function(e) {
handleDragStart(e);
}, false);
$btnItem[0].addEventListener("dragend", function (e) {
handleDragEnd(e);
}, false);
$btnItem[0].addEventListener("drag", function (e) {
handleDrag(e);
}, false);
}
function jQueryWrap(){
var $btnItem = $("#dragMe");
$btnItem.on('dragstart', e=> handleDragStart(e));
$btnItem.on('dragend', e=> handleDragEnd(e));
$btnItem.on('drag', e=> handleDrag(e));
}
$(document).ready(function(){
jQueryUnWrap();
//jQueryWrap();
});
jQuery normalizes the event object to provide an interface that works in all browsers. Unfortunately, this means removing certain properties that aren't supported in all browsers. You can get back to the original event object by accessing the originalEvent
property.
$btnItem.on('dragstart', e=> self.handleDragStart(e.originalEvent));
$btnItem.on('dragend', e=> self.handleDragEnd(e.originalEvent));
$btnItem.on('drag', e=> self.handleDrag(e.originalEvent));