Heigo
Heigo

Reputation: 946

Show/Hide HTML5 element based on localStorage value

In the below code, I have a button with id='questionaire'. When a user clicks on the button I want to save the event to the local storage so that the button would not be shown next time the user opens the page.

I managed to do this earlier with window.onload=function(){} script but then the button appeared for a moment and then disapeared, if it had been clicked. This didn't look nice.

<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Storage?</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>

<body>
    <?php
        echo "
        <form>
            <input type='button' class='button' value='Question' id='questionaire'>
        </form>
        ";

        echo "<script type='text/javascript'>
                document.getElementById('questionaire').onclick = function() {
                    localStorage.clicked = 'true';
                }
            </script>";
... <More HTML code> ...
    ?>      
</body>
</html>

Upvotes: 0

Views: 970

Answers (1)

Nikolaj Zander
Nikolaj Zander

Reputation: 1270

maybe you should always hide the button and show it when it was not clicked before.

when its hidden in the first place you won't get the flashing button for users who have already clicked it!

This does not help. As this button is the topmost element in the page and if I don't show it at the first place and then show it after the page has loaded then all the other elements move. I have edited the question

wrap the button inside a div which has the dimensions of the button! then nothing moves

<div style="width: XXpx; height: XXpx; display: inline-block;">
    <input type='button' class='button' value='Question' id='questionaire'>
</div>

your problem is "the flash of unstyled content" your page moves when showing or hiding the button on load with js, unless you hide everything until your manipulation is done!

you can try to google for "avoid flash of unstyled content" or read this: Avoid Flash of unstyled content

Upvotes: 1

Related Questions