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.
Related
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 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/
I am struggling with using cookie along with javascript in webview android.
I have one HTML page which is located in sdcard data. This html file consist of javasript and cookie. I need to load this html file in webview and webview needs to respond to javascript as well as cookie.
Work done so far:-
Enabled javascript for webview
WebView1.getSettings().setJavaScriptEnabled(true);
Also tried to enable cookie using CookieManager
CookieManager.getInstance().setAcceptCookie(true);
Doing this, webview respond to javascript but not cookies. Any Idea how to solve this problem?
HTML file is as follows
<!DOCTYPE html>
<html>
<head>
<script>
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;
}
function getCookie(cname) {
var res = "No Cookie!";
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) != -1) res = c.substring(name.length, c.length);
}
document.getElementById('txt').innerHTML = res;
}
</script><noscript>No JavaScript!</noscript>
</head>
<body onload="setCookie('id', 'Cookie is working properly!', '1');">
<p id="txt"> </p>
<center>
Next Page
</center>
</body>
</html>
When i open this File in browser, its working fine. If someone wants to open this file in browser then please use the following url https://www.ypsid.com/demo/test/test-1.html
If you are using Android Lollipop i.e. SDK 21, then:
CookieManager.getInstance().setAcceptCookie(true);
won't work. You need to use:
CookieManager.getInstance().setAcceptThirdPartyCookies(true);
I ran into same issue and the above line worked as a charm.
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>