I'm working on a project and I have to make a button to remember users selected specific page. It should work like a cookie, but I need some more information about how to save website page on cookies. The main part is when users clicks on a button, website remember users selection and when users enter after some time the same page, he will see his selection. And of course, if user push the button one more time, his selection deletes.
P.s. I'm new guy in coding so, your help will be useful for me.
Thanks in advance.
You can use browser storage for this
When user select some value:
localStorage.setItem("userSelection", "selection-value");
And when the user enter on page, you verify if userSelection exists:
var userSelection = localStorage.getItem('userSelection');
if ( userSelection ) {
// some action
}
See more: localStorage
Use any of these below to store user preferences
sessionStorage.setItem("sessionData", "I am set in session storage.");
localStorage.setItem("localData", "I am set in local storage.");
My recommendation is to store preference using URL hash combination while.storing in session or localstorage
you can do that based on ids like in my example right bellow
function getCookie(name){
var b=name+"=",
c=decodeURIComponent(document.cookie),
d=c.split(";");
for(var e=0;e<d.length;e++){
for(var f=d[e];" "==f.charAt(0);)f=f.substring(1);
if(0==f.indexOf(b))return f.substring(b.length,f.length)
}
}
function setCookie(name,value,period,path){
var time=new Date;
time.setTime(time.getTime()+1e3*(60*(60*(24*period))));
document.cookie=name+"="+value+";"+"expires="+time.toUTCString()+";path="+(path?path:"/")
}
function removeCookie(cookie_name){
if(getCookie(cookie_name)){
document.cookie=cookie_name+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
}
document.getElementById('xxx').onclick = function(){
if(getCookie(this.id)==1) {
removeCookie(this.id)
} else {
setCookie(this.id,1,999999);
}
}
<button id="xxx">Selection 1</button>
and of course use php or maybe javascript to detect if cookie exists.
Related
Explination:
We are facing some issues with logged in users being able to checkout via wordpress's woocommerce. The fix for these few users that reached out to us was to simply clear their cookies. (Because we recently changed servers which mucked things up a bit causing this checkout issue)
So i want to provide a red bar at the top of our checkout and cart pages that recommends to our users that they update the cookies to our site. And provide a button they can click that will remove the cookie for them.
Problem:
Okay so i have this script.. Which I am told is suppose to work.
Start your bacon
--
function deleteAllCookies() {
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";
}
}
function clearAndRedirect(link) {
deleteAllCookies();
document.location = link;
}
Start your bacon
However when i open dev tools and select the application tab. I am able to clear my cookie by simply right clicking and selecting clear - at which point it deletes itself and removes itself from the cookie folder.
But when I am in dev tools and use this button script to clear my cookie. The cookie remains in the file unlike if i cleared it manually by right clicking on it in dev tools. So I am unsure if its working or not. How do i properly test this?
Also how do i make it re-direct the user to the login page after the cookie is successfully cleared and successful? instead of just directly after the function runs.
Any help much appreciated. Not sure if its working.
I have implemented localStorage for some data that is useful for user experience, but is NOT essential for application itself (doesn't break functionality).
Problem: Every time I go to show page and then press BACK button to INDEX page all my local storage disappears.
localStorage is set in INDEX page with function:
$(document).ready(function () {
return $(".sort_link").on("ajax:success", function(e, data, status, xhr) {
localStorage.removeItem('results'); //removes any old localStorage values
if (document.getElementById("results-dupl")) {
var results = $("#results-dupl").html();
localStorage.results = results
} else {
var results = $("#searc_re").html();
localStorage.results = results
}
}).on("ajax:error", function(e, xhr, status, error) {
});
});
Basically, localStorage key is set independently, NOT before leaving current INDEX page.
Problem doesn't occur if I press any other link that redirects to INDEX page. I have tried and the same problem occurs on Firefox and Chrome so I guess - on all browsers.
What I have tried:
1) Added localStorage.getItem('results'); right after setting localStorage key as seen in other question.
2) Double checked that above seen function actually creates localStorage key- Yes, 100 % creates.
3) It seems that also cookie that is created within the same INDEX page is lost after visiting show page and then with "BACK" button getting back to INDEX page.
Thanks in advance for any help.
EDIT:
Found solution based on accepted answer.
Basically, somehow previously commented out script was working and deleting localStorage and cookies:
localStorage.removeItem('menu');
localStorage.removeItem('results');
document.cookie = "menu_storage=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
Do not use localStorage.removeItem('results');. it'll fix the problem and localStorage.removeItem('results'); is useless anyway in this case because you can edit localStorage instead of deleting it.
What I am looking to achieve is that when a user comes to my site they immediately encounter a pop up (or a landing page) that asks, are you a man or a woman or other (choose x or y or z). They pick and click the link, then once they choose they go to that part of the site (and no it isn't a adult site ;). A cookie then remembers their choice and each time they return they are automatically redirected to their choice.
So basically we need the ability to set a cookie based on their choice (via link or form button) and then when they return to the homepage get that cookie and redirect.
I've seen some questions and answers that are close but just not quite there with this scenario and I end up confused.
What do you think? Doable? Please help and thanks so much.
Without knowing much of your architecture, I came up with the following:
This code should be called after the user has made the choice:
//´choice´ contains the value of what the user chose
//Setting the cookie:
document.cookie="gender="+ choice +"; expires=Thu, 18 Dec 2029 12:00:00 UTC";
//Redirect the user after the cookie has been set:
document.location.href = "http://yoursite.com/";
Take a look how cookies are defined in PHP: http://php.net/manual/en/function.setcookie.php
Then in PHP code you may read what cookies are set when the user loads your site:
if($_COOKIE["gender"] === "x"){
//Do some x stuff
} else if($_COOKIE["gender"] === "y") {
//Do some y stuff
}
I have a pop up form on my site which pops up as soon as some one click on the link. but I want to make it such that it should not pop up for the second time for a same user.
how to do it, as I don't have user management system.
Even better Solution,Use one in Jquery
<a id="popup" >link1</a><br>
$('#popup').one('click',function(){
alert('open your popup here');
});
Here is you fiddle
You need to use cookies for it. At first click, generate a cookies when user clicks at first time and checks if it's available when user click on it.
So, as kind of solution u can use cookies. Example below.
This support function will help u get cookie using JS later
function getCookie(name) {
var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,'\\$1')+"=([^;]*)"));
var x = matches ? decodeURIComponent(matches[1]) : undefined;
return x;
}
And than in user click handler set cookie for browser like this
$(document).on('click','#someDivHere',function() {
if (getCookie('addShowed') === undefined) {
var date = new Date( new Date().getTime() - 2*24*60*60*1000 );
document.cookie="addShowed='true'; path=/; expires="+date.toUTCString();
}
});
I had a project in my web design class this semester(I'm a newbie at this) and I've been working on a little side work in my free time. I've been trying to work with cookies and JavaScript. We didn't cover cookies very much in my class and I've been searching and searching for an answer to my current problem. Chances are, if you've ever responded to anything on this site about JavaScript and/or HTML, I've read it. As my title says, I'm having a problem where my cookie doesn't seem to save. On first load, the code works fine, then I reload the page and it doesn't recall the cookie value.
This is my cookie script:
var name;
if(document.cookie)
{
var q1=unescape(document.cookie);
var q2=q1.search("name");
if(q2!=(-1))
{
var n=str.split("name=");
var n1=n[1];
var n2=n1.split(";");
var q=n2[0];
name=q;
}
else
{
name=window.prompt("Please enter your name.");
document.cookie="name="+escape(name);
}
}
else
{
name=window.prompt("Please enter your name.");
document.cookie="name="+escape(name);
}
This is used once the rest of the page is loaded in:
document.writeln(name+"text stuff");
In the case of an incorrect value in the cookie, I've created this function that is called on via a button in the HTML:
function wrongPerson()
{
document.cookie="name=hooper; expires=Thu, 01 Jan 1970 00:00:01 GMT";
location.reload();
}
Sorry for such a long post, but I wanted to make sure the community had as much information as possible. Also, sorry about the poor formatting. I wasn't sure how to bring over my entire long thing of code and have the system allow it.
You need to set expire on your cookie script. If you don't put an expire date to your cookie it will recognize as a "one-time cookie". And after a reload or anything, it will disappear.
Set an expire to Wed, 01 Jan 2014 00:00:01 GMT
This is my personal opinion, but I rather use window.location.href = window.location.href; instead of location.reload();