When a user closes a
, hide that
on all site pages

前端 未结 12 956
忘了有多久
忘了有多久 2020-12-15 02:49

I\'ve developed a couple of alert boxes that display on all site pages.

The user is able to close each box separately:

12条回答
  •  余生分开走
    2020-12-15 03:40

    Following on @Loading.. answer:

    the alert boxes always re-appear briefly on reload before disappearing. Any ideas?


    Why is this?

    The functions inside $(document).ready() will execute until the entire DOM is loaded. That's why the alerts are rendered, then as soon as the function runs, it hides them.


    Solution:

    You can initially hide your alerts with a class just to take advantage that the browser won't render the content until the CSSOM has been built.

    The class we are using is just setting the property display: none;.

    .hidden {
      display: none;
    }
    

    This will of course cause redraw in the browser. (see notes)

    Your logic is already showing the alert with

        if (localStorage.getItem('desiredTime') >= currentTime) {
          $('#alert-box-news').hide();
        } else {
          $('#alert-box-news').show();
        }
    

    Because using .show() will add an inline-style display: block; it will have a higher specificity than the .hidden class, showing the alert.


    jsFiddle


    Notes:

    • Using display: none; will push the content below the alert up or down. You can use other methods if you like, like visibility: hidden; or transform which is not in the scope of this answer.

    EDIT:

    An illustration will be presented below doing the following steps:

    • Demo counter increased to 20 seconds for testing.
    • We click to dismiss the alert and trigger the localStorage function, setting the desiredTime key.
    • After the key has been set, we refresh the browser and hit run several times to see if the key is working.
    • Finally, just to check that the key is indeed being set, we go to:

      DevTools (F12) -> Application Tab -> Local Storage -> jsFiddle shell.

    • Run is hit one more time, after the countdown has finished, showing the alert again.

    Illustration:


    We might need further details to solve the issue with this approach if it is not working live.

提交回复
热议问题