<script type="text/javascript">
function WorldwideSellingModelCookie(){
days=7;
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'WorldwideSellingModelCookie=Accepted; expires=' + myDate.toGMTString();
}
function CheckCookies(){
var worldwideSellingCookie = getCookie("WorldwideSellingModelCookie");
if (worldwideSellingCookie == "Accepted")
{
jQuery(".alert-worldwide").hide();
}
}
CheckCookies();
</script>
Hi,
The cookie is being created, I am just unsure how to get my if statement to work within my CheckCookies function so that it hide a div on the page?
I am recieving the following console error:
Uncaught ReferenceError: getCookie is not defined
Can anyone advise what I am doing wrong?
Thanks
UPDATE:
<script type="text/javascript">
function WorldwideSellingModelCookie(){
days=7;
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'WorldwideSellingModelCookie=Accepted; expires=' + myDate.toGMTString();
}
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 "";
}
function CheckCookies(){
var worldwideSellingCookie = getCookie("WorldwideSellingModelCookie");
if (worldwideSellingCookie == "Accepted")
{
jQuery(".alert-worldwide").hide();
}
}
CheckCookies();
</script>
Just added the function to check the cookie and seems to be working now, however the div appears for a split second before hiding. Is there any way to stop this from happening?
These are the functions I use to add, get, or clear cookies in JavaScript.
/* function creates cooke with random key */
function setCookie(inputs) {
/* cookie name */
var name = (inputs[0]) ? inputs[0] : "key" + document.cookie.length;
/* cookie expire in 120 seconds */
var date = new Date();
date.setTime(date.getTime() + (120 * 1000));
var expires = "; expires=" + date.toGMTString();
/* sets cookie */
document.cookie = name + "=" + inputs[1] + expires;
};
/* get the cookie based on input */
function getCookie(input) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var name = cookies[i].split('=')[0].toLowerCase();
var value = cookies[i].split('=')[1].toLowerCase();
if (name === input) {
return value;
} else if (value === input) {
return name;
}
}
return "";
};
/* destroy me cookies (well only delete javascript cookies) */
function clearCookies(elements) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf('=');
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
$(elements[0]).val('');
$(elements[1]).val('');
$(elements[2]).val('');
$(elements[3]).html('No Cookie');
};
Also this is a good Document.cookie MDN
Related
I am trying to set the JS cookie if a specific class exists in a document. The cookie script is working but it's not applying to the class match logic.
Code:
(function( $ ) {
'use strict';
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*1000*60*60*24));
var expires = "expires=" + d.toGMTString();
window.document.cookie = cname+"="+JSON.stringify(cvalue)+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var cArr = window.document.cookie.split(";");
for(var i=0; i<cArr.length; i++) {
var c = cArr[i].trim();
if (c.indexOf(name) == 0){
return c.substring(name.length, c.length);
}
}
return "";
}
function deleteCookie(cname) {
var d = new Date();
d.setTime(d.getTime() - (1000*60*60*24));
var expires = "expires=" + d.toGMTString();
window.document.cookie = cname+"="+"; "+expires;
}
$(document).ready(function(){
setTimeout(function(){
var ele = document.getElementsByTagName('div');
for(var i=0;i<ele.length;i++){
var classes = ele[i].getAttribute('class');
var fclass = "smcx-iframe-container";
console.log(classes);
if(classes = fclass){
var cookieval = getCookie('device-t-ban');
if( cookieval === "" ){
var fp = new Fingerprint({
canvas: true,
ie_activex: true,
screen_resolution: true
});
var uid = fp.get();
setCookie('device-t-ban',uid,1);
console.log('no cookie!');
console.log(getCookie('device-t-ban'));
}else if(cookieval != ""){
$(".smcx-iframe-container").html("<div class='tryagain'><p>Try again in 24 hours!</p></div>");
console.log('yes cookie!');
console.log(getCookie('device-t-ban'));
}
} else {
exist = 'class not available'
}
}
}, 3000);
});
})( jQuery );
I am unable to figure out why it's not working. It seems something to do with the class match.
Thanks in advance,
Is it possible to create a session number of page view/visit like PHP, but in JavaScript?
$_SESSION['views'] = 0;
Is it possible to keep track of the number even when user quite the page and get back again?
You could use Cookies. On visit get the cookie and increment it by 1. Or set it to 1 if it doesn't exist
Example:
<p id="yolo"> </p>
<script>
var numberOfVisits = function getCookie('numberOfVisits');
if (numberOfVisits == "")
{
setcookie('numberOfVisits', 1, 100);
}
else
{
numberOfVisits++;
setcookie('numberOfVisits', numberOfVisits, 100);
}
document.getElementById('yolo').innerHTML = getCookie('numberOfVisits');
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
function setcookie(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=/";added
}
</script>
If you only need the data on the client side then use
window.localStorage, it stores data with no expiration date on the client side and it does not send it to the server on every request like cookies, as explained here.
<script>
var varname = "VISIT_COUNTER";
if (localStorage.getItem(varname) === null) {
localStorage.setItem(varname, 1);
} else {
var visits_count = parseInt(localStorage.getItem(varname)) + 1;
localStorage.setItem(varname, visits_count);
console.log("Total visits: " + visits_count);
}
</script>
What I want is to compare current url with my cookie array which would contain all the URL's a user has visited so it would compare that whether the array contains the current link or not so if not it would push that new link to the array and would again recreate the cookie with the new array which would contain the new pushed link so what I am facing right now is that everytime the if function which checks for the unique link always comes true I am not sure that what's the problem?
Can you people please have a look over it :
<script type="text/javascript">
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
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);
}
var url = window.location.href;
var pathname = new URL(url).pathname;
var jsonObj = [];
//jsonObj.push("test");
var x = readCookie('vid_cookies');
if (x) {
var res = x.split(",");
console.log(res);
for (var i = 0; i < res.length; i++) {
if (pathname != res[i]) {
alert("IS NOT EQUAL");
//res.push(pathname);
//var joinedArray = res.join(",");
//console.log(joinedArray);
//createCookie('vid_cookies',joinedArray,7);
//var z = readCookie('vid_cookies');
//console.log(z)
}
}
} else {
jsonObj.push(pathname);
createCookie('vid_cookies',jsonObj,7);
}
//alert(jsonObj);
</script>
Here is the Array as :
["/evercookie-master/yahoo.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html"]
The logic is not correct. If you want to add a value to an array only if it doesn't exist yet, you have to check all elements before you add it.
In your code you are adding the value as soon as any of the element doesn't match. That will always be the case of course because out n elements, n - 1 will not match.
One way to do it would be to use Array#every:
if (res.every(x => x !== pathname)) {
// add to array and set cookie
}
Alternatively you could convert the array to a Set, always add the value and set the cookie. The Set will automatically dedupe the values:
var res = new Set(x.split(","));
res.add(pathname);
res = Array.from(res);
Desperately reaching out here now!
My webpage contains three columns with three different divs: "primary", "main" and "secondary".
I would like to maintain the scrollpositions of all divs on reload.
For the the first column "primary" I'm using this script below, that works lika a charm.
I know getElementbyID only can get one div, so how could I possibly do?
window.onload = function() {
var strCook = document.cookie;
if (strCook.indexOf("!~") != 0) {
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS + 2, intE);
document.getElementById("primary").scrollTop = strPos;
}
}
function SetDivPosition() {
var intY = document.getElementById("primary").scrollTop;
document.cookie = "yPos=!~" + intY + "~!";
}
The way that you set the cookie seems to be set up primarily for one item - I would change this so that you can set cookies by a key value pairing.
Using some functions for getting and setting cookies, I would then change your code to:
//add cookie functions
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 + ";path=/";
}
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 "";
}
//I am assuming you will have some sort of on scroll function for setting your cookie. Change this to a function so you can bind it multiple times
function bindScrollEvent(elementId) {
var element = document.getElementById(elementId);
element.onscroll = function() {
setCookie(elementId, element.scrollTop); // use the element id to set the cookie to the scrolltop value
};
// once the event is bound, you can set it's current scroll position
var scrollTopPosition = getCookie(elementId);
if (scrollTopPosition !== '') {
element.scrollTop = scrollTopPosition;
}
}
// reload the div positions when the document loads
window.onload = function() {
bindScrollEvent('primary');
bindScrollEvent('secondary');
bindScrollEvent('main');
}
<script type="text/javascript">
jQuery(document).ready(function(){
if (document.cookie.indexOf('visited=false') == -1)
{
var fifteenDays = 1000*60*60*24*30;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
$.colorbox({width:"400px", inline:true, href:"#exestylepopups"});
}
});
</script>
What's wrong with my above code my facebook like popup is called every time the page is loaded in my blog. I just to show only one time every 30 days.How i can do that?
Your particular implementation looks like it has you checking the cookie for 'visited=false', but setting the cookie to 'visited=true' so your if statement will never match.
I'd suggest you use a proven set of cookie manipulation functions and then your task will be pretty easy.
Here are the cookie functions I use when my environment doesn't already have them:
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);
}
Once you have those, you can do this:
jQuery(document).ready(function() {
var visited = readCookie('visited');
if (!visited || visited !== "true") {
createCookie('visited', "true", 30);
$.colorbox({width:"400px", inline:true, href:"#exestylepopups"});
}
});