Home > front end >  JQuery/CSS Hide cookie banner
JQuery/CSS Hide cookie banner

Time:09-13

I have a simple cookie banner:

  <div id="cookie-consent" >
      <span>This site uses cookies to enhance user experience. see <a href="..." target="_blank" >Privacy policy</a> </span>
      <div  >
        <button id="cookie-ok-button" >I'm aware</button>            
      </div>          
    </div>

I use jquery to hide the banner when users click the ok button:

$(document).ready(function()
{

if (window.localStorage.getItem('accept_cookies'))
{
    $('#cookie-consent').css('display','none');
}

$("#cookie-ok-button").click(function()
{              
    $('#cookie-consent').fadeOut();
    $('#cookie-consent').css('display','none');
    window.localStorage.setItem('accept_cookies', true);              
}); 
});

It works but sometimes on Chrome the banner appears before rapidly disappearing. Is there any modification I can do to avoid such behavior.

CodePudding user response:

Instead of showing the banner by default and conditionally hiding it, hide it by default and conditionally show it.

For example:

<div id="cookie-consent"  style="display:none;">
  <!--- etc. -->
</div>

And:

$(document).ready(function()
{
  if (!window.localStorage.getItem('accept_cookies'))
  {
    $('#cookie-consent').css('display','block');
  }

  // etc.
});
  • Related