I want a alert at the bottom of the screen that says that the website is using cookies (and it only needs to be shown to new users). It needs to stay at the bottom if you scroll down too. I don't know how to do it, because I am a self-learning person and I am just starting learning how to code. Thanks for the help.
Asked
Active
Viewed 3,391 times
1 Answers
1
Part 1 : HTML & CSS
We need to add the alert panel into the bottom of the page. for styling this panel we should use CSS. this panel also has the confirmation button. if user click button we set the cookie to browser and never show the panel again.
<div class="bottom" id="alert">
this website use cookies
<button onclick="accpetCookie()">
click here for accpet cookie
</button>
</div>
<div class="scroll">
website content
</div>
for setting style we create CSS class
.bottom {
position: fixed;
bottom: 0;
width: 100%;
background: #ccc;
color: #fff
}
.scroll {
min-height: 1500px;
}
Part 2 : Javascript
<script>
// if user has already checked the confirmation button
// the alert panel should be hidden.
if (getCookie('accepted') === 'yes') {
document.getElementById("alert").style.display = "none";
}
// user clicks the confirmation -> set the 'yes' value to cookie and set 'accepted' as name
function accpetCookie() {
setCookie('accepted', 'yes', 100);
}
// code from :http://stackoverflow.com/a/4825695/191220
// set cookie method
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
// get cookie method
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
</script>
check the Jsfiddle page for live demo.
Mironline
- 2,654
- 7
- 33
- 58
-
@Julian have you added the `` tag in html page ?. please delete your second post(answer), for adding note to any answer in this website you can use comment section – Mironline Oct 20 '16 at 14:59
-
I did it again and now there is an other problem. If I click to accept, it will come back if I refresh the page and it creates no cookie (I can't see one in my cookie inspector). – Julian Oct 20 '16 at 21:59
-
The default state of the "bottom" div should be `display:none` in the CSS to prevent it from flickering when page loads. Change `if (getCookie('accepted') === 'yes') { document.getElementById("alert").style.display = "none"; }` to `if (getCookie('accepted') !== 'yes') { document.getElementById("alert").style.display = "block"; }` – Victor Stoddard Feb 15 '19 at 22:03