Maintain scroll position in two columns on reload - javascript

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');
}

Related

How to create page visit counting like PHP session on JavaScript (client) side

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>

Logical Operator always stays true?

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);

Run javascript function once a week

I have the below javascript function that currently runs on every visit. I do not want to spam our visitors with this popup on every visit so I am trying to get my head around cookies and running this once a week.
setTimeout(function() {
jQuery(document).one('mouseleave', function() {
console.log('mouse left');
jQuery('.open-popup-link').magnificPopup('open');
});
}, 10000);
I placed this within a cookie function that I found on here however nothing runs and no errors in the console.
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 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) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var pinball = getCookie("pinball");
if (pinball === "") { // Cookie not set
setTimeout(function() {
jQuery(document).one('mouseleave', function() {
console.log('mouse left');
jQuery('.open-popup-link').magnificPopup('open');
});
}, 10000);
setCookie("pinball", "seen", 7);
}
}
What have I missed or need to do to make this run?
I agree with #MysterX about local storage, but to answer your question - from reading your code - there does not seem to be a call to trigger checkCookie() which means that there are no errors because the function has not run.
You should probably have:
$(document).ready(function(){
checkCookie()
})
also you have a typo in the first section of code and in the checkCookie function as well - same error - you have :
jQuery(document).one('mouseleave', function() {...
and it should be .
jQuery(document).on('mouseleave', function() {...
Using localStorage, only call checkSeen once per page load, or execute it inside of setInterval for browsers that never close.
function popup() {
...
}
function updateSeen() {
var sec = Math.round(Date.now()/1000);
localStorage.setItem("seen", sec);
return sec;
}
function checkSeen() {
var seen = localStorage.getItem("seen") || updateSeen();
var now = Math.round(Date.now()/1000);
var week = 604800;
if ((now - seen) >= week) {
updateSeen();
popup();
}
}
checkSeen();

Using a js cookie to remember objects position when the page is reloaded

Okay. So the code pasted below is another update. What I am trying to do is use a cookie to store the position of an object which changes it's position based on two buttons (DIVs actually).
The createCookie and readCookie are basically copy and pasted.
The checkCookie and storeCookie are doing most of the functionality I'm looking for (remembering cookie & checking on page load).
The $(document).ready(function() is the position control using jquery.
<SCRIPT type=text/javascript>
////////////////////////FROM QUIRKSMODE.ORG///////////////////////////////
//equivalent of "setCookie" from w3schools
//time is represented in days*hours*minutes*seconds*milliseconds
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=/";
}
//equivalent of "getCookie" from w3schools
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;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////cookie functions////////////////////////////////
var pos=readCookie("position");
//var object = document.getElementById('CWS_flow_001');
function checkCookie()
{
var object = document.getElementById('CWS_flow_001');
if (pos=378)
{
object.style.position="absolute";
object.style.left = 378;
$("#show_primary_rec_001").fadeIn(500);
$("#show_secondary_rec_002").fadeOut(500);
}
else if (pos=-990)
{
object.style.position="absolute";
object.style.left = -990;
$("#show_primary_rec_001").fadeOut(500);
$("#show_secondary_rec_002").fadeIn(500);
}
}
function storeCookie()
{
//var pos=readCookie("position");
createCookie("position",pos,1*24*60*60*1000);
alert("the cookie is set to " + pos);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////animation of object/////////////////////////////////
$(document).ready(function() {
$("#show_secondary_rec_002").fadeOut(0);
$("#show_primary_rec_001").click(function moveLeft () {
$("#CWS_flow_001").animate({
left: "-990px"
}, 500 );
$("#show_primary_rec_001").fadeOut(500);
$("#show_secondary_rec_002").fadeIn(500);
//sets "pos" to -990 and runs storeCookie on click w/ 1 second delay
pos=-990;
setTimeout("storeCookie()", 1000);
});
$("#show_secondary_rec_002").click(function moveRight () {
$("#CWS_flow_001").animate({
left: "378px"
}, 500 );
$("#show_primary_rec_001").fadeIn(500);
$("#show_secondary_rec_002").fadeOut(500);
//sets "pos" to 378 and runs storeCookie on click w/ 1 second delay
pos=378;
setTimeout("storeCookie()", 1000);
});
});
</SCRIPT>

How to find out user clicked 3 times through my website with Javascript

Is there any way in JavaScript how to find out user clicked through the same domain 2 or more times?
I need to popup a window after user clicked anywhere on the site for 3 times. I know how to do it after one click - with document.referrer or addEventListener, but then I'm lost.
I need something that will capture all click events (not only links) and count them.
Sure. You need to store a list of users' click events, either in a cookie, or in a server-side data store. On every recorded click, increment the count by one, and do your thing when the number hits 3.
Try using session cookies to store state between pages -- they're fast, pretty widely compatible, and will zero out when the browser shuts down, to keep from spamming your users' cookie jars.
I tried this and it worked fine:
window.onload = function() {
var clicked = readCookie('popunder');
if(clicked == null) {
clicked = 0;
}
var allLinks = document.getElementsByTagName("a");
for(i=0;i<=allLinks.length;i++) {
allLinks[i].addEventListener("click",countClicks,true);
}
function countClicks() {
if(clicked == 2) {
popunder(); //something to do
} else {
clicked++;
doCookie('popunder', clicked, 1);
alert(clicked);
}
}
function popunder() { alert('thats 3 clicks!'); }
function doCookie(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 readName = name + "=";
var cSplit = document.cookie.split(';');
for(var i=0;i < cSplit.length;i++) {
var sc = cSplit[i];
while (sc.charAt(0)==' ') sc = sc.substring(1,sc.length);
if (sc.indexOf(readName) == 0) return sc.substring(readName.length,sc.length);
}
return null;
}
}
Thanks for all your advice.
I tried this code. But after the refresh the clicked variable goes to 0 again.
I need to save every new value of clicked into cookie (or whatever else), so its number will rise with every click on link on page.
Is it possible to change value of the variable in cookie this way?
window.onload = function(){
var **allLinks** = document.getElementsByTagName("a");
var **clicked** = 0;
**doCookie**('popunder',clicked,1);
for(i=0;i<=allLinks.length;i++){
allLinks[i].addEventListener("click",countClicks,true);
}
function **countClicks**(){
if(clicked == 3){
popunder(); //something to do
}
else{
alert(readCookie('popunder'));
return clicked++;
}
}
function **doCookie**(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 readName = name + "=";
var cSplit = document.cookie.split(';');
for(var i=0;i < cSplit.length;i++) {
var sc = cSplit[i];
while (sc.charAt(0)==' ') sc = sc.substring(1,sc.length);
if (sc.indexOf(readName) == 0) return sc.substring(readName.length,sc.length);
}
return null;
}

Categories