PDA

View Full Version : Grayscale Effect with CSS on other browsers beside IE



tech_support
10-24-2006, 09:01 AM
I'd like to make the same grayscale effect on IE compatiable with FireFox. Any ideas?

djr33
10-24-2006, 09:29 AM
Is that a filter?
Not compatible.

I don't know if there is another way.

It's not that hard to just take an image and make it greyscale in most any graphics application, or you could even use the PHP GD library, if you must have it dynamically generated.

Twey
10-24-2006, 11:21 AM
No, it isn't possible (without Flash, Java, &c.).

tech_support
10-25-2006, 07:49 AM
How would you do it with PHP?

djr33
10-25-2006, 08:17 AM
Check this out, maybe:
(From http://us3.php.net/manual/en/function.imagecopymergegray.php )

To convert the picture to grayscale, use the following code:
<?php
// replace with your files
$originalFileName = "colorPicture.jpg";
$destinationFileName = "bwPicture.jpg";

// create a copy of the original image
// works with jpg images
// fell free to adapt to other formats ;)
$fullPath = explode(".",$originalFileName);
$lastIndex = sizeof($fullPath) - 1;
$extension = $fullPath[$lastIndex];
if (preg_match("/jpg|jpeg|JPG|JPEG/", $extension)){
$sourceImage = imagecreatefromjpeg($originalFileName);
}

// get image dimensions
$img_width = imageSX($sourceImage);
$img_height = imageSY($sourceImage);

// convert to grayscale
// note: this will NOT affect your original image, unless
// originalFileName and destinationFileName are the same
for ($y = 0; $y <$img_height; $y++) {
for ($x = 0; $x <$img_width; $x++) {
$rgb = imagecolorat($sourceImage, $x, $y);
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;

$gray = round(.299*$red + .587*$green + .114*$blue);

// shift gray level to the left
$grayR = $gray << 16; // R: red
$grayG = $gray << 8; // G: green
$grayB = $gray; // B: blue

// OR operation to compute gray value
$grayColor = $grayR | $grayG | $grayB;

// set the pixel color
imagesetpixel ($sourceImage, $x, $y, $grayColor);
imagecolorallocate ($sourceImage, $gray, $gray, $gray);
}
}

// copy pixel values to new file buffer
$destinationImage = ImageCreateTrueColor($img_width, $img_height);
imagecopy($destinationImage, $sourceImage, 0, 0, 0, 0, $img_width, $img_height);

// create file on disk
imagejpeg($destinationImage, $destinationFileName);

// destroy temp image buffers
imagedestroy($destinationImage);
imagedestroy($sourceImage);
?>Copy-paste, replace the file names on the top and there you go (picture files must be in same folder as this script. If not, you will have to do your own file management).

tech_support
10-25-2006, 09:15 AM
I mean, making the WHOLE PAGE grayscale (just like when you click Logout in these forums when using IE)

djr33
10-25-2006, 01:45 PM
Ah. HTML, etc?

Interesting.

I'm not sure.

I'm not seeing anything in IE when I log out. Or FF, for that matter.

The way, I suppose, would be to fade/switch to greyscale CSS, Images, etc.

Depending on the purpose, you could just create alternate CSS, use when needed, and be done with it.

tech_support
10-26-2006, 07:36 AM
Have you tried clicking Logout on the menu?

It will ask for a confirmation as well as grayscaling the screen.

Twey
10-26-2006, 06:34 PM
You can overlay a semi-transparent element over the page, which will result in the same sort of effect if the user's brightness/contrast is sufficiently low, and be an acceptable alternative if not.

djr33
10-26-2006, 11:49 PM
Interesting. I did just see it in IE. Before, I clicked ok, expecting something after that, and missed as the confirm was there.
That is, according to the code, just a filter.
So... still not sure.

Twey's idea might work. It would work really well if you could set the blending mode, like in photoshop, to "color" or something...

I still suggest a CSS switch and perhaps something about images... like switcing the SRCs, similar to a mouseover, or perhaps PHP GD if need be.

djr33
10-27-2006, 10:04 AM
Hmm... I should've noticed how long that greyscale funtion is above. It's WAY too much.

Here's a better one---
function ConvertGreyscale($image){
# this file outputs a grey version of specified image

$total = ImageColorsTotal($image);
for( $i=0; $i<$total; $i++){
$old = ImageColorsForIndex($image, $i);

#trying to keep proper saturation when converting
$commongrey = (int)(($old[red] + $old[green] + $old[blue]) / 3);

ImageColorSet($image, $i, $commongrey, $commongrey, $commongrey);
}
}

tech_support
10-28-2006, 12:23 AM
You can overlay a semi-transparent element over the page, which will result in the same sort of effect if the user's brightness/contrast is sufficiently low, and be an acceptable alternative if not.

Cool - How would I do that?

Twey
10-28-2006, 11:42 AM
var d = document.createElement("div");
d.style.display = "none";
if(typeof d.style.filter !== 'undefined')
d.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=/path/to/semitransparent.png)";
else
d.style.backgroundImage = "url(/path/to/semitransparent.png)";
d.style.position = "absolute";
d.style.width = "100%";
d.style.height = "9000%"; // big number. Ugly, but necessary.
d.style.margin = d.style.padding = "0";
d.style.zIndex = "100";
document.body.appendChild(d);

function showShadow() {
d.style.display = "block";
}

function hideShadow() {
d.style.display = "none";
}That will probably work. I have some tested code for it somewhere, but no access to it at the moment.

tech_support
10-28-2006, 12:54 PM
Is there any alternative solution without using images?

Twey
10-28-2006, 05:47 PM
Yes, you can use opacity instead, but it won't be as compatible. The image only needs to be a single pixel, and it's not difficult to create; one is attached.

tech_support
10-30-2006, 12:34 AM
It doesn't seem to work.

Twey
10-30-2006, 12:35 AM
Tsk, you should know better by now than to say "it doesn't work" :p

What happens when you try to use it? Is there an error? Can we see a demo page?

tech_support
10-30-2006, 12:38 AM
Sorry... I seem to be losing my mind :p

I used your code:



var d = document.createElement("div");
d.style.display = "none";
if(typeof d.style.filter !== 'undefined')
d.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=/images/semitransparent.png)";
else
d.style.backgroundImage = "url(/images/semitransparent.png)";
d.style.position = "absolute";
d.style.width = "100%";
d.style.height = "9000%"; // big number. Ugly, but necessary.
d.style.margin = d.style.padding = "0";
d.style.zIndex = "100";
document.body.appendChild(d);

function showShadow() {
d.style.display = "block";
}

...and

it says "Object Expected" or shows nothing at all. I've tried to add a loader to it (window.onload=showShadow) and nothing happens.

tech_support
10-30-2006, 05:18 AM
I made my own code:



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<style type="text/css">
.shadow{
position: absolute;
top: 0;
left: 0;
z-index: 90;
width: 102%;
height:900px;
background-color: #000;
filter:alpha(opacity=60);
-moz-opacity: 0.6;
opacity: 0.6;
}
body {

font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:10px;
}
</style>

</head>

<body>
<p>
<script type="text/javascript">
<!--
function opacity(id, opacStart, opacEnd, millisec) {
var speed = Math.round(millisec / 100);
var timer = 0;
if(opacStart > opacEnd) {
for(i = opacStart; i >= opacEnd; i--) {
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
} else if(opacStart < opacEnd) {
for(i = opacStart; i <= opacEnd; i++)
{
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
}
}
function changeOpac(opacity, id) {
var object = document.getElementById(id).style;
object.opacity = (opacity / 100);
object.MozOpacity = (opacity / 100);
object.KhtmlOpacity = (opacity / 100);
object.filter = "alpha(opacity=" + opacity + ")";
}
function createShadow(id) {

var s=document.createElement('div');
s.className="shadow";
s.setAttribute("id", id, 0);
document.body.appendChild(s);
opacity(id,0,60,500);
}
function clearShadow(id) {

opacity(id,60,0,500);
setTimeout("document.getElementById('"+id+"').style.display='none'",500)
}

//The Below is for demonstration purposes only.
function writeDemo() {

document.getElementById("demo").innerHTML='<a href="javascript:clearShadow(\'demo\');"><font color="#FFFFFF">Turn off Shadow</font></a>'
}
//The above is for demonstration purposes only.

//-->
</script>
This is a Shadow effect.</p>
<p>Functions:</p>
<p>createShadow(id) - Create the Shadow<br>
clearShadow(id) - Clear the Shadow<br>
</p>
<p><strong>id </strong> - The name of the div you wish to call</p>
<p>&nbsp;</p>
<p><strong>Demo: </strong><a href="javascript:createShadow('demo');writeDemo()">Turn Shadow On</a></p>
<p><strong>Code:</strong></p>
<form name="form1" method="post" action="">
<label>
<textarea name="textarea" cols="100" rows="20"> <!--
function opacity(id, opacStart, opacEnd, millisec) {
var speed = Math.round(millisec / 100);
var timer = 0;
if(opacStart > opacEnd) {
for(i = opacStart; i >= opacEnd; i--) {
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
} else if(opacStart < opacEnd) {
for(i = opacStart; i <= opacEnd; i++)
{
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
}
}
function changeOpac(opacity, id) {
var object = document.getElementById(id).style;
object.opacity = (opacity / 100);
object.MozOpacity = (opacity / 100);
object.KhtmlOpacity = (opacity / 100);
object.filter = "alpha(opacity=" + opacity + ")";
}
function createShadow(id) {

var s=document.createElement('div');
s.className="shadow";
s.setAttribute("id", id, 0);
document.body.appendChild(s);
opacity(id,0,60,500);
}
function clearShadow(id) {

opacity(id,60,0,500);
setTimeout("document.getElementById('"+id+"').style.display='none'",500)
}
//-->
</textarea>
</label>
</form>
<p><strong></strong></p>
</body>
</html>


Tell me if you like it or not.

Twey: I'm using HTML 4.01 Strict!!!! :D

Twey
10-30-2006, 05:57 PM
Don't specify the height in pixels -- people with resolutions greater than that won't see the whole page covered. 100% of the height of a child of the body is the height of the viewport.
function createShadow(id) {

var s=document.createElement('div');You create a new element every time you call createShadow()? Ouch.
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));It's generally considered nicer to use a closure rather than a string there. It avoids having to give everything IDs, and is also just cleaner than using a string, which is almost as bad as using new Function() or eval() :)
Twey: I'm using HTML 4.01 Strict!!!! Well done. :p

tech_support
10-31-2006, 05:23 AM
OK, here's another version:



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<style type="text/css">
.shadow{
position: absolute;
top: 0;
left: 0;
z-index: 90;
width: 100%;
height:100%;
background-color: #000;
filter:alpha(opacity=60);
-moz-opacity: 0.6;
opacity: 0.6;
color:#FFFFFF;

}
body {

font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:10px;
}

.close {

font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:10px;
color:#FFFFFF;
}

.dialog {

border:medium #000000;
font-family:Verdana, Arial, Helvetica, sans-serif;
overflow:auto;
height:250px;
width:250px;
position:relative;
border-bottom:medium #000000;
border-top:medium #000000;
border-left:medium #000000;
border-right:medium #000000;
display:none;
background-color:#FFFFFF;
color:#000000;
}
</style>

</head>

<body>
<p>
<script type="text/javascript">
<!--
//Configuration
var imageDir = "" //Images Directory
var shadowOnload = 0 //Onload? Yes=1 No=0
//End Configuration

function opacity(id, opacStart, opacEnd, millisec) {
var speed = Math.round(millisec / 100);
var timer = 0;
if(opacStart > opacEnd) {
for(i = opacStart; i >= opacEnd; i--) {
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
} else if(opacStart < opacEnd) {
for(i = opacStart; i <= opacEnd; i++)
{
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
}
}
function changeOpac(opacity, id) {
var object = document.getElementById(id).style;
object.opacity = (opacity / 100);
object.MozOpacity = (opacity / 100);
object.KhtmlOpacity = (opacity / 100);
object.filter = "alpha(opacity=" + opacity + ")";
}
var eCreated = 0
var windowOpen=0
function createShadow(effect) {

if (windowOpen==1) {

alert("Shadow already open!")
return false
}
if (eCreated==0) {
var s=document.createElement('div');
eCreated==1
s.className="shadow";
s.setAttribute("id", "overlay", 0);
document.body.appendChild(s);
opacity('overlay',0,60,700);
document.getElementById("overlay").innerHTML='<div align="right"><a href="javascript:clearShadow();" class="close">Close</a></div>'
}
else {
document.getElementById("overlay").style.display = "block"
opacity('overlay',0,60,700);
}

windowOpen==1


}
function clearShadow() {

opacity('overlay',60,0,700)
setTimeout("document.getElementById('overlay').style.display='none'",700)
}

function initShadow() {

if (shadowOnload==1) {

createShadow();

}
}
setTimeout("initShadow()",300)

function openConfirmationDialog() {

createShadow();
if (confirm("Are you sure?")) {

alert("Confirmed")
clearShadow();
return;
}
else {

alert("Not confirmed");
clearShadow();
}
}

function createDialog(e) {

createShadow()
var dialogText = document.getElementById(e).innerHTML
document.getElementById("overlay").innerHTML += '<div id="d" class="dialog">'+dialogText+'</div>'
setTimeout("document.getElementById(\"d\").style.display = \"block\";opacity('d',0,100,500)",1000)
}

function getKey(e){
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
key = String.fromCharCode(keycode).toLowerCase();

if(key == 'x'){
clearShadow();
}
if (key == 's'){
createShadow();
}
}
window.onkeyup=getKey;
//-->
</script>
This is a Shadow effect.</p>
<p><strong>Functions:</strong></p>
<p>createShadow() - Create the Shadow<br>
clearShadow() - Clear the Shadow</p>
<p><strong>Keyboard Shortcuts:</strong></p>
<p>X - Close<br>
S - Turn on the Shadow
</p>
<p><strong>Demos: </strong></p>
<p><a href="javascript:createShadow()">Turn Shadow On</a></p>
<p><a href="javascript:openConfirmationDialog();">Ask for confirmation</a></p>
<p><a href="javascript:createDialog('demoText')">Open up a dialog </a></p>
<div id="demoText" class="dialog">
<p>This is a dialog.</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam eget purus. Curabitur leo enim, accumsan eu, varius in, tincidunt eu, augue. Nulla auctor tellus vitae turpis. Cras sed elit. Suspendisse pulvinar nisi eget diam. Vivamus vehicula. Duis nec sapien sed sapien ultricies facilisis. Sed tellus. Phasellus facilisis est et ligula. Aliquam erat volutpat. Nunc sed velit vel arcu consectetuer sodales. Maecenas mattis lacinia mauris. Morbi dapibus iaculis ante. Aenean sed urna eget nulla molestie interdum. Nulla vitae ligula. Cras sollicitudin, orci id venenatis ullamcorper, magna tortor iaculis est, vel nonummy lacus leo in magna. Fusce vel nisl interdum eros imperdiet ullamcorper. Donec interdum, elit id porta scelerisque, dui leo gravida elit, non euismod tellus elit lobortis lorem. Sed risus lacus, ultrices vel, laoreet ut, gravida nec, eros. </p>
</div>
</body>
</html>


I picked up the fade in and fade out code from here: http://www.brainerror.net/scripts_js_blendtrans.php

How do I make the dialog in the center of the page?


Edited: Dialog feature, some fixes. See demo.

tech_support
10-31-2006, 06:49 AM
Here's a demo:

http://www.b3ta.cr3ation.co.uk/data/html/shadowEffect.html

djr33
10-31-2006, 07:53 AM
Interesting. It doesn't really do a greyscale effect, but the fade is just as effective. Makes sense too... easy in theory (and the code works well, though it doesn't look simple, exactly).

The demo page isn't great, but it shows off the effect.
The most noticable problem is not being able to turn off the effect, and likewise hitting S repeatedly and getting it darker and darker.
Also, if you activate the effect, the links don't work, so you can't turn it off/activate the alert, etc etc.

Note: X doesn't seem to work. (though I'm using Safari, but S works fine...). Does "close" mean close the window? Maybe that's why.... it's supposed to be loaded as a popup?

tech_support
10-31-2006, 08:33 AM
Note: X doesn't seem to work. (though I'm using Safari, but S works fine...). Does "close" mean close the window? Maybe that's why.... it's supposed to be loaded as a popup?

Hmm... It seems to work on my machine.


The most noticable problem is not being able to turn off the effect, and likewise hitting S repeatedly and getting it darker and darker.


Yeah, I'm going to work on that.


Also, if you activate the effect, the links don't work, so you can't turn it off/activate the alert, etc etc.

On the top-right hand corner there's a close link.

djr33
10-31-2006, 08:51 AM
Ah, I see the link now. Cool.
(Doesn't work if you hit S multiple times, though.)

Anyway, this isn't important... just a demo page... and what it's demoing is cool :)

tech_support
10-31-2006, 08:53 AM
Ok, here's another version:



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<style type="text/css">
.shadow{
position: absolute;
top: 0;
left: 0;
z-index: 90;
width: 100%;
height:100%;
background-color: #000;
filter:alpha(opacity=60);
-moz-opacity: 0.6;
opacity: 0.6;
color:#FFFFFF;

}
body {

font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:10px;
}

.close {

font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:10px;
color:#FFFFFF;
}

.dialog {

border:medium #000000;
font-family:Verdana, Arial, Helvetica, sans-serif;
overflow:auto;
height:250px;
width:250px;
position:relative;
border-bottom:medium #000000;
border-top:medium #000000;
border-left:medium #000000;
border-right:medium #000000;
display:none;
background-color:#FFFFFF;
color:#000000;
}
</style>

</head>

<body>
<p>
<script type="text/javascript">
<!--
//Configuration
var imageDir = "" //Images Directory
var shadowOnload = 0 //Onload? Yes=1 No=0
//End Configuration

function opacity(id, opacStart, opacEnd, millisec) {
var speed = Math.round(millisec / 100);
var timer = 0;
if(opacStart > opacEnd) {
for(i = opacStart; i >= opacEnd; i--) {
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
} else if(opacStart < opacEnd) {
for(i = opacStart; i <= opacEnd; i++)
{
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
}
}
function changeOpac(opacity, id) {
var object = document.getElementById(id).style;
object.opacity = (opacity / 100);
object.MozOpacity = (opacity / 100);
object.KhtmlOpacity = (opacity / 100);
object.filter = "alpha(opacity=" + opacity + ")";
}
var eCreated = 0
var windowOpen=0
function Shadow() {

if (eCreated==0) {
var s=document.createElement('div');
eCreated==1
s.className="shadow";
s.setAttribute("id", "overlay", 0);
document.body.appendChild(s);
opacity('overlay',0,60,700);
document.getElementById("overlay").innerHTML='<div align="right"><a href="javascript:clearShadow();" class="close">Close</a></div>'

}
else {
document.getElementById("overlay").style.display = "block"
opacity('overlay',0,60,700);
}

}

function createShadow() {

if (windowOpen==1) {

return false;
}
else {

new Shadow();
windowOpen++
}
}
function clearShadow() {

opacity('overlay',60,0,700)
setTimeout("document.getElementById('overlay').style.display='none'",700)
windowOpen--
}

function initShadow() {

if (shadowOnload==1) {

createShadow();

}
}
setTimeout("initShadow()",300)

function openConfirmationDialog() {

createShadow();
if (confirm("Are you sure?")) {

alert("Confirmed")
clearShadow();
return;
}
else {

alert("Not confirmed");
clearShadow();
}
}

function createDialog(e) {

createShadow()
var dialogText = document.getElementById(e).innerHTML
document.getElementById("overlay").innerHTML += '<div id="d" class="dialog">'+dialogText+'</div>'
setTimeout("document.getElementById(\"d\").style.display = \"block\";opacity('d',0,100,500)",1000)
}

function getKey(e){
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
key = String.fromCharCode(keycode).toLowerCase();

if(key == 'x'){
clearShadow();
}
if (key == 's'){
createShadow();
}
}
window.onkeyup=getKey;
//-->
</script>
This is a Shadow effect.</p>
<p><strong>Functions:</strong></p>
<p>createShadow() - Create the Shadow<br>
clearShadow() - Clear the Shadow</p>
<p><strong>Keyboard Shortcuts:</strong></p>
<p>X - Close<br>
S - Turn on the Shadow
</p>
<p><strong>Demos: </strong></p>
<p><a href="javascript:createShadow()">Turn Shadow On</a></p>
<p><a href="javascript:openConfirmationDialog();">Ask for confirmation</a></p>
<p><a href="javascript:createDialog('demoText')">Open up a dialog </a></p>
<div id="demoText" class="dialog">
<p>This is a dialog.</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam eget purus. Curabitur leo enim, accumsan eu, varius in, tincidunt eu, augue. Nulla auctor tellus vitae turpis. Cras sed elit. Suspendisse pulvinar nisi eget diam. Vivamus vehicula. Duis nec sapien sed sapien ultricies facilisis. Sed tellus. Phasellus facilisis est et ligula. Aliquam erat volutpat. Nunc sed velit vel arcu consectetuer sodales. Maecenas mattis lacinia mauris. Morbi dapibus iaculis ante. Aenean sed urna eget nulla molestie interdum. Nulla vitae ligula. Cras sollicitudin, orci id venenatis ullamcorper, magna tortor iaculis est, vel nonummy lacus leo in magna. Fusce vel nisl interdum eros imperdiet ullamcorper. Donec interdum, elit id porta scelerisque, dui leo gravida elit, non euismod tellus elit lobortis lorem. Sed risus lacus, ultrices vel, laoreet ut, gravida nec, eros. </p>
</div>
</body>
</html>


Demo: http://www.b3ta.cr3ation.co.uk/data/html/605shadowEffect.html

tech_support
10-31-2006, 08:56 AM
I just noticed that it looks kinda like Lightbox :)

djr33
10-31-2006, 09:05 AM
Yep. I think it's based on the same ideas.

Note-- on both versions, in safari at least (I can test in other browsers later if you want, but since you don't have access to safari, that should be helpful), I get a flash before it starts to fade, like it jumps to grey then to the beginning of the fade from white to grey.

tech_support
10-31-2006, 09:09 AM
Yeah, that happens in FireFox as well. I don't know why...

Twey
10-31-2006, 09:54 AM
Better, but you're still using strings instead of closures for that setTimeout.

tech_support
11-01-2006, 05:40 AM
Do you know how to make the dialog in the center of the page?

tech_support
11-11-2006, 04:23 AM
Ok, just made another version. Called it 'eXtreme Lightbox'



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>eXtreme Lightbox 1.0</title>
<style type="text/css">
.style1 {font-size: 24px}
body {

font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:10px;
}
</style>
<link rel="stylesheet" href="shadow.css" type="text/css" media="screen">
<script type="text/javascript">
/*
Configuration

shadowOnload: 1 for Yes, 0 for No
key: Enables keyboard operations (S for new Shadow; X for closing shadow, F for flashing shadow etc.)
*/
var shadowOnload = 0
var key = 1


/*
Opacity Code
From: http://www.brainerror.net/scripts_js_blendtrans.php
*/
function opacity(id, opacStart, opacEnd, millisec) {
var speed = Math.round(millisec / 100);
var timer = 0;
if(opacStart > opacEnd) {
for(i = opacStart; i >= opacEnd; i--) {
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
} else if(opacStart < opacEnd) {
for(i = opacStart; i <= opacEnd; i++)
{
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
}
}

function changeOpac(opacity, id) {
var object = document.getElementById(id).style;
object.opacity = (opacity / 100);
object.MozOpacity = (opacity / 100);
object.KhtmlOpacity = (opacity / 100);
object.filter = "alpha(opacity=" + opacity + ")";
}
/*
Shadow
*/

var eCreated = 0
var windowOpen=0
Shadow = function(speedFade) {

if (eCreated==0) { //If element has NOT been created
var s=document.createElement('div'); //Create the element
eCreated++ //Say it has been created
s.className="shadow"; //Set the class
s.setAttribute("id", "overlay", 0); //Set the id
document.body.appendChild(s); //Make it alive
opacity('overlay',0,60,speedFade*1000); //Fade in
document.getElementById("overlay").innerHTML='<div align="right"><a href="javascript:Shadow.ClearShadow()" class="close">Close</a></div>' //Add the link

}
else { //If the element has been created
document.getElementById("overlay").style.display = "block" //Make the shadow appear
opacity('overlay',0,60,speedFade*1000); //Fade it in
}

}
/*
CreateShadow
*/
Shadow.CreateShadow = function() {

if (windowOpen==1) { //Check if the shadow's open already

return false;
}
else {

new Shadow(0.7); //Or else create a shadow with 0.7sec fade in
windowOpen++ //Say that the window is open
}
}
/*
ClearShadow
*/
Shadow.ClearShadow = function() {

opacity('overlay',60,0,700) //Fade away!!!
document.getElementById('overlay').innerHTML == "" //Clearing the shadow content
// document.getElementById('dialog').innerHTML == "" //Clearing the dialog content
setTimeout("document.getElementById('overlay').style.display='none'",700) //Hiding the display
windowOpen-- //Saying that the window's not open
}
/*
Shadow on onload
*/
function initShadow() {

if (shadowOnload==1) { //If you chosen to put the shadow onload
Shadow.CreateShadow() //Create the shadow
}
}
setTimeout("initShadow()",300) //Set the onload

/*
Confirmation when opening Shadow
*/
function openConfirmationDialog() {

createShadow();
if (confirm("Are you sure?")) {

alert("Confirmed")
Shadow.ClearShadow()
return;
}
else {

alert("Not confirmed");
Shadow.ClearShadow()
}
}
/*
Create a dialog when opening a shadow
*/
Shadow.createDialog = function(e) {

createShadow()
var dialogText = document.getElementById(e).innerHTML
document.getElementById("overlay").innerHTML += '<div id="d" class="dialog">'+dialogText+'</div>'
setTimeout("document.getElementById(\"d\").style.display = \"block\";opacity('d',0,100,0.7*1000)",1000)
}

var flashCreated = 0
var flash = 1
var flashCancel = 0
var TimerInit = 0
var sec1 = 0
/*
Flash the Shadow
*/
Shadow.Pulsing = function() {

if (flashCancel==1) {return false;}
if (flash==1){new Shadow(0);flash--}
if (flash==0){Shadow.ClearShadow();flash++}
}
Shadow.Pulse = function(sec) {

if (flashCancel==1) {return false;}
if (sec1==sec){return false}
sec1++
Shadow.Pulsing()
setTimeout("Shadow.Pulse("+sec+")",700)
}
Shadow.ClearPulse = function() {

flashCancel++
}
var typing = 0
/*
Keyboard Functions
*/
function getKey(e){
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
key = String.fromCharCode(keycode).toLowerCase();

if(key == 'x'){
Shadow.ClearShadow()
}
if (key == 's'){
createShadow();}
if (key == 'f'){
flashCancel++
}
}
if (key==1){
window.onkeyup=getKey;}
/*
Ajax GET Code
*/
window.onload=function(){
var aj = document.createElement("div")
aj.setAttribute("id", "ajaxDisturbance", 0);
document.body.appendChild(aj);
}
Shadow.createDialogAjax = function(url){
var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Error calling Ajax")
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("ajaxDisturbance").innerHTML = ajaxRequest.responseText;
createDialog('ajaxDisturbance')
}
}
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}

//-->
</script></head>

<body>
<p><span class="style1">eXtreme LightBox v.1.0 </span>Beta</p>
<p>

<strong>Functions:</strong></p>
<p>Shadow.createShadow() - Create the Shadow<br>
Shadow.clearShadow() - Clear the Shadow<br>
Shadow.Pulse() - Flash Shadow<br>
Shadow.createDialog(e) - Create a dialog (e - element id) <br>
new Shadow(duration) - Alternative way to open Shadow (Bypasses the 'once only' shadow) </p>
<p><strong>Keyboard Shortcuts:</strong></p>
<p>X - Close<br>
S - Turn on the Shadow<br>
F - Turn off flashing </p>
<p><strong>Command:</strong></p>
<p><strong>Demos: </strong></p>
<p><a href="javascript:Shadow.CreateShadow()">Turn Shadow On</a></p>
<p><a href="javascript:Shadow.Pulse(5)">Flash Effect on Shadow for 5 seconds</a> - <strong>Note: </strong>Press F to turn off the flashing <em>Function to stop flashing: <strong>Shadow.clearFlash()</strong></em></p>
<p><a href="javascript:openConfirmationDialog();">Ask for confirmation</a></p>
<p><a href="javascript:createDialog('demoText')">Open up a dialog</a></p>
<p><a href="javascript:createDialogAjax('external.html')">Open up external document (Ajax)</a></p>
<p><strong>Note: </strong>If you see the same page all the time when you edit it, please delete the cache on your computer. </p>
<p>&nbsp;</p>
<hr noshade>
<p>Created by Peter Nguyen<br>
<em>Based on LightBox 2.0 </em><br>
See: <a href="http://www.dynamicdrive.com/forums" target="_blank">http://www.dynamicdrive.com/forums</a><br>
User: tech_support</p>
<div id="demoText" class="dialog">
<p>This is a dialog.</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam eget purus. Curabitur leo enim, accumsan eu, varius in, tincidunt eu, augue. Nulla auctor tellus vitae turpis. Cras sed elit. Suspendisse pulvinar nisi eget diam. Vivamus vehicula. Duis nec sapien sed sapien ultricies facilisis. Sed tellus. Phasellus facilisis est et ligula. Aliquam erat volutpat. Nunc sed velit vel arcu consectetuer sodales. Maecenas mattis lacinia mauris. Morbi dapibus iaculis ante. Aenean sed urna eget nulla molestie interdum. Nulla vitae ligula. Cras sollicitudin, orci id venenatis ullamcorper, magna tortor iaculis est, vel nonummy lacus leo in magna. Fusce vel nisl interdum eros imperdiet ullamcorper. Donec interdum, elit id porta scelerisque, dui leo gravida elit, non euismod tellus elit lobortis lorem. Sed risus lacus, ultrices vel, laoreet ut, gravida nec, eros. </p>
</div>

</body>
</html>


Demo: http://www.b3ta.cr3ation.co.uk/data/html/201shadowEffect.html

I still need to make the dialog in the center though.



Better, but you're still using strings instead of closures for that setTimeout.

I don't know what you mean there Twey.

jscheuer1
11-11-2006, 06:22 AM
If you are going the lightbox route on this, that has already been worked out -

Info:

http://particletree.com/features/lightbox-gone-wild/

Demo:

http://particletree.com/examples/lightbox/

Twey
11-11-2006, 01:38 PM
When one defines a function inside an existing scope, the function retains access to that scope and all variables defined within, even if it's later moved out of that scope. This is a much neater alternative to setting IDs for dynamically-created elements, especially since using setTimeout() or setInterval() with a string is really little better than eval(). http://jibbering.com/faq/faq_notes/closures.html has a good briefing on the subject.

tech_support
11-12-2006, 06:32 AM
If you are going the lightbox route on this, that has already been worked out -

Info:

http://particletree.com/features/lightbox-gone-wild/

Demo:

http://particletree.com/examples/lightbox/
That's based on the original Lightbox.

Plus I like the fancy transitions, like the fade in, fade out etc.