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,
Related
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>
<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
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');
}
I have code which sets Cookie for every folder of domain (for example, domain.com and domain.com/folder, domain.com/folder2) have same Cookie name ("history") and different "history" values. How can i ignore Path for Cookie and add all Cookie value in same name ("history") even if Cookie was set from another folder? I used standart cookie.js (https://github.com/js-cookie/js-cookie) and this additional code:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + '=' + cvalue + ';path="/";' + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for ( var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0)
return c.substring(name.length, c.length);
}
return "";
}
function checkHistory(targetId) {
var history = getCookie("history");
var htmlContent = '';
if (history != "") {
var insert = true;
var sp = history.toString().split(",");
for ( var i = sp.length - 1; i >= 0; i--) {
htmlContent += '<div id="recentViewes" data-recentViewes="'
+ sp[i] + '"></div> ';
if (sp[i] == document.URL) {
insert = false;
}
document.getElementById(targetId).innerHTML = htmlContent;
}
if (insert) {
sp.push(document.URL);
}
setCookie("history", sp.toString(), 30);
} else {
var stack = new Array();
stack.push(document.URL);
setCookie("history", stack.toString(), 30);
}
}
Found solution by myself:
This code for page where you want to have History block:
function checkHistory(targetId) {
var history = getCookie("history");
var htmlContent = '';
if (history != "") {
var insert = true;
var sp = history.toString().split(",");
var se = decodeURIComponent(sp).split(",");
for ( var i = se.length - 1; i >= 0; i--) {
htmlContent += '<div id="recentViewes" data-recentViewes="'
+ se[i] + '"></div> ';
if (se[i] == window.location.pathname) {
insert = false;
}
document.getElementById(targetId).innerHTML = htmlContent;
}
if (insert) {
se.push(window.location.pathname);
}
setCookie("history", se.toString(), 30);
} else {
var stack = new Array();
stack.push(window.location.pathname);
setCookie("history", stack.toString(), 30);
}
}
And this for every folder/page of domain:
function checkHistory(targetId) {
var history = getCookie("history");
var htmlContent = '';
if (history != "") {
var insert = true;
var sp = history.toString().split(",");
var se = decodeURIComponent(sp).split(",");
for ( var i = se.length - 1; i >= 0; i--) {
htmlContent += '<div id="recentViewes" data-recentViewes="'
+ se[i] + '"></div> ';
if (se[i] == window.location.pathname) {
insert = false;
}
document.getElementById(targetId).innerHTML = htmlContent;
}
if (insert) {
se.push(window.location.pathname);
}
$.cookie('history', se.toString(), { expires: 30, path: '/' });
} else {
var stack = new Array();
stack.push(window.location.pathname);
$.cookie('history', stack.toString(), { expires: 30, path: '/' });
}
}
<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"});
}
});