Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bring the selected div on top of all other div's

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?

like image 794
ssdesign Avatar asked Oct 25 '10 05:10

ssdesign


2 Answers

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.

like image 107
StanE Avatar answered Nov 08 '22 22:11

StanE


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.

like image 36
Ben Avatar answered Nov 08 '22 23:11

Ben