Setting z-index on draggable elements
The easiest way I found to solve this problem was to use the appendTo and zIndex options.
$('#box1,#box2,#box3,#box4').draggable({
appendTo: "body",
zIndex: 10000
});
All you need to do is use draggable({stack: "div"})
Now when you drag a div it will automatically come to the top.
Check working example at http://jsfiddle.net/LQ4JT/8/
Following code will fulfill your requirements. You need to stack
your divs
instead of setting z-indexes
and secondly you need to show the div at top after simply clicking it not dragging it.
So for stacking you need stack: "div"
and for showing the div element on the top by simply click, you need to use distance: 0
.
By default the value is distance: 10
which means until you don't drag it 10 pixels
, it won't show up on the top. By setting the value to distance: 0
makes it show on the top after a simple click.
Try the following code.
$('#box1,#box2,#box3,#box4').draggable({
stack: "div",
distance: 0
});
Working JSFiddle Here.
Edit:
Click the Run code snippet button below to execute this embedded code snippet.
$(document).ready(function() {
$('#box1,#box2,#box3,#box4').draggable({
stack: "div",
distance: 0
});
$('#dragZone div').click(function() {
$(this).addClass('top').removeClass('bottom');
$(this).siblings().removeClass('top').addClass('bottom');
});
});
#box1 {
width: 150px;
height: 150px;
background-color: red;
position: absolute;
top: 0px;
left: 0px;
z-index: 0
}
#box2 {
width: 150px;
height: 150px;
background-color: green;
position: absolute;
top: 20px;
left: 50px;
z-index: 0
}
#box3 {
width: 150px;
height: 150px;
background-color: yellow;
position: absolute;
top: 50px;
left: 100px;
z-index: 0
}
#box4 {
width: 150px;
height: 150px;
background-color: blue;
position: absolute;
top: 70px;
left: 200px;
z-index: 0
}
.top {
z-index: 100!important;
position: relative
}
.bottom {
z-index: 10!important;
position: relative
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div id="dragZone">
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
</div>
I have updated your CSS and Javascript. Don't use "!important" in css unless you are that much desperate.
http://jsfiddle.net/LQ4JT/7/
$(document).ready(function() {
var a = 3;
$('#box1,#box2,#box3,#box4').draggable({
start: function(event, ui) { $(this).css("z-index", a++); }
});
$('#dragZone div').click(function() {
$(this).addClass('top').removeClass('bottom');
$(this).siblings().removeClass('top').addClass('bottom');
$(this).css("z-index", a++);
});
});
Though this answer works it has the limitation of max number of 2^31−1 in javascript. refer What is JavaScript's highest integer value that a Number can go to without losing precision? for more info.