Click here to Skip to main content
Click here to Skip to main content

How To Make Floating and Dimming a Div using JavaScript

By , 14 Feb 2006
 
Sample Image - js_floating_dimming_div.jpg

Introduction

This script allows you to simulate, dimming the page, a pop up window message using a div. You can also use it to create an input window to ask for additional information.
This script has been tested only with Internet Explorer 6.0, Firefox 1.0.7 and Opera 8.51 on Windows 2003 Server.

How It Works

The first peculiarity of this script is to dim the page and to use any div, identified by an id, you write in your HTML code.
To dim the page, my code uses a dynamically added dimmer div having a semi-transparent PNG image as background. The source file contains a few PNG background images.
The script dynamically sets the dimmer's size equal to the window screen size as shown below:

//
// dynamically add a div to
// dim all the page
//
function buildDimmerDiv()
{
    document.write('<div id="dimmer" class="dimmer" style="width:'+
    window.screen.width + 'px; height:' + window.screen.height +'px"></div>');
}

And this is its CSS style:

div.dimmer
{
    visibility: hidden;
    position:absolute;
    left:0px;
    top:0px;
    font-family:verdana;
    font-weight:bold;
    padding:40px;

    background-image:url(honey.png);
    /* ieWin only stuff */
        /* with this trick only IE
           manage the following 2 attributes */
    _background-image:none;
    _filter:progid:DXImageTransform.Microsoft.AlphaImageLoader
        (enabled=true, sizingMethod=scale src='honey.png');
}

The script changes its visibility to visible before showing the floating div.

document.getElementById('dimmer').style.visibility = "visible";

The second script's feature is the chance to move the div. We are able to do it writing handlers for the main mouse events.

//
//
//
function MouseDown(e)
{
    if (over)
    {
        if (isMozilla) {
            objDiv = document.getElementById(DivID);
            X=e.layerX;
            Y=e.layerY;
            return false;
        }
        else {
            objDiv = document.getElementById(DivID);
            objDiv = objDiv.style;
            X=event.offsetX;
            Y=event.offsetY;
        }
    }
}

//
//
//
function MouseMove(e)
{
    if (objDiv) {
        if (isMozilla) {
            objDiv.style.top = (e.pageY-Y) + 'px';
            objDiv.style.left = (e.pageX-X) + 'px';
            return false;
        }
        else
        {
            objDiv.pixelLeft = event.clientX-X + document.body.scrollLeft;
            objDiv.pixelTop = event.clientY-Y + document.body.scrollTop;
            return false;
        }
    }
}

//
//
//
function MouseUp()
{
    objDiv = null;
}

//
//
//
function init()
{
    // check browser
    isMozilla = (document.all) ? 0 : 1;

    if (isMozilla)
    {
        document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
    }

    document.onmousedown = MouseDown;
    document.onmousemove = MouseMove;
    document.onmouseup = MouseUp;

    // add the div
    // used to dim the page
    buildDimmerDiv();

}

How To Use It

The layout of the dimmer and floating div is customizable using the dimming.css file. To use the script, first you must insert the following HTML code in the head section of your page:

<link REL=StyleSheet HREF="dimming.css" TYPE="text/css">
<script LANGUAGE="JavaScript" SRC="dimmingdiv.js">
</script>

Then define in your HTML code, a div containing the code to display:

<!--  the following hidden div will be used by the script -->
<div style="width: 518px; height: 287px;visibility:hidden" id="windowcontent">
            <script language="javascript">
            function Hello()
            {
               alert('Hello '+  document.getElementById('yourname').value + '!');
            }
            </script>
            <table >
            <tr><td colspan="2"></td></tr>
            <tr>
            <td>Your name:</td>
            <td><input type="text" style="width: 292px" id="yourname" /></td>
            </tr>
            <tr>
            <td colspan="2">
            <input type="button" value="Hello button" onclick="Hello();"
                style="width: 119px"/></td>
            </tr>
            <tr><td colspan="2">
Click the left mouse button on the blue header then move the floating div!!!</td></tr>
            </table>
</div>

Call the displayFloatingDiv function to show the div. This function accepts six input parameters:

  • ID of the div to show
  • title
  • width
  • height
  • left position
  • top position

//
//
//
function displayFloatingDiv(divId, title, width, height, left, top)
{
    DivID = divId;

    document.getElementById('dimmer').style.visibility = "visible";

    document.getElementById(divId).style.width = width + 'px';
    document.getElementById(divId).style.height = height + 'px';
    document.getElementById(divId).style.left = left + 'px';
    document.getElementById(divId).style.top = top + 'px';

    var addHeader;

    if (originalDivHTML == "")
        originalDivHTML = document.getElementById(divId).innerHTML;

    addHeader = '<table style="width:' + width + 'px" class="floatingHeader">' +
                '<tr><td ondblclick="void(0);" onmouseover="over=true;" onmouseout=
                     "over=false;" style="cursor:move;height:18px">' + title + '</td>' +
                '<td style="width:18px" align="right">
                <a href="javascript:hiddenFloatingDiv(\'' + divId + '\');void(0);">' +
                '<img title="Close..." alt="Close..." src="close.jpg" border="0" /</a>
                </td></tr></table>';


    // add to your div an header
    document.getElementById(divId).innerHTML = addHeader + originalDivHTML;


    document.getElementById(divId).className = 'dimming';
    document.getElementById(divId).style.visibility = "visible";
}

A displayFloatingDiv calling example is shown below:

var w, h, l, t;
w = 400;
h = 200;
l = screen.width/4;
t = screen.height/4;

// no title
// displayFloatingDiv('windowcontent', '', w, h, l, t);

// with title
displayFloatingDiv('windowcontent', 'Floating and Dimming Div', w, h, l, t);

Screenshots

Firefox screenshot

An Internet Explorer screenshot.

Firefox screenshot

An Opera screenshot.

Conclusion

The zip source file contains the script, CSS, PNG images and a demo HTML page.
I hope you enjoy this article.

Code4dotnet

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Massimo Beatini
Web Developer
Italy Italy
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralDimmer only the displayed part of pagememberkenpeck4 Mar '10 - 6:23 
Hi, I have the floating dimmer working but if the user scrolls down past the original page's display area the dimmed area stops. How do I get it to dim the entire page including the part does not show until the viewer scrolls down?
GeneralCannot round the corner of the dimming floating divisionmemberkenpeck24 Feb '10 - 6:20 
Hi,
 
I have tried several rounding corner methods, but none of the seem to work when the floating division appears. I have also tried putting a an extra row between the title and what I present in the division. which is an iframe and cannot get it to recognixze the extra row. here are some of the off the shelf rounded corner makers I have tried. I can get them to work on anything except the floating division.
 
http://www.editsite.net/blog/rounded_corners.html
 
http://kalsey.com/2003/07/rounded_corners_in_css
GeneralRe: Cannot round the corner of the dimming floating divisionmemberMassimo Beatini24 Feb '10 - 22:15 
Hi,
add this code to the "dimming" and "floatingHeader" class inside the dimming.css file
 

-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;

 
Attention: IE doesn't support "border-radius" CSS attribute.
http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx[^]
 

Bye
Massimo
GeneralRe: Cannot round the corner of the dimming floating divisionmemberkenpeck4 Mar '10 - 6:26 
Hi,
 
What can I do to get rounded corners with IE without using the Border-Radius?
GeneralRe: Cannot round the corner of the dimming floating divisionmemberkenpeck9 Mar '10 - 7:20 
I applied your fix and found a hack for IE
 
http://www.htmlremix.com/css/curved-corner-border-radius-cross-browser[^]
 
But it only works on the header and if you try to move the division the the rounded corner image does not move
GeneralFloating dimmermemberkenpeck19 Feb '10 - 3:52 
Hi,
 
Thanks for replying. I fixed the problem. I did try all those combninations of screen size. The problem was my brain Frown | :( Your script has to run after the ,<Body tag else there are no values for screen height and width no matter how you address them. Thank you for the code. Your authorship will always be there.
Generalfloating Div dimmermemberkenpeck18 Feb '10 - 6:44 
Hello Massimo,
 
I am trying to make the floating division center on the html page that it is embedded in. It seems that these lines.
 
document.getElementById(divId).style.width = width + 'px';
document.getElementById(divId).style.height = height + 'px';
document.getElementById(divId).style.left = left + 'px';
document.getElementById(divId).style.top = top + 'px';
 
cannot recognize the true size of the html page in the open browser. I have tried many variations regarding centering the floating division, Including commenting out left and top variables and just declaring the Div as centered
 
'HTML PAGE I am using
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="GENERATOR" content="Microsoft FrontPage 6.0">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

<LINK REL=StyleSheet HREF="dimming.css" TYPE="text/css">
<SCRIPT LANGUAGE="JavaScript" SRC="dimmingdiv.js"></SCRIPT>
<script language="javascript">
function displayWindow()
{
var w, h, l, t;
//w = 0
//h = 0
//l = 0
//t = 0
w = 640;
h = 430;
l = ((screen.width) - (640))/2;
t = ((screen.height) - (430))/2;

// no title
//displayFloatingDiv('windowcontent', '', w, h, l, t);
 
// with title
displayFloatingDiv('windowcontent', 'Hold mouse down here to move video', w, h, l, t);
}
</script>
</head>
<body leftmargin="0" topmargin="0" bgcolor=FloralWhite>
<p align="center" ><b>Content Area</b></p>
<p align="center" >Click here for video <a href="javascript:displayWindow();">Here</a></p>
<!-- the following hidden div will be used by the script -->
<Center><div style="visibility:hidden; width:656px; height:446px;" id="windowcontent">
<table width="640" height="430" id="table1" >
<tr>
<td width="640" bgcolor="#000000" align="center" style="background-color: #000000">
<iframe name="IFrameName" width="640" height="430" marginwidth="1" marginheight="1" style="background-color: #1a1a1a" title="Video" align="middle" target="_self" src="http://www.resume-software.com/slideshow/video/GopherIntroduction/GopherIntroductionWithVoiceY.html"></td>
</tr>
</table>
</div></Center>
</body>
</html>
 

 
****Your java Script
 

var isMozilla;
var objDiv = null;
var originalDivHTML = "";
var DivID = "";
var over = false;
 
//
// dynamically add a div to
// dim all the page
//
function buildDimmerDiv()
{
document.write('<div id="dimmer" class="dimmer" style="width:'+ window.screen.width + 'px; height:' + window.screen.height +'px"></div>');
}
 

//
//
//
function displayFloatingDiv(divId, title, width, height, left, top)
 
{
DivID = divId;
 
document.getElementById('dimmer').style.visibility = "visible";
 
document.getElementById(divId).style.width = width + 'px';
document.getElementById(divId).style.height = height + 'px';
document.getElementById(divId).style.left = left + 'px';
document.getElementById(divId).style.top = top + 'px';

var addHeader;

if (originalDivHTML == "")
originalDivHTML = document.getElementById(divId).innerHTML;

addHeader = '<table style="width:' + width + 'px" class="floatingHeader">' +
'<tr><td ondblclick="void(0);" onmouseover="over=true;" onmouseout="over=false;" style="cursor:move;height:18px">' + title + '</td>' +
'<td style="width:18px" align="center"><a href="javascript:hiddenFloatingDiv(\'' + divId + '\');void(0);">' +
'<img alt="Close..." title="Close..." src="close.jpg" border="0"></a></td></tr></table>';

 
// add to your div an header
document.getElementById(divId).innerHTML = addHeader + originalDivHTML;


document.getElementById(divId).className = 'dimming';
document.getElementById(divId).style.visibility = "visible";
 

}
 

//
//
//
function hiddenFloatingDiv(divId)
{
document.getElementById(divId).innerHTML = originalDivHTML;
document.getElementById(divId).style.visibility='hidden';
document.getElementById('dimmer').style.visibility = 'hidden';

DivID = "";
}
 
//
//
//
function MouseDown(e)
{
if (over)
{
if (isMozilla) {
objDiv = document.getElementById(DivID);
X = e.layerX;
Y = e.layerY;
return false;
}
else {
objDiv = document.getElementById(DivID);
objDiv = objDiv.style;
X = event.offsetX;
Y = event.offsetY;
}
}
}
 

//
//
//
function MouseMove(e)
{
if (objDiv) {
if (isMozilla) {
objDiv.style.top = (e.pageY-Y) + 'px';
objDiv.style.left = (e.pageX-X) + 'px';
return false;
}
else
{
objDiv.pixelLeft = event.clientX-X + document.body.scrollLeft;
objDiv.pixelTop = event.clientY-Y + document.body.scrollTop;
return false;
}
}
}
 
//
//
//
function MouseUp()
{
objDiv = null;
}
 

//
//
//
function init()
{
// check browser
isMozilla = (document.all) ? 0 : 1;
 

if (isMozilla)
{
document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
}
 
document.onmousedown = MouseDown;
document.onmousemove = MouseMove;
document.onmouseup = MouseUp;
 
// add the div
// used to dim the page
buildDimmerDiv();
 
}
 
// call init
init();
GeneralRe: floating Div dimmermemberMassimo Beatini18 Feb '10 - 23:13 
Hi,
substitue the displayWindow function with the following one.
I hope this can solve your problem.
Bye
Massimo

function displayWindow()
{
var w, h, l, t;
//w = 0
//h = 0
//l = 0
//t = 0
w = 640;
h = 430;
//l = ((screen.width) - (640))/2;
//t = ((screen.height) - (430))/2;
 
l = ((document.body.clientWidth) - (640))/2;
t = ((document.body.clientHeight) - (430))/2;
 
// no title
//displayFloatingDiv('windowcontent', '', w, h, l, t);
 
// with title
displayFloatingDiv('windowcontent', 'Hold mouse down here to move video', w, h, l, t);
}

GeneralInteraction with servermembersigurdur einarsson6 Nov '09 - 4:06 
If the "popup" had a yes|no question, and a serverside deletefunction() would have to be called respectively, how would you do that? I cannot find a way to initiate a serverside function from here! Sigh | :sigh:
Generaldisable controls problem in IEmemberhans heijstee14 Apr '09 - 4:20 
Hi,
 
Thanks for the article!
 
I have a problem with the dimmer div.
The background image covers the complete screen, but the div does not cover/disable all the controls on the page.
It looks like it 'covers' only half the page.
The style properties of the div are correct. (screen.height and screen.width)
 
In Firefox, the floating div does disable all the controls...
 
Please help!?
 
Thanks in advance
 
Regards,Hans

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 15 Feb 2006
Article Copyright 2006 by Massimo Beatini
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid