Sunday, July 5, 2015

Image comes on top setting z-index - using javascript only


These are three images whose z-index is set using javascript. Z-index determines the depth of the image. All text and images by default have z-index of 0. If you set z-index of -1 for an image and its position property to absolute you can make it a background image.

Here is the code:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<!DOCTYPE html>
<html>
<head>
<style>

div.img:hover img
{display:block;
z-index:3}
div imgc2 :hover img
{display:block;
z-index:3}
div imgc3 :hover img
{display:block;
z-index:3}
#img1 {
    position: absolute;
    left: 0px;
    top: 0px;

}
#img2 {
    position: absolute;
    left: 20px;
    top: 20px;

}
#img3 {
    position: absolute;
    left: 40px;
    top: 40px;

}
</style>
<script type="text/javascript">
function button1()
{
var img1=document.getElementById("img1");
var img2=document.getElementById("img2");
var img3=document.getElementById("img3");
var para1=document.getElementById("para");
para1.style.fontSize="20px";
img1.style.zIndex=3;
img2.style.zIndex=2;
img3.style.zIndex=1;
}
function button2()
{
var img11=document.getElementById("img1");
var img22=document.getElementById("img2");
var img33=document.getElementById("img3");

img11.style.zIndex=2;
img22.style.zIndex=3;
img33.style.zIndex=1;

}
function button3()
{
var img11=document.getElementById("img1");
var img22=document.getElementById("img2");
var img33=document.getElementById("img3");

img11.style.zIndex=1;
img22.style.zIndex=2;
img33.style.zIndex=3;

}
</script>
</head>
<body>
<h1>This is a heading</h1>
<div class="img"><img id="img1" class="imgc1" src="w3css.gif" width="100" height="140">
<img id="img2" class="imgc2" src="300x300_72.gif" width="100" height="140">
<img id="img3" class="imgc3" src="index.jpg" width="100" height="140"></div>
<p id="para">Because the image has a z-index of -1, it will be placed behind the text.</p>
<br /><br /><br /><br /><br /><br />
<input type="button" id="button1" value="3,2,1" onclick="button1()"/>
<input type="button" id="button2" value="2,3,1" onclick="button2()"/>
<input type="button" id="button3" value="1,2,3" onclick="button3()"/>
</body>
</html>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here button1, button2 and button2 are three javascript functions which set the z-index using the DOM function getElementById().

No comments:

Post a Comment