I've been trying to add a EU cookie policy banner to my website. The javascript code below inserts the banner (once I add a small bit of styling) but when I click on the "x" to close the banner and hopefully hide it for future visits, nothing happens. The banner doesn't disappear.
Can anyone tell me why this isn't working? Javascript is not my strong point!
//Cookie banner
var dropCookie = true; // false disables the Cookie, allowing you to style the banner
var cookieDuration = 14; // Number of days before the cookie expires, and the banner reappears
var cookieName = 'complianceCookie'; // Name of our cookie
var cookieValue = 'on'; // Value of cookie
function createDiv(){
var bodytag = document.getElementsByTagName('body')[0];
var div = document.createElement('div');
div.setAttribute('id','cookie-law');
div.innerHTML = '<p>Our website uses cookies. By continuing we assume your permission to deploy cookies, as detailed in our privacy and cookies policy. <a class="close-cookie-banner" href="javascript:void(0)" onclick="removeMe()"><span>X</span></a></p>';
// Be advised the Close Banner 'X' link requires jQuery
// bodytag.appendChild(div); // Adds the Cookie Law Banner just before the closing </body> tag
// or
bodytag.insertBefore(div,bodytag.firstChild); // Adds the Cookie Law Banner just after the opening <body> tag
document.getElementsByTagName('body')[0].className+=' cookiebanner'; //Adds a class tothe <body> tag when the banner is visible
createCookie(window.cookieName,window.cookieValue, window.cookieDuration); // Create the cookie
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
if(window.dropCookie) {
document.cookie = name+"="+value+expires+"; path=/";
}
}
function checkCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)===' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
window.onload = function(){
if(checkCookie(window.cookieName) !== window.cookieValue){
createDiv();
}
};
function removeMe(){
var element = document.getElementById('cookie-law');
element.parentNode.removeChild(element);
};
Thanks!
The function removeMe is undefined in the current scope of the onclick handler. To fix this, you should replace this line function removeMe() { with window.removeMe = function removeMe() {.
Live example (with formatted code): https://jsfiddle.net/xnhpzto8/1/
Related
This is popup-up div and it's working good. But it's load every time after I refresh the browser and what I want? I need this only one time when user open my website.
Any idea how to control this. FYI this is magento-2 popup.
require(
[
'jquery',
'Magento_Ui/js/modal/modal'
],
function(
$,
modal
) {
var options = {
type: 'popup',
responsive: true,
innerScroll: true,
//title: 'popup modal title',
buttons: [{
text: $.mage.__('Continue'),
class: '',
click: function() {
this.closeModal();
}
}]
};
var popup = modal(options, $('#popup-modal'));
$('#popup-modal').modal('openModal');
}
);
$(document).ready(function() {
$(".actions").click(function() {
alert("The paragraph was clicked.");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup-modal">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<h1>Subscribe for Our <span>exclusive offer</span></h1>
<p>Be the first to know about new arrivals exclusive offers and promotions</p>
<?php echo $block->getLayout()->createBlock('Magento\Newsletter\Block\Subscribe')->setTemplate('subscribe.phtml')->toHtml();?>
</div>
Since normal JavaScript (actually NodeJS works server side) only handles client side operations (i.e. your browser), it cannot "remember" that a pop-up was shown once after a page reload. JavaScript need some kind of help for it. The point is that you do not need to care about the JavaScript part that much, but more about PHP in this case.
1.: You could save this information in a cookie, which could save the information if a pop-up was shown once. Only downside is that when you clear your browser cookies, the pop-up would come up again.
2.: You could you the MySQL Database to store this information permanently. Therefore you would need your own custom module though. Good examples can be found in the search.
My recommendation is to create your own module if you haven't already and extend the database table for customers with your information.
Hope this helps you to get in the right direction.
Add cookie there are some functions related to CREATE ,READ and REMOVE cookie please find this fiddle or below snippet for more information.
I hope it'll help you
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires=" + date.toUTCString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
$(function(){
if(readCookie('OnlyONCE') == null)
{
$('#popup-modal').modal('openModal');
createCookie('OnlyONCE','true',7);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cookie" style="display:none;">POP UP
<a href="#" class="cookie-close">
<span class="icon" onclick='onClose()'>X</span>
</a>
</div>
I have a countdown clock here that resets when the page is refreshed. I would appreciate it if someone could help me?
I have included the script below.
<script type="text/javascript">
var ticker = function() {
$("#ticker").css({
left: "120%"
}).animate({
left: "-420px"
}, 6000, 'linear', ticker);
}
ticker();
</script>
Considering you need it to be "running" while user is not in the page, I will point out that Javascript is a client side scripting language Javascript code is run in local side i.e its interpereted by the browser. This makes hard to "keep" track of things if the user refreshes the page until unless you have have stored them somewhere. There can be different approaches for your solution such as:-
LocalStorage
Cookies
Server Side Clock
You can use either of the three. You can use localstorage to save the clock end time and whenever the user refreshes the page get the value from localstorage and start you clock accordingly. Similar approach can be used with cookies. Or you can use some server side code to initialize the clock whenever your page loads the server will set start the clock accordingly. but there can be some lag as mentioned above in comments. So the best approach in my opinion, if you just want to use javascript, would be to use cookies/localstorage to save the exact time when the countdown will reach value 0. So everytime you load into the page, you can get the stored value , and get how long is missing yet and set the clock accordingly.
Some coding
Create a cookie with expiration time:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Get a cookie:
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Sample of use:
function checkCookie() {
var clock = getCookie("clock");
if (clock != "") {
//You already have the cookie. Make use of it
} else {
//You still dont have the cookie, create new clock, and save cookie
//i.e.
setCookie("clock", new Date().getTime().toString(), 365);
}
}
I've created a function to show a cookie policy in my website. The cookie is stored across the website and is working fine but the show/hide part of it only works in the index file and not in all the other pages and I can't understand why.
The function is as follows:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
(function() {
var InfoCookieCont = jQuery('#info_cookie');
var InfoCookieDiv = jQuery(".ok-cookie");
InfoCookieDiv.click(function() {
createCookie('infoCookie','true',365)
InfoCookieCont.removeClass("cookie-visible").addClass("cookie-hidden");
});
var InfoCookie = readCookie("infoCookie");
if (!InfoCookie) {
InfoCookieCont.removeClass("cookie-hidden").addClass("cookie-visible");
}
})();
This installs a cookie from my website and until you click the .ok-cookie button, the #info_cookie will keep showing up on top of the page thanks to the .cookie-visible class.
This works fine on index.php, but not in the other pages. In other pages it keeps the .cookie-hidden class even if I didn't click the ok-cookie button in the previous page.
The .js file where this function is, is of course included in every page of my website.
The live website is: www.valeriopierbattista.com
thanks for your help, im going crazy!
You've got some other js errors on the other pages which are killing the js script.
I am using the following script to redirect visitors of a page to another page on first visit, however it loads the index.html page first, and then triggers the redirect. Can anyone point me in the direction of how I might trigger this script before the page loads?
<script type="text/javascript">
function redirect(){
var thecookie = readCookie('doRedirect');
if(!thecookie){window.location = '/coming-soon.html';
}}
function createCookie(name,value,days){if (days){
var date = new Date();date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name){
var nameEQ = name + "=";var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++){
var c = ca[i];while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);}
return null;
}
window.onload = function(){redirect();createCookie('doRedirect','true','1');}
</script>
(the JS snippet used here was taken from Stack Overflow: JS to redirect to a splash page on first visit)
Thanks.
You don't need to wait while window is loaded:
<script type="text/javascript">
var thecookie = readCookie('doRedirect');
if(!thecookie) {
createCookie('doRedirect','true','1');
window.location = '/coming-soon.html';
};
function createCookie(name,value,days){
// do work
}
function readCookie(name){
// do work
}
</script>
Also Petr B. said right thing: server-side redirect is better in your case.
Try this How to Run a jQuery or JavaScript Before Page Start to Load.
Btw. if you want redirect without displaying page you must use php with cookies check.
I have some script, written in Javascript, that show progress of loading site elements. I put this script on index.html file, so it runs only on main page. It works perfectly fine, but now it show progress when you land on index.html and also when you come back to main page from subpage which is my problem because main page is already cached and it's waste of time.
My question is: How to run script only when user land on page, not when he come back from subpage?
Try cookies to control when/when not to execute Javascript.
Create a cookie when the user hits index.html for the first time. Check for the cookie and only run the script if the cookie hasn't been set.
if(!isset($_COOKIE['something'])) {
// run your loading script;
setcookie('something','someValue');
}
Just be sure you have the above code before sending any output to the browser.
In addition to cookies you can use document.referrer:
<script>
if(document.referrer &&
document.referrer.indexOf("yoursite.com") == -1)
{
// Page loading process script goes here.
}
</script>
<html>
<head>
..
</head>
<body onload="doStuff()">
...
<script type="text/javascript" language="JavaScript">
//<![CDATA[
function doStuff(){
//check condition
if (readCookie('checkFirstTime')!=null) return;
//otherwise set the flag && do your thing
createCookie('checkFirstTime','yep',1);
alert("Welcome home Yo!");
...
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
//]]>
</script>
...
</body>
</html>