Question

...for chrome extension I have couple of popups, and I want to bring clicked one on top

screenshot

this is what I did

document.addEventListener("mousedown", function test(evt) {
    evt = evt || window.event;
    if (evt.target.className == 'popup') {
        //evt.target.style.backgroundColor = "blue";  **** successful test
        zIndex++;
        evt.target.style.zIndex = zIndex;
        evt.target.innerHTML = zIndex;
        console.log(evt.target.style.zIndex);
    }


});

on every click (on popup class) there is a counter that raise z-index by 1, save it to variable zIndex, and then that variable is applied to clicked element through

evt.target.style.zIndex = zIndex;

counter works, innerHTML is set to show z-index (evt.target.innerHTML = zIndex;) and also console is showing z-index of clicked element(popup)

but....that popup is not coming in front

What am I missing?

tnx

Was it helpful?

Solution

You should create 2 CSS classes, one called focus and one called unfocus. When you click on your element, you should swap the class. The currently clicked element will get the focus class with a high static z-index. The last clicked element, that was focused will get swapped back to unfocus with the low static z-index. I'll post some code as quickly as I can whip it up, but this is the method you should be using instead of stepping zIndex up incrementally.

Here is a basic example, simply replace my color background with your z-index settings.

<html><head><title></title>
<style>
  .first{
    background:silver;
    padding:20px;
    color:#ffffff;
    z-index:9000;
  }
  .second{
    background:yellow;
    padding:30px;
    color:#000000;
    z-index:9001;
  }
</style>
<script type="text/javascript">
  var y;  // create a variable to save the last focused element.
  function changeClass(x) {
    if (y) {
        y.className="first"; // sets last focused element to original style
    }
    x.className="second";  // sets current focused element to new style
    y = x;  // sets current element as y (the basis of a toggle)
  }
</script>
</head>
<body>
    <div id="div1" class="first" style="width: 200px;" onclick="changeClass(this);">Click me and I will change!</div>
    <div id="div2" class="first" style="width: 200px;" onclick="changeClass(this);">Click me and I will change too!</div>
</body>
</html>

Here is this in a fiddle: http://jsfiddle.net/v55z7/

OTHER TIPS

z-index is relative to the other objects on screen.

If you increment z-index for an element you need to relativly decrease the bottom element

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top