Set zindex from js function

Discussion in 'JavaScript' started by nfzgrld, Jan 20, 2009.

  1. #1
    I'm trying to set the zindex on an object on the screen, could be an image, div, etc., and am having no luck at all. I want to use onclick() to call the function so when clicked on the item goes to the top of the stack. I've tried several different ideas, but nothing seems to be working. This is where I am now:

    function etop(){document.style.zIndex=1000;}
    Code (markup):
    Shouldn't this, or a variation of it, work?
     
    nfzgrld, Jan 20, 2009 IP
  2. lp1051

    lp1051 Well-Known Member

    Messages:
    163
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    108
    #2
    Hi,
    yes, 'this' would work better when set onclick, document.style actually has no element to set the style for. So if you want to do that through HTML, you can write <div onclick="etop(this)"> and in javascript :
    function etop(el){el.style.zIndex=1000;}
    Hope it helps
     
    lp1051, Jan 20, 2009 IP
  3. gnp

    gnp Peon

    Messages:
    137
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #3
    here is a complete example for you to play with ..

    
    <!-- stylesheet -->
    <style>
    	.freefloat{
    		position:absolute;
    		width:250px;
    		height:250px;
    		border:1px solid #000;
    		padding:1px;
    		}
    	.red{
    		background-color:red;
    		color:white;
    		left:10px;
    		top:10px;
    		}
    	.green{
    		background-color:green;
    		color:white;
    		left:100px;
    		top:200px;
    		}
    	.blue{
    		background-color:blue;
    		color:white;
    		left:200px;
    		top:50px;
    		}
    </style>
    
    <!-- javascript -->
    
    <script type="text/javascript">
     var start_z_index = 1000;
     function bringtotop( item )
     {
    	item.style.zIndex = start_z_index++;
     }
    </script>
    
    <!-- html in body -->
    <div id="red" class="freefloat red" onclick="bringtotop(this)">red content</div>
    <div id="green" class="freefloat green" onclick="bringtotop(this)">green content</div>
    <div id="blue" class="freefloat blue" onclick="bringtotop(this)">blue content</div>
    HTML:
    this example will work with multiple items in the same page being able to go to the top (that is why i keep a variable with the topmost item.. which increases on each new item going to top..)
     
    gnp, Jan 20, 2009 IP