-2

I am making an age restriction for other people to use, but I want some HTML text to be invisible by this if statement. This is h3 text The HTML Text:

If you are reading this, you are over 18.

The JavaScript:

var user = prompt("Enter your age [NO LETTERS]: ");


if (user<18) {


document.write("<div style='font-family:Arial;font-size: 29px;''>Age restrictions have been enabled for this session.</div>");


alert("You are too young for this content, some restrictions might be activated.");
}
2

1 Answer 1

2
  • 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry your code did not work for me. But, I have solved the problem. Thank you for your help though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.