DevLiv DevLiv - 4 months ago 6
CSS Question

Image won't show on onLoad function

I am working on a website where the person entering it, has to be prompted with an image on load. This image is just like any image, but apparently it won't show. I have an onLoad function and an onClick function, so that once the image is showing, the user can just click the image and then in theory it should disappear.
I have a variable, which from the start is "false" and then once the page is loaded, it is supposed to change to "true" and then once the image is clicked it is supposed to turn "false" again. This way it should be fairly easy to control whether the image is showing or not.

I am not completely sure what is wrong as everything seems right to me.

Here is my code.

HTML:

<head>

<script type="text/javascript">

var popUP = false;

function popUpOpen(){
var popUp = true;
}

function popUpClose() {
var popUp = false;
}

if (popUp = true) {
document.getElementById('popUpStart').style.visibility='visible';
} else {
document.getElementById('popUpStart').style.visibility='hidden';
}

</script>

</head>

<body onload="popUpOpen()">

<img id="popUpStart" src="popUpOnLoad.png" style="visibility:hidden" onclick="popUpClose()"/>

</body>


CSS:

#popUpStart{
position: absolute;
left: 50%;
top: 50%;
margin-left:-325px;
margin-top:-220px;
z-index: 3;
}


UPDATE:




The issue has been solved and here underneath I have attached my new code, incase anyone ever has the same problem. Big thank you to all of you.

HTML:

<head>

<script type="text/javascript">

var popUP = false;

function updateImage()
{
if (popUp === true) {
document.getElementById('popUpStart').style.visibility='visible';
} else {
document.getElementById('popUpStart').style.visibility='hidden';
}
}

function popUpOpen(){
popUp = true;
updateImage();
}

function popUpClose() {
popUp = false;
updateImage()
}


</script>

</head>

<body onload="popUpOpen()">

<img id="popUpStart" src="popUpOnLoad.png" style="visibility:hidden" onclick="popUpClose()"/>

</body>

Answer

Your real problem is that the code that checks if popUp is true or not is run exactly once, before onLoad even happens. You can change the value of popUp, but that won't change the visibility of the image.

You want something like:

var popUp = false;

function updateImage()
{
    if (popUp === true) {
        document.getElementById('popUpStart').style.visibility='visible';
    } else {
        document.getElementById('popUpStart').style.visibility='hidden';
    }
}

function popUpOpen(){
    popUp = true;
    updateImage();
}

function popUpClose() {
    popUp = false;
    updateImage()
}

Note that the changes to removing "var" in the functions, and using "===" instead of "=" in your comparison.