javascript image overlay over a specified div

17,848

Solution 1

You can define the overlay such as

<div id="myoverlay" class="myoverlay">...contents...</div>

and define the dimensions and position and z-index etc... in CSS

.myoverlay {
   position: absolute;
   display: none;
   ...
}

I don't quite see the need for JavaScript just yet, but I guess you will want to use JS to toggle the overlay's display attribute on/off.

<script type="text/javascript">
function showOverlay(){
  document.getElementById("myoverlay").style.display = "block";
}
</script>

Is this roughly what you're after? Sorry for unintentional syntax mistakes, for this is untested code purely off the top of my head. Just to give you an idea.

Solution 2

You can create a div with transparency and absolutely position it over the specified region.

var shimDiv = document.createElement('div');  
shimDiv.id = 'shim';  
shimDiv.style.position = 'absolute';  
shimDiv.style.top = 0;  
shimDiv.style.left = 0;  
shimDiv.style.width = "700px";  
shimDiv.style.height = "300px";  
shimDiv.style.backgroundColor = '#000'; 
shimDiv.style.zIndex = 3;   

For non IE browsers set opacity:

shimDiv.style.opacity = '0.75'; 

As IE doesn't natively support transparency you should use the filter like this:

shimDiv.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=75)';  

And add this new div to the end of the document body:

document.body.appendChild(shimDiv); 

To support older IE versions you will have to put IFrame element under your transparent DIV.

To create IFrame dynamically from JavaScript try the following code:

var iframe = document.createElement('iframe');
iframe.setAttribute("src", "javascript:false");

Don't forget to set IFrame src attribute with useless 'javascript:false' statement to prevent IFrame from trying to load the page (which you won't notice it doing, but it will be the cause for tripping the "Unsecured Items" message if you use it on a HTTPS page).

Position this IFrame under the div by giving it a lower z-index property value.

iframe.style.zIndex = 2;

All the styling can be done with CSS. I just wanted to show how it done with JavaScript.

Share:
17,848
amit
Author by

amit

new to stack overflow. learning...

Updated on June 05, 2022

Comments

  • amit
    amit almost 2 years

    i am new at javascript. very new actually, this ought to be my first script. can anyone explain to me how to make a transparent overlay over any specified fixed width region, say 700x300px.

  • James
    James almost 15 years
    Shouldn't the "display" be set to "block"?
  • Doug J. Huras
    Doug J. Huras over 8 years
    Works like a charm! Thanks.