Hide block (and remember it) with JavaScript and cookies?

I want to implement a demo hidden div block on my site, like on stackoverflow.com - at a time when the user wants to hide it by clicking the "X" button. Maybe you already have a ready-made solution? I am not a verse in Javascript and will be very grateful for your help!

A photo:

+6
source share
2 answers

This is a simple working example without using any external library. You can improve it with animation / design. Also, these cookie functions can be very simplified, but you can use it in the future to set more than just a boolean value. UPDATE: I added functon to display the popup again (for greater debugging).

<html> <head> <script type="text/javascript"> function setCookie (name, value, expires, path, domain, secure) { document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); } function getCookie (name) { var cookie = " " + document.cookie; var search = " " + name + "="; var setStr = null; var offset = 0; var end = 0; if (cookie.length > 0) { offset = cookie.indexOf(search); if (offset != -1) { offset += search.length; end = cookie.indexOf(";", offset); if (end == -1) { end = cookie.length; } setStr = unescape(cookie.substring(offset, end)); } } if (setStr == 'false') { setStr = false; } if (setStr == 'true') { setStr = true; } if (setStr == 'null') { setStr = null; } return(setStr); } function hidePopup() { setCookie('popup_state', false); document.getElementById('popup').style.display = 'none'; } function showPopup() { setCookie('popup_state', null); document.getElementById('popup').style.display = 'block'; } function checkPopup() { if (getCookie('popup_state') == null) { // if popup was not closed document.getElementById('popup').style.display = 'block'; } } </script> </head> <body onload="checkPopup();"> <div id="popup" style="display:none">Hello! Welcome to my site. If you want to hide this message then click <a href="#" onclick="hidePopup(); return false;">[x]</a></div> <div>Some static text here.</div> <div>Bring me <a href="#" onclick="showPopup(); return false;">back</a> my popup!</div> </body> </html> 
+3
source

Alternative:

 -> Using localStorage instead of cookie<br/> -> LocalStorage never expire until they delete personal data on browser<br/> -> jQuery Library for easy customization on future<br> -> re-display hidden remembered content<br> -> jsfiddle.net/axcelleria/41t76s8q/<br> 

And I remember you also need mobile detection ...? Here's the edit:

To detect mobile devices:
jsfiddle.net/axcelleria/nmosxbgm/

0
source

Source: https://habr.com/ru/post/903986/


All Articles