Please do not use document.write as it's only used for testing, it actually might reset the page.
There are only two possible outcomes, either a user is older than 18 or less. Use confirm() instead to eliminate redundant input.
If there's a lot of content that needs to be censored, hiding everything in JS is not a viable solution. A better way would be to only apply a specific class to body:
Javascript:
var message = "Are you older than 18?";
if(!confirm(message)) {
document.body.classList.add("nsfw");
// Inform the user that some content might be hidden.
}
Use CSS for design and layout and JS for logic. Assign class "sensitive" to all sensitive content:
HTML:
<body>
...
<span class="any-other-class">Hi</span>
<span class="sensitive any-other-class">If you are reading this, you are over 18.</span>
</body>
CSS:
body.nsfw .sensitive {
display: none!important;
}
This way, every element with class sensitive would be automatically hidden if the user is underage.
But wait! Maybe you want to store user's choice? Use Session Storage!
function agecheck() {
var key = "nsfw-preference"
var message = "Are you older than 18?";
// Remove nsfw class if it exists
document.body.classList.remove("nsfw");
// No preference data.
if(window.sessionStorage.getItem(key) === null) {
// Ask the user:
if(!confirm(message))
window.sessionStorage.setItem(key, "true");
else
window.sessionStorage.setItem(key, "false");
}
// If the user is underage
if(window.sessionStorage.getItem(key) == "true") {
document.body.classList.add("nsfw");
// Inform the user some content might be hidden. Avoid alerts()!
}
// User isn't underage
else if(window.sessionStorage.getItem(key) == "false") {
// Inform the user if needed.
}
}
Call this function once when the DOM/page has loaded.