Display a one-time button only

时间:2015-07-28 15:58:54

标签: javascript html css

I couldn't get this right. I'm doing my business website for our project this coming finals. What I wanted to do is that when the user clicks the homepage for the first time (home.html), it will load a centered button on the middle of the page and the main content is opaque. I tried an IF statement for JS but I couldn't get the logic. Everytime I click the homepage, it continues to load the button. I just wanted it to load once whenever the home.html file is opened.

<style>
    body {
        font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;
        margin: 3%;
        margin-bottom: 0;
        font-size: 13px;
    }
    ul#features li::before {
        content: "\2713    "; /* inserts a check mark */
        color: green;
        font-weight: bold;
        font-size: 14px;
    }
    ul#features {
        list-style-type: none;
    }
    #textOpener {
        display:none;
        position: absolute;
        /* all four properties tries to center the button in the middle */
        top: 40%;
        bottom: 40%;
        left: 40%;
        right: 40%;
    }
    div#mainContent {
        opacity: 0.2;
        visibility: visible;
        background-color: gray;
    }
</style>
</head>

<body>

<script>
if(!localStorage["firstLoad"]) {
    document.getElementById("textOpener").style.display = "block";
    localStorage["firstLoad"] = true;
}
</script>

<p id="textOpener"><a href="#.html" class="button" onclick="showWebpage(i)">Proceed to site</a></p> <!-- this would show up first before the rest of the content -->
<div id="mainContent">

jsfiddle

2 个答案:

答案 0 :(得分:2)

Here's how you could do it with localStorage:

if(!localStorage["firstLoad"]) {
    document.getElementById("textOpener").style.display = "block";
    localStorage["firstLoad"] = true;
}

In the CSS set display:none; on the textOpener div:

#textOpener {
    display:none;
    position: absolute;
    /* all four properties tries to center the button in the middle */
    top: 40%;
    bottom: 40%;
    left: 40%;
    right: 40%;
}

This code checks to see if there's a key called firstLoad in localStorage, if there's not, then the button is displayed and the key is created(so that the next time the person visits the site, providing they haven't cleared their cache, the code that displays the button will not fire).

JSFiddle

答案 1 :(得分:-1)

Well, the script is executed before the dom is ready.

$(document).ready(function(){
    //do your code here.
})

Otherwise, document.getElementById("textOpener") returns nothing.