Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JQuery/CSS Hide cookie banner

I have a simple cookie banner:

  <div id="cookie-consent" class="cookie-consent">
      <span>This site uses cookies to enhance user experience. see <a href="..." target="_blank" class="ml-1 text-decoration-none">Privacy policy</a> </span>
      <div  class="mt-2 d-flex align-items-center justify-content-center g-2">
        <button id="cookie-ok-button" class="cookie-allow-button mr-1">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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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" class="cookie-consent" style="display:none;">
  <!--- etc. -->
</div>

And:

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

  // etc.
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading