Search code examples
javascriptjqueryif-statementonloadcover

If correct answer, body loads! Any ideas?


Guys I can't find a way to do this on my website. I need something the covers the entire website (can be an div with black background or an image, whatever) and a question comes up before the body loads.

The person types the answer on an input and submit, if the answer is correct (the answer can be visible on html) then body loads, or the div with black background covering the page goes away, showing the website.

Anything that covers the website and only loads the body after typing a certain word. Can anybody help me? :(


Solution

  • See http://jsfiddle.net/AMVA3/

    You can add the following code to the <head>, so it will be executed before the <body> is loaded:

    var ask=prompt('Write answer here:',"answer");
    if(ask!="answer"){
        //If the answer is wrong, we stop the document's loading
        if(window.stop){
            window.stop();
        }else if(document.execCommand){
            document.execCommand('Stop');
        }else{
            document.write('<!--');
        }
    }
    

    So, while you are asking the question, the page is only white because the body has not been loaded. If the answer is right, the document continues loading. If not, it stops loading.

    Note: I have taken the codes that stops document's loading from How to stop page load in html static page

    Edit:

    If you want to alert "wrong answer!", just add it after checking if it's wrong.

    See it here: http://jsfiddle.net/AMVA3/1/

    var ask=prompt('Write answer here:',"answer");
    if(ask!="answer"){
        alert("Wrong answer!!");
        if(window.stop){
            window.stop();
        }else if(document.execCommand){
            document.execCommand('Stop');
        }else{
            document.write('<!--');
        }
    }
    

    Edit 2:

    It's weird that the previous code's alert doesn't work for you. For me it works.

    But if you want to avoid loading only a div, you can use comments.

    See it here: http://jsfiddle.net/AMVA3/3/

    HTML:

    <div class="a">
        You should se me
    </div>
    <div id="cover"></div>
    <script type="text/javascript">
    var wrongAnswer=prompt('Write answer here:',"answer")!="answer";
    document.getElementById('cover').style.display='none';
    if(wrongAnswer){
        alert("Wrong answer!!");
        document.write('<!--');
    }
    </script>
    <div class="a hide">
        If you see me, you have written the right answer!
    </div>
    <script type="text/javascript">
    if(!wrongAnswer){
        document.write('<!-- ');
    }
    </script>
    -->
    <div class="a">
        You should see me too
    </div>
    

    CSS:

    #cover{position:fixed;top:0;left:0;height:100%;width:100%;
        background:yellow;/* Set it to the color that you want */
    }