I have a bunch of divs on the screen. What I want to do is, when I select any div, I want its zIndex to be always higher than all other divs.
In my application, i will need to do this repeatedly whenever I select a div, put it on top of others.
Is this possible using Javascript?
In some cases, you can bring an element to top without using CSS directly. If you place your DIVs to the body tag or under another parent element, you can re-append itself to the parent. JavaScript will move it to the last position in the child list which will bring the element in a "natural" way to the top.
Example:
myElement.parentNode.appendChild(myElement);
I used this trick for my custom context menu. Works without zIndex.
Yes, very much so.
HTML:
<div>foo</div>
<div>bar</div>
<div>bas</div>
Javascript:
//Collect all divs in array, then work on them
var all = document.selectElementsByTagName("div");
var prev = false;
for(i = 0; i < all.length; i++) {
all[i].onclick = function() {
all[i].style.position = 'relative'; //necessary to use z-index
if (prev) { prev.style.zIndex = 1; }
this.style.zIndex = 1000;
prev = this;
}
}
}
//Edit: Sorry, forgot a brace. Corrected now.
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