Hiding a div once user has closed it

I have got a div that is on each page of the website, and is ‘hidden’ once the user ‘closes’ it - but I want it to stay hidden if the user were to navigate to another page… could someone please help me go about this?


.alert {
    padding: 1em 3em;
position:relative;
    background-color: #ff9800;
    color: white;
	text-align:center;
	font-size:.95em;
	
	opacity: 1;
    transition: opacity 0.6s; /* 600ms to fade out */
}
.closebtn {
	position:absolute;
	top:1em;
	right:1em;
    color: white;
    font-weight: bold;
	display: block;
    
    font-size: 22px;
    line-height: 20px;
    cursor: pointer;
    transition: 0.3s;
}
.closebtn:hover {
    color: #414042;
}


<!-- HTML -->
<div class="alert">
  <span class="closebtn">&times;</span> 
  Our office will be closed from Friday 23rd December and re-open Wednesday 11th January.
</div>



$(document).ready(function() {
// Get all elements with class="closebtn"
var close = document.getElementsByClassName("closebtn");
var i;
	
// Loop through all close buttons
for (i = 0; i < close.length; i++) {
    // When someone clicks on a close button
    close[i].onclick = function(){

        // Get the parent of <span class="closebtn"> (<div class="alert">)
        var div = this.parentElement;

        // Set the opacity of div to 0 (transparent)
        div.style.opacity = "0";

        // Hide the div after 600ms (the same amount of milliseconds it takes to fade out)
        setTimeout(function(){ div.style.display = "none"; }, 600);
    }
}
	
});

Hi there,

To remember user preferences in this way, you’d use localstorage.

Basically, when the user hides the notification div, save a key/value pair to local storage:

localStorage.setItem('showNotification', false);

Which you check for when deciding whether to display the notification:

if(showNotification){
  // display notification here
}

Make sense?

1 Like

Hi Pullo,
Thanks for your guidance. I’ve been trying to add the localstorage code to my existing function but am a little unsure of the if statement part… sorry I am a total novice at javascript. (FYI - I also changed the .alert div to .alertMsg as to avoid confusion with JS alert method.)

$(document).ready(function() {
// Get all elements with class="closebtn"
var close = document.getElementsByClassName("closebtn");
var i;
	
// Loop through all close buttons
for (i = 0; i < close.length; i++) {
    // When someone clicks on a close button
    close[i].onclick = function(){

        // Get the parent of <span class="closebtn"> (<div class="alertMsg">)
        var div = this.parentElement;

        // Set the opacity of div to 0 (transparent)
        div.style.opacity = "0";

        // Hide the div after 600ms (the same amount of milliseconds it takes to fade out)
        setTimeout(function(){ div.style.display = "none"; }, 600);
		
	// When user hides div, save a key/value pair to local storage
	localStorage.setItem('alertMsg', false);
		
	// Check when deciding whether to display div
	if(alertMsg){
  	div.style.display = "none";
	} else { 
    div.style.display = "none";
}
}
}
	
});

Hey,

Sure thing :slight_smile:
First off, let’s tidy up the code a bit. A few points:

  • You can lose the call to $(document).ready() if you include your script at the foot of the page before the closing </body> tag. If you place it here, the document will be ready by default.
  • You are obviously including jQuery, so why not use it. There is no need to use getElementsByClassName, rather $(".closebutton"); will do instead.
  • Why are you selecting this by class? Is there more than one notification on the page? If not, consider using an ID instead.

Anyway, this means you can replace all of your code with this:

$('.closebtn').on('click', function(){
  $('.alert').fadeOut('slow');
});

Note: you’ll need to remove the following CSS rules from .alert:

opacity: 1;
transition: opacity 0.6s;

Now, on with the local storage functionality:

const showMsg = localStorage.getItem('showMsg');

if(showMsg === 'false'){
  $('.alert').hide();
}

$('.closebtn').on('click', function(){
  $('.alert').fadeOut('slow');
  localStorage.setItem('showMsg', 'false');
});

And that should do what you want.

Here’s a demo. I’ve added a link to clear the key from localStorgare. After clicking it, you’ll need to re-run the demo.

1 Like

Thanks for your patience, in response to your points:

  • I have scripts located in an external file which is why I was using the $(document).ready()
  • Ok thanks for the advice - I was using a tutorial… I’ll keep that tip in mind in the future.
  • Yes, I am using class rather than id as there could be more than 1 notification.

I implemented your code but the issue I am now facing is the message flickers from ‘visible to hidden’ as I navigate from page to page. (fyi - the notification is located in the header.)

Hey,

Same principle still applies. If you reference the external file just before the closing body tag, you can do away with $(document).ready()

No problem, just invert the logic. Hide the message by default and then show it if the user hasn’t dismissed it.

const showMsg = localStorage.getItem('showMsg');

if(showMsg != 'false'){
  $('.alert').show();
}

$('.closebtn').on('click', function(){
  $('.alert').fadeOut('slow');
  localStorage.setItem('showMsg', 'false');
});

I updated my demo.

Hi again,

Just to be complete here is a more robust solution which works in such a way that people with JavaScript disabled will still see the div.

My previous solution was using CSS to hide the element and (based on a value from localStorage) JS to display it again.

A better way would be to use JS to add a class of js (for example) to the html element and use this class to target the element in question. So instead of:

.alert {
  ...
  display: none;
}

you would have:

.js .alert {
  display: none;
}

This way, if JS is disabled, the js class won’t be applied and the element will always be shown. But if JS is enabled, the element will be hidden and you will avoid that annoying flash on page load.

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Hide div example</title>
    <script>
      document.documentElement.classList.add('js');
    </script>
    <style>
      .js .alert {
        display:none
      }
      .alert {
        padding: 1em 3em;
        position:relative;
        background-color: #ff9800;
        color: white;
        text-align:center;
        font-size:.95em;
      }
      .closebtn {
        position:absolute;
        top:1em;
        right:1em;
        color: white;
        font-weight: bold;
        display: block;
        font-size: 22px;
        line-height: 20px;
        cursor: pointer;
        transition: 0.3s;
      }
      .closebtn:hover {
        color: #414042;
      }
    </style>
  </head>
  <body>
    <div class="alert">
    <span class="closebtn">&times;</span>
      Our office will be closed from Friday 23rd December and re-open Wednesday 11th January.
    </div>

    <p>
      <a href="#">Clear storage</a>
    </p>

    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
      const showMsg = localStorage.getItem('showMsg');

      if(showMsg !== 'false'){
        $('.alert').show();
      }

      $('.closebtn').on('click', function(){
        $('.alert').fadeOut('slow');
        localStorage.setItem('showMsg', 'false');
      });

      $('a').on('click', function(e){
        e.preventDefault();
        localStorage.setItem('showMsg', null);
      });
    </script>
  </body>
</html>
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.