I want to capture the event when my drop action fails, either because the user did not drop at the right location or may be he himself has cancelled it by hitting 'Esc' key.
Take a look at this script. Took me some time to write and finish it. => DEMO
If this is what you want, let me know.
Note: => this code isn't compatible with legacy (browsers that don't have HTML5 support) browsers (e.g. IE8 etc)
First, we define our draggable element by setting its draggable attribute to true
<div id="draggable" draggable="true"> Drag this div </div>
Then we define our dropzone (target:where the element should be dropped on)
<div class="dropzone" id="dropzone">Dropzone</div>
We need to get the coordinates of the mouse when the element is being released, so we know if the mouse was released on the dropzone or not (I've put an alert notification showing whether the dragend event occurred on the dropzone. If on the dropzone than it will alert dropped on the dropzone, else it will alert dropped not on the dropzone)
function cords(event)
We also need to get the coordinates of the dropzone element, so we will be able to find where the drop event (successful or not (*manually cancelled (Esc) or dropped on the wrong place)) occurred.
var elTop = dragZone.getBoundingClientRect().top + getDocTopLeftPos().fT;
var elLeft = dragZone.getBoundingClientRect().left;
var elBottom = elTop + parseInt(getElProps(dragZone,'height'));
var elRight = elLeft + parseInt(getElProps(dragZone,'width'));
We will know whether the drag operation was successful or not via (on)dragend event
HTML
<div id="draggable" draggable="true">
Drag this div
</div>
<div class="dropzone" id="dropzone">Dropzone</div>
CSS
#draggable {
width: 200px;
height: 50px;
text-align: center;
background: red;
margin-bottom:50px;
}
.dropzone {
width: 200px;
height: 200px;
background: brown;
margin-bottom: 10px;
padding: 10px;
text-align:center
}
Javascript
//checking if the browser is Internet Explorer
var isIEX = navigator.userAgent.match(/Trident/);
var doc = isIEX ? document.documentElement : document.body;
function getDocTopLeftPos() {
scrollTop = window.pageYOffset || doc.scrollTop;
scrollLeft = window.pageXOffset || doc.scrollLeft;
clientTop = doc.clientTop || 0;
clientLeft = doc.clientLeft || 0;
fromTop = Math.round(scrollTop - clientTop);
fromLeft = Math.round(scrollLeft - clientLeft);
return {fT:fromTop, fL:fromLeft}
}
//get the value of the property of the specified element
function getElProps(el,attr){
whaT_ = isIEX ? el.currentStyle : window.getComputedStyle(el);
getWhaT_ = isIEX ? whaT_.getAttribute(attr) : whaT_.getPropertyValue(attr);
return getWhaT_;
}
//getting the coordinates of the mouse
function cords(ev) {
if (ev.pageX == null && ev.clientX != null ) {
var html = document.documentElement;
var body = document.body;
ev.pageX = ev.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0)
ev.pageY = ev.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0)
}
return {x:ev.pageX,y:ev.pageY}
}
var x,y;
var dragZone = document.getElementById("dropzone");
//getting our element's coordinates
//the mouse should be between these coordinates, otherwise that wouldn't be the dropzone
//from top
var elTop = dragZone.getBoundingClientRect().top + getDocTopLeftPos().fT;
//from left
var elLeft = dragZone.getBoundingClientRect().left;
//the height of the draggable element + its top coordinate
var elBottom = elTop + parseInt(getElProps(dragZone,'height'));
//the width of the draggable element + its left coordinate
var elRight = elLeft + parseInt(getElProps(dragZone,'width'));
var dragElement;
document.getElementById("draggable").addEventListener("dragstart",function(event){
evt = event || window.event;
if(navigator.userAgent.match(/Firefox/)) event.dataTransfer.setData('text/plain',null)
},false);
document.addEventListener("dragstart",function(event){
evt = event || window.event;
//the element that is being dragged
dragElement = evt.target || evt.srcElement
//make our target half transparent;
dragElement.style.opacity = 0.5;
},false);
document.addEventListener("dragend",function(event){
console.log(x + ' ' + y + ' ' + elTop + ' ' + elLeft + ' ' + elBottom + ' ' + elRight);
//if the dragged element was dropped at the right place
if(x>elLeft && x<elRight && y>elTop && y<elBottom){
alert('dropped on the dropzone');
}else{
//if the destination was wrong or the drag was cancelled (Esc)
alert('dropped not on the dropzone')
}
//reset our element's transparency
dragElement.style.opacity = 1;
dragZone.style.background = "brown";
},false);
document.addEventListener("dragover",function(event){
evt = event || window.event;
x = cords(evt).x;
y = cords(evt).y;
console.log(x + ' ' + y);
//this will prevent browser's default behaviour which will allow the drop event to occur
if(evt.preventDefault) evt.preventDefault() ; else return false;
},false);
document.addEventListener("dragenter",function(event){
evt = event || window.event;
dropTarget = evt.target || evt.srcElement;
//this will highlight potential drop target when the draggable element enters it
if(dropTarget.className == "dropzone" ){
dropTarget.style.background = "purple";
}
}, false);
document.addEventListener("drop",function(event){
evt = event || window.event;
if(evt.preventDefault) evt.preventDefault() ; else return false;
}, false);
Related
I'm defining a class Session that is created for every new session.
In window.onload, the Session object has a mouse click event listener , on click, it fires the handler and 1. checks if anchor tag was clicked and saves href 2. saves the x and y of mouse click.
The problem: The function user.onclick is not working. Doesn't call the anchorLinkClickHandler(); OR window.addEventListener i.e. the click event handler that saves x and y. NO ERRORS. I think there is a syntactical issue with the below code.. don't know what. Ideas?
As shown (in window.onload):
var user = new UserSession('001');
user.onclick = function(event) {
// check if an anchor tag link is clicked, if so, save the href.
user.aTagHref = anchorLinkClickHandler();
// CLICK event listener - save the x and y of mouse click
window.addEventListener("load", function(event){
document.body.addEventListener("click", handleClick)
});
}
Here is the full code:
function UserSession(campaignId) {
this.campaignId = campaignId;
var aTagHref = aTagHref;
this.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
};
// get the position of click - Event Listener Function
this.getPosition = function(el) {
var xPosition = 0;
var yPosition = 0;
while (el) {
if (el.nodeName == "BODY") {
// deal with browser quirks with body/window/document and page scroll
var xScrollPos = el.scrollLeft || document.documentElement.scrollLeft;
var yScrollPos = el.scrollTop || document.documentElement.scrollTop;
xPosition += (el.offsetLeft - xScrollPos + el.clientLeft);
yPosition += (el.offsetTop - yScrollPos + el.clientTop);
} else {
xPosition += (el.offsetLeft - el.scrollLeft + el.clientLeft);
yPosition += (el.offsetTop - el.scrollTop + el.clientTop)
}
el = el.offsetParent;
}
return {
x: xPosition,
y: yPosition,
a: "hahah",
};
};
// On click handler
this.handleClick = function(event) {
// Return the current element clicked on
var el = event.currentTarget;
// Return the offset values of the element clicked on
var relOffsetValues = getPosition(el);
// Find the true value of x and y by adding the offset and the to clicked value of x and y
var realValueX = (relOffsetValues.x + event.clientX );
var realValueY = (relOffsetValues.y + event.clientY);
// display the x and y of the mouse click
alert("Clicks x:" + realValueX + ", y:" + realValueY);
// alert("clientx:" + event.clientX + ", real valie:" + realValueX);
}
// On click ANCHOR TAGS SAVE THEM
// Anchor Tags - Capture the href of the link clicked
this.anchorLinkClickHandler = function() {
var aTags = document.getElementsByTagName('a');
for (var i = aTags.length - 1; i >= 0; --i) {
aTags[i].onclick = function() {
aTagHref[i] = this.getAttribute("href");
alert(aTagHref);
};
}
}
// END OF CLASS
}
Window.onload function (where everything is called)
window.onload = function() {
var user = new UserSession('001');
user.onclick = function(event) {
// check if an anchor tag link is clicked, if so, save the href.
user.aTagHref = anchorLinkClickHandler();
// CLICK event listener - save the x and y of mouse click
window.addEventListener("load", function(event){
document.body.addEventListener("click", handleClick)
});
}
// SCROLL Event Listener
// Get the x and y of the scroll
window.addEventListener("scroll", function(event) {
// document.getScroll= function(){
var sx, sy;
if(window.pageYOffset!= undefined){
sx = pageXOffset;
sy = pageYOffset;
console.log(sx +" if " + sy);
// return [pageXOffset, pageYOffset];
}
else{
var d= document, r= d.documentElement, b= d.body;
sx= r.scrollLeft || b.scrollLeft || 0;
sy= r.scrollTop || b.scrollTop || 0;
console.log(sx +" else " + sy);
// return [sx, sy];
}
// }
});
};
Take a look at https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick to better understand.
The click event is raised when the user clicks on an element. The click event will occur after the mousedown and mouseup events.
You will have to create a HTML element first and when that element is clicked you have to execute a function that does all the actions you want.
HTML:
<button id="btn">Click me</button>
JavaScript:
document.querySelector("#btn").onclick = function(event) {
// do things here
}
I have an object with the name "element". If somebody touches the tablet, I would like to return the x and y coordinates of the touch position relative to the object, i. e. the upper left corner of the object has the coordinates x=0 and y=0.
I know how to implement this on desktops:
$(function() {
$(document).mousedown(function(e) {
var offset = $("#element").offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
alert(relativeX+':'+relativeY);
$(".position").val("afaf");
});
});
So the word "mousedown" should be replaced by "touchstart", I guess. However, it still doesn't work.
How do I change the above code such that it works on tablets with "touchstart" instead of "mousedown"?
UPDATE: See Daniel Lavedonio de Lima's answer below
You have to explicitly pull a touches object out of the event, it doesn't contain the coordinates directly. Look at line two of the code below.
Here is the code I always use to get touch/pointer coordinates:
if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
x = touch.pageX;
y = touch.pageY;
} else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
x = e.clientX;
y = e.clientY;
}
Put this inside an event listener that listens for any or all of those events and add your offset calculation and this should work.
Christopher Reid's answer almost worked for me, but I had to make a few ajustments because originalEvent property was not part of the event when I was testing in Google Chrome version 81.0.4044.138 and Mozila Firefox version 76.0.1.
Since I found some answers that use directly the event and other that uses event.originalEvent property, I added a check to use the first if the latter is undefined.
So instead of:
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
I used:
var evt = (typeof e.originalEvent === 'undefined') ? e : e.originalEvent;
var touch = evt.touches[0] || evt.changedTouches[0];
So the full answer then becomes:
if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
var evt = (typeof e.originalEvent === 'undefined') ? e : e.originalEvent;
var touch = evt.touches[0] || evt.changedTouches[0];
x = touch.pageX;
y = touch.pageY;
} else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
x = e.clientX;
y = e.clientY;
}
Normally you would use e.g. e.touches[0].clientX to handle touch events
A non jquery solution, Assuming you have the following HTML
<div id="touchme" style="width: 200px; height: 200px; background: blue;">
And script
document.getElementById("touchme").addEventListener("touchstart",
function clicked(e) {
var br = document.getElementById("touchme").getBoundingClientRect();
// x & y are relative to the clicked element
var x = e.touches[0].clientX - br.left;
var y = e.touches[0].clientY - br.top;
console.log("x: " + x + " y: " + y);
});
Note the following script handles only the first (of all the possible) touch input
Try this:
$(function(){
$('body').on('touchstart', function(e) {
var offset = $("#element").offset();
var t = e.targetTouches.length > 0 ? e.targetTouches.item(0) : e.touches.item(0);
var relativeX = t.pageX - offset.left;
var relativeY = t.pageY - offset.top;
console.log(relativeX+':'+relativeY);
$(".position").val("afaf");
});
});
PointerEvent supports mouse and touch both.
For example, let's see Sortable.js.
Bind events #L423
el.addEventListener('pointerdown', handler);
Get coords #L574
let touch = (evt.touches && evt.touches[0]) || (evt.pointerType && evt.pointerType === 'touch' && evt);
let clientX = (touch || evt).clientX;
let clientY = (touch || evt).clientY;
I adapted the Domenico solution to move the camera on pc and mobile for threeJS without orbitcontrols:
window.addEventListener("touchmove", function clicked(e) {
cursor.x = e.touches[0].clientX / sizes.width - 0.5
cursor.y = -(e.touches[0].clientY / sizes.height - 0.5)});
In case you have some built-in scroll, you should do it as follows:
const rect = event.target.getBoundingClientRect();
x = event.targetTouches[0].pageX - (rect.left + document.documentElement.scrollLeft);
y = event.targetTouches[0].pageY - (rect.top + document.documentElement.scrollTop);
i'm developing a canvas-based timeline.
I want to trigger the onClick event to get informations about the clicked element.
canvas.onclick = function(e){
var evt = e || event;
var x = evt.offsetX;
var y = evt.offsetY;
for(var i=0;i<items_loaded.length;i++){
var item = items_loaded[i];
alert(x + ' | ' + y);
if((x > item['x_start'] && x < item['x_end']) && (y > item['y_start'] && y < item['y_end'])){
alert('Trovata fermata con ID: ' + item['id']);
}
}
}
I checked the code and the event seems to not fire right.
I have a javascript code, using which an iframe moves with mouse pointer.
and when I slide mouse over another iframe (e.x youtube embed video), the iframe doesn't move with mouse while mouse pointer is on youtube video.
what can be done? thanks
<script type="text/javascript">
var opacity = 1;
var time = 3500000;
if (document.cookie.indexOf('visited=true') == -1) {
(function openColorBox() {
if ((document.getElementById) && window.addEventListener || window.attachEvent) {
var hairCol = "#ff0000";
var d = document;
var my = -10;
var mx = -10;
var r;
var vert = "";
var idx = document.getElementsByTagName('div').length;
var thehairs = "<iframe id='theiframe' scrolling='no' frameBorder='0' allowTransparency='true' src='b.html' style='margin: px 0px 0px px; position:fixed;width:200px;height:200px;overflow:hidden;border:0;opacity:" + opacity + ";filter:alpha(opacity=" + opacity * 100 + ");'></iframe>";
document.write(thehairs);
var like = document.getElementById("theiframe");
document.getElementsByTagName('body')[0].appendChild(like);
var pix = "px";
var domWw = (typeof window.innerWidth == "number");
var domSy = (typeof window.pageYOffset == "number");
if (domWw) r = window;
else {
if (d.documentElement && typeof d.documentElement.clientWidth == "number" && d.documentElement.clientWidth != 0) r = d.documentElement;
else {
if (d.body && typeof d.body.clientWidth == "number") r = d.body
}
}
if (time != 0) {
setTimeout(function() {
document.getElementsByTagName('body')[0].removeChild(like);
if (window.addEventListener) {
document.removeEventListener("mousemove", mouse, false)
} else if (window.attachEvent) {
document.detachEvent("onmousemove", mouse)
}
}, time)
}
function scrl(yx) {
var y, x;
if (domSy) {
y = r.pageYOffset;
x = r.pageXOffset
} else {
y = r.scrollTop;
x = r.scrollLeft
}
return (yx == 0) ? y : x
}
function mouse(e) {
var msy = (domSy) ? window.pageYOffset : 0;
if (!e) e = window.event;
if (typeof e.pageY == 'number') {
my = e.pageY - 0 - msy;
mx = e.pageX - 0
} else {
my = e.clientY - 6 - msy;
mx = e.clientX - 6
}
vert.top = my + scrl(0) + pix;
vert.left = mx + pix
}
function ani() {
vert.top = my + scrl(0) + pix;
setTimeout(ani, 300)
}
function init() {
vert = document.getElementById("theiframe").style;
ani()
}
if (window.addEventListener) {
window.addEventListener("load", init, false);
document.addEventListener("mousemove", mouse, false)
} else if (window.attachEvent) {
window.attachEvent("onload", init);
document.attachEvent("onmousemove", mouse)
}
}
})();
var oneDay = 1000 * 60 * 30;
var expires = new Date((new Date()).valueOf() + oneDay);
document.cookie = "visited=true;expires=" + expires.toUTCString()
}
</script>
<iframe width="420" height="315" src="https://www.youtube.com/embed/sTesehdHbqs" style="display:block; position:static;"frameborder="0" allowfullscreen></iframe>
Without seeing your HTML, the best guess is: you're not going to be able to do this. The issue is that, once you move your mouse into an iframe that has an origin different from your page, mouse events will not fire out to your script, and therefore you won't be able to update the position of your iframe. DEMO: Note how the mouse coordinates stop updating once you move your mouse pointer inside the iframe.
function mouseMoveListener() {
var outputX = document.querySelector('#mouseX');
var outputY = document.querySelector('#mouseY');
return function(ev) {
outputX.innerText = ev.clientX;
outputY.innerText = ev.clientY;
};
}
function test(ev) {console.log('ev::', ev.clientX);}
document.addEventListener('mousemove', mouseMoveListener());
<div>Mouse position:
<span id="mouseX"></span>
,
<span id="mouseY"></span>
</div>
<iframe src="http://www.example.com" width="200" height="200"></iframe>
If you don't need to let your users interact with the content of the iframe, you can cheat this by overlaying a transparent div on top of the iframe. That prevents mouse events from "falling through" to the iframe beneath them, while still showing the content of the iframe. DEMO: But note that the iframe doesn't allow you to scroll, since mouse events (like clicks on the scroll bar or wheel events) are captured by the overlay div.
function mouseMoveListener() {
var outputX = document.querySelector('#mouseX');
var outputY = document.querySelector('#mouseY');
return function(ev) {
outputX.innerText = ev.clientX;
outputY.innerText = ev.clientY;
};
}
function test(ev) {console.log('ev::', ev.clientX);}
document.addEventListener('mousemove', mouseMoveListener());
#iframe-wrapper {
position: relative;
}
#iframe-wrapper iframe {
position: relative;
z-index: 0;
}
#iframe-wrapper .overlay {
position: absolute;
background: transparent;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 2;
}
<div>Mouse position:
<span id="mouseX"></span>
,
<span id="mouseY"></span>
</div>
<div id="iframe-wrapper">
<iframe src="http://www.example.com" width="200" height="200"></iframe>
<div class="overlay"></div>
</div>
However, if you're displaying a YouTube video, it's unlikely this will satisfy your requirements, since user interaction is a key part of the viewing experience.
Hi I am trying to make drag drop feature in JS, It works fine in Firefox, but it doesn't work on chrome. I Think it is something to do with Event Deligation, I am attaching the link of my code base. Following are the steps to reproduce the problem:
Create a new Task
Drag it to another column
Now click on Edit or Delete Icon(E and D in circle).
Following are the Code highlights(Code is a bit bigger You can check it on Codepen):
JS:
$(function(){
function init(){
var mouseX = 0, // Mouse Position
mouseY = 0,
elmX = 0, // Element Position
elmY = 0,
pillers = $('.pillers'), // Task Container
pillerWidth = $('.pillers:nth-child(1)').width(), // Taks Container width
currentElm; // Current Element
/* When Left Mouse Button is Pressed */
$('.dragable').on('mousedown', function(e){
var temp;
$(this).addClass('rel');
mouseX = e.clientX; // Current Mouse Position and Store it to global variables
mouseY = e.clientY;
temp = +($(this).css('left').slice(0, -2)); // Get Element Position and if it not a number then change it to 0
elmX = null || isNaN(temp) ? 0 : temp;
temp = +($(this).css('top').slice(0, -2));
elmY = null || isNaN(temp) ? 0 : temp;
$(this).css({'z-index':'9999'}); // Increase the Z-Index of the Element so that it wont be overlapped by other element.
currentElm = $(this); // set the current value so that it could be use by mouse move
/* Some Hack for not let heighlight the data(Copied from net) */
document.body.focus();
document.onselectstart = function () { return false; };
$(this).ondragstart = function() { return false; };
return false;
}).on('mouseup',function(e){ // This will be fired when Mouse Button release back
if(currentElm !== null){
currentElm.removeClass('rel').prependTo('.arrived .tasks').css({ // Resetting the Position Object
left: 0,
top: 0
});
currentElm.css({'z-index' : '1'}); // Set Z-Index back to normal value.
currentElm = null; // Finally Set the Current Element to null so that it won't get dragged any more
}
}).on("mousemove", function(e){ // Mouse Move Event .. This is the main part, It will reposition the element with mouse pointer
if(currentElm !== undefined && currentElm !== null){
currentElm.addClass('draged').css({ // This sets the position of div element
left : (elmX + e.clientX - mouseX)+'px',
top : (elmY + e.clientY - mouseY)+'px'
});
/* Set Appropriate Class to Piller to Which The Element is going to be added */
if( e.clientX >= $('.pillers:nth-child(1)').offset().left && e.clientX < ($('.pillers:nth-child(1)').offset().left+pillerWidth) && e.clientY < $('.pillers:nth-child(1)').outerHeight()){
$('.pillers:nth-child(1)').addClass('arrived').siblings('.pillers').removeClass('arrived');
}else if(e.clientX >= $('.pillers:nth-child(2)').offset().left && e.clientX < ($('.pillers:nth-child(2)').offset().left+pillerWidth) && e.clientY < $('.pillers:nth-child(2)').outerHeight()){
$('.pillers:nth-child(2)').addClass('arrived').siblings('.pillers').removeClass('arrived');
}else if(e.clientX >= $('.pillers:nth-child(3)').offset().left && e.clientX < ($('.pillers:nth-child(3)').offset().left+pillerWidth) && e.clientY < $('.pillers:nth-child(3)').outerHeight()){
$('.pillers:nth-child(3)').addClass('arrived').siblings('.pillers').removeClass('arrived');
}else if(e.clientX >= $('.pillers:nth-child(4)').offset().left && e.clientX < ($('.pillers:nth-child(4)').offset().left+pillerWidth) && e.clientY < $('.pillers:nth-child(4)').outerHeight()){
$('.pillers:nth-child(4)').addClass('arrived').siblings('.pillers').removeClass('arrived');
}
}
});
$('a.remove').on('click',function(){
console.log('hey')
$(this).parents('.dragable').remove();
});
$('.add_task_button').on('click',function () {
var place= $(this).closest('.create_task_box'),
titl=place.find('input#title').val(),
disc=place.find('textarea#discription').val(),
time = new Date(),
format = time.toLocaleDateString();
if(titl || disc){
var val = $('.temp').clone(true).removeClass('temp hide').insertBefore(place);
val.find('#TaskHeading').val(titl).end().find('#task-discription').text(disc).end().find('.time').text(format).css({
left: 0,
top: 0
});
}
$('input#title, textarea#discription').val('');
});
$(document).on("click", ".edit", function(){
e.stopPropagation();
if($(this).is('.done')){
$(this).removeClass('done');
$(this).closest('.task-unit').addClass('dragable').find('input, textarea').attr('readonly', 'readonly').addClass('readonly');
}else{
$(this).addClass('done');
var task = $(this).closest('.dragable');
task.removeClass('dragable').find('input, textarea').removeAttr('readonly').removeClass('readonly');
}
});
}
init();
});
I am not mentioning the HTML and CSS part here because it will take a lot of space.. You can see full code Here on Codepen.
Let me know if anything else required.
The problem is, you have an object (parent) with a mousedown event and inside it, another object (children) with a click event. It seems that in Chrome, the first event (mousedown) is capturing the click over the buttons.
As a workaround, you can do this:
have a function for the mousedown event on the parent element.
unbind the mousedown event when the user does a mouseover event on the children.
bind again the function to the parent when the user does a mouseout off the parent.
As an example:
$(".theparent").on("mousedown",function(){
doThings();
});
$(".thechildren").on("click",function(){
alert("Child");
});
$(".thechildren").on("mouseover",function(){
$(this).closest(".theparent").off("mousedown");
console.log("Off");
});
$(".thechildren").on("mouseout",function(){
$(this).closest(".theparent").on("mousedown",doThings);
console.log("on");
});
function doThings(){
alert("Parent");
}
.theparent{
width:200px;
height:100px;
background-color:#3a3a3a;
position:absolute;
}
.thechildren{
position:relative;
background-color:#FF0000;
width:50px;
height:50px;
cursor:pointer;
left:50px;
top:25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="theparent">
<div class="thechildren">Child</div>
</div>
See it working on fiddle.