I'm trying to change a div containment from "#div" to "window" when you click on a button. I couldn't find a way to do this, so I've tried to do it toggling the element's class.
It changes the class, but doesn't affect the containment.
Am I missing something?
Here is an example (the idea is that the red box can only be dragged in the blue area but if the button is pressed it can be dragged out of it and returns is its pressed again):
$(function() {
$("#draggable").draggable();
});
$(function() {
$('.float').draggable({
containment: "body"
});
});
$(function() {
$('.unfloat').draggable({
containment: "#desktop"
});
});
$(window).load(function() {
$(document).ready(function() {
$('#button').click(function() {
$(this).parent().toggleClass('unfloat');
$(this).parent().toggleClass('float');
});
});
});
html, body {
width: 100%;
height: 100%;
margin: 0px;
background-color: #000;
}
#desktop {
background-color: #00aaff;
width: 70%;
height: 70%;
}
#draggable {
width: 200px;
height:200px;
background-color: #ff0000;
margin: 0px;
}
#button {
width: 100px;
height: 30px;
float: right;
background-color: #bababa;
margin: 5px 5px 0px 0px;
}
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
</head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<div id="desktop" >
<div id="draggable" class="float">
<div id="button" onClick="">Toggle</div>
</div>
</div>
</body>
</html>