In my application I can open several div boxes that overlap each other. When clicking on a box that box should be moved to the top. What is the best way to accomplish this?
The only thing I can think of is looping through all the boxes z-index values to get the highest value, and then add 1 to that value and apply it on the clicked div.
Any advices for me?
Set the DIV's z-index to one larger than the other DIVs. You'll also need to make sure the DIV has a position other than static set on it, too. position relative and z index set to 999999999999999999999999999999999999999999999999999.
Use the CSS z-index property. Elements with a greater z-index value are positioned in front of elements with smaller z-index values. Note that for this to work, you also need to set a position style ( position:absolute , position:relative , or position:fixed ) on both/all of the elements you want to order.
In order to pull an html element out of the natural flow of how the elements are layed out on the screen you need to use position: absolute. This will allow the element to become a layer above the other elements (assuming that the z-index value is greater than all other's).
Note: Z index only works on positioned elements ( position:absolute , position:relative , or position:fixed ).
Assuming you have elements with a specific class ("box" in my example) and that all are in the same container like this :
<div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
Assuming you have the correct css :
.box {position:absolute; z-index:10}
You can use the jquery js code below :
$('.box').click(function() {
// set ohters element to the initial level
$(this).siblings('.box').css('z-index', 10);
// set clicked element to a higher level
$(this).css('z-index', 11);
});
something like this should do it:
// Set up on DOM-ready
$(function() {
// Change this selector to find whatever your 'boxes' are
var boxes = $("div");
// Set up click handlers for each box
boxes.click(function() {
var el = $(this), // The box that was clicked
max = 0;
// Find the highest z-index
boxes.each(function() {
// Find the current z-index value
var z = parseInt( $( this ).css( "z-index" ), 10 );
// Keep either the current max, or the current z-index, whichever is higher
max = Math.max( max, z );
});
// Set the box that was clicked to the highest z-index plus one
el.css("z-index", max + 1 );
});
});
I would approach this by making a jQuery plugin, so you don't have to worry about manually setting the z-index
and keeping track of the highest value with a variable:
(function() {
var highest = 1;
$.fn.bringToTop = function() {
this.css('z-index', ++highest); // increase highest by 1 and set the style
};
})();
$('div.clickable').click(function() {
$(this).bringToTop();
});
This wouldn't work well if you set z-index
with any other code on your page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With