Allow drag and drop only when mouse is over specific element using jQuery UI
I <div>
only want to drag when the mouse is over the first element inside this <div>
. When the mouse is not over this first element, the whole <div>
cannot be dragged. This is my code:
<div id="containers">
<div id="cont1">foo</div>
<div id="cont2">bar</div>
</div>
<script>
$(document).ready(function() {
$("#cont1").mouseenter(function() {
$("#containers").draggable("enable");
});
$("#cont1").mouseleave(function() {
$("#containers").draggable("disable");
});
});
</script>
When the mouse enters or leaves #cont1
, an error appears in the console:
Uncaught TypeError: undefined is not a function(index):27 (anonymous function)jquery-1.11.0.js:4995 jQuery.event.special.(anonymous function).handlejquery-1.11.0.js:4624 jQuery.event.dispatchjquery-1.11.0.js:4292 elemData.handle
+3
source to share
2 answers
You're looking for the handle
drag and drop widget option :
$("#containers").draggable({
handle: "#cont1"
});
#containers {
height: 100px;
background: grey;
}
#cont1 {
width: 50px;
height: 50px;
background: dodgerblue;
}
#cont2 {
width: 50px;
height: 50px;
background: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div id="containers">
<div id="cont1">foo</div>
<div id="cont2">bar</div>
</div>
+2
source to share
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<div id="containers" style="height: 200px;width: 200px;background-color: blanchedalmond">
<div id="cont1">foo</div>
<div id="cont2">bar</div>
</div>
<script>
$(document).ready(function() {
$("#cont1").mouseenter(function() {
$("#containers").draggable({ disabled: false });
});
$("#cont1").mouseleave(function() {
$("#containers").draggable({ disabled: true });
});
});
</script>
Use this code.
0
source to share