I'm currently building a music blog which uses the following JavaScript code to toggle dark mode / light mode buttons:
function swapStylesheet(sheet) {
document.getElementById('swap').setAttribute('href', sheet);
}
My issue is that the website reverts back to the default CSS sheet whenever the page is refreshed or a new page is visited, instead of remembering the chosen theme. Might I be able to have my website remember the user's last chosen theme via cookies or localstorage or something else?
Please let me know! Thank you so much. =]
Short answer is yes.
You could save it via Cookies or Local Storage, and there's many ways to achieve this, I'll just give you reference for cookies, you could test it on W3School
The question you gave right now is only for between pages, but in cases that you want it to retain based on user accounts, then the answer is you need to centralize the "Theme" data for each account somewhere like Database or Server Cache.
https://www.w3schools.com/js/js_cookies.asp
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let 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 checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
checkCookie();
Related
I recently had issues using javascript cookies inside an MTurk HIT. In particular I'm trying to track user preferences w.r.t showing/hiding the HIT instruction.
My approach so far is the following:
<body>
<div id='instructionButton'>
<!-- Button triggering instruction body to collapse/show -->
</div>
<div id='instructionBody'>
<!-- Instruction content (collapsible) -->
...
</div>
</body>
<script>
const instructionBodyId = 'instructionBody';
const instructionButtonId = 'instructionButton';
const cookieName = 'my_cookie_name';
var isInstructionShown = true;
var instrContent = $('#' + instructionBodyId);
var instrButton = $('#' + instructionButtonId);
function setCookie(name, value) {
var date = new Date();
<!-- Cookie valid for 48h -->
date.setTime(date.getTime() + (48 * 60 * 60 * 1000));
var expires = "; expires=" + date.toUTCString();
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(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 toggleInstructions(isShow) {
setCookie(cookieName, isShow);
isInstructionShown = isShow;
if (isShow) {
instrContent.slideDown();
} else {
instrContent.slideUp();
}
}
function prepare_cookie() {
instrButton.click(function() {
toggleInstructions(!isInstructionShown);
});
let cookieVal = getCookie(cookieName);
if (cookieVal == "false") {
toggleInstructions(false);
} else {
toggleInstructions(true);
}
}
$(document).ready(function() {
prepare_cookie();
});
</script>
The code above shows part of the HIT layout I'm creating, and when testing it out while editing the HIT directly in MTurk, the cookie works as expected (it shows up in Google Chrome and works as expected, showing/hiding the instruction automatically).
Unfortunately, when publishing the HIT, the cookie does not seem to be set (it does not appear in the list of cookies shown in Google Chrome).
This question already has answers here:
How do I create and read a value from cookie with javascript?
(23 answers)
Closed 5 years ago.
Here is my html:
<span class="boxclose" id='close'>X</span>
Here is my script:
<script type="text/javascript">
window.onload = function(){
document.getElementById('close').onclick = function(){
this.parentNode.parentNode.parentNode
.removeChild(this.parentNode.parentNode);
return false;
};
};
</script>
All works, but i have no idea how i would update the script to set a cookie to remember, once it has been closed. Any help would be appreciated, thanks
Saving and reading cookies
If you want to read and save cookies the easy way you can use the two functions below from W3Schools. If the close element gets clicked I create a cookie named "closed" for which I set the value to "True". On the page load the cookie "closed" just gets checked if it was indeed already clicked.
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(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=/";
}
window.onload = function() {
if (getCookie("closed") == "True") {
document.getElementById('close').parentNode.parentNode.parentNode.removeChild(document.getElementById('close').parentNode.parentNode);
} else {
document.getElementById('close').onclick = function() {
setCookie("closed", "True", 42);
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
return false;
};
}
};
For more information about cookies click here.
Saving inside and reading from the localStorage
This is an example with localStorage which might be interesting for you since a localStorage item is almost like a cookie.
Once you click on the close element I store that it has been clicked inside the localStorage by using localStorage.setItem("closed","True");. To now check if the element was already closed by the visitor on a previous visit etc. you can use localStorage.getitem("closed") which will return "True" (in this case) and compare it to the String "True".
window.onload = function() {
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("closed") == "True") {
document.getElementById('close').parentNode.parentNode.parentNode.removeChild(document.getElementById('close').parentNode.parentNode);
}
document.getElementById('close').onclick = function() {
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
localStorage.setItem("closed", "True");
return false;
};
} else {
alert("Your browser does not support localStorage");
}
};
Click here for a functioning jsfiddle.
For more information about localStorage I recommend W3Schools.
I have this script in JS
function setCookie(name, value, days) {
var d = new Date;
d.setTime(d.getTime() + 24*60*60*1000*days);
document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
I can see in my Chrome browser options->settings that the cookie name "workLocation" is set. The domain for the cookie is "/", 'send for' option is "Any kind of Connection" and 'accessible to script' option is "Yes".
when I call the cookie using JS code below, it returns null.
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
alert(getCookie("workLocation"));
I had tried using PHP to show cookies var_dump($_COOKIE); but it only shows codeigniter cookies "ci_session" and "httpUser". I had used the same javascript to set and get cookies and it's working, except for this page. Any ideas how to solve it?
cookie in server and in client is different the cookie in server is stored in
Local Storage
and the cookie in client is stored in
Cookies
if you want to get the cookie from js u can use this functions :
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 checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
but if you want to get the cookie from php especially those session in CI
u can use this command $this->session->userdata("key");
Using both internet and Stack Overflow resources I managed to write a crude HTML website, that allows the user to switch Language of it on the fly, using Javascript, jQuery and XML.
Now, the problem I ran into is to keep the preferred language across the entire portal, without the need to change it each time when navigating through it. I have decided to use a simple cookie to keep the track of it, but it seems I have messed something up, and I can't figure out what I'm doing wrong.
Basically speaking, the page itself has text in the code itself (as a backup just in case), however the text becomes invisible when booting the site, until I switch a language, nor the language is kept when I navigate the portal. For the former, I assumed that the script was reading some empty or overall wrong cookie, so I made an attempt to filter it out and use a default language, but in vain. As for the latter issue, I guess I save the cookie itself wrong as well, but I can't seem to figure out what's wrong with it.
Any help/advice would be appreciated.
function changeLanguage(lang) {
$(function() {
$.ajax({
url: 'jezyki.xml',
success: function(xml) {
$(xml).find('translation').each(function(){
var id = $(this).attr('id');
var text = $(this).find(lang).text();
$("." + id).html(text);
if (lang === "") { }
else {
var title = lang;
createCookie("language", title, 365);
}
});
}
});
});
}
$(document).ready(function () {
$("input[name='radio-language']").click(function () {
changeLanguage($(this).val());
});
});
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 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 (e) {
var cookie = readCookie("language");
var domyslny = "english";
if (title === "") { changeLanguage(domyslny); } else { changeLanguage(title); }
}
Apologies if this is something silly, I am quite a newbie when it comes to Javascript/jQuery.
I'm trying to figure out how to track how many pages a user vists via cookies. I just want to count how many pages they visit, and on the 3rd page, display a newsletter signup form. This is my current script, which doesn't have any counting mechanism:
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) == 0) return c.substring(name.length,c.length);
}
return "";
}
var hidePopoverCookie = getCookie("hidePopover");
if (hidePopoverCookie == "") { // && pagesVisited > 2
setTimeout(function() {
$("#popOver").show();
}, 5000);
}
$("#popOver button").click(function() {
$("#popOver").hide();
setCookie("hidePopover", true, 365);
})
And this is what I'm trying to implement as a page counter:
var pagesVisitedCookie = getCookie("pagesVisited");
if (pagesVisitedCookie === "") {
console.log ("no pages visited");
setCookie("pagesVisted", 1, 365);
} else if (pagesVisitedCookie === 1) {
console.log("2 pages visited");
setCookie("pagesVisted", 2, 365);
} else if (pagesVisitedCookie > 2) {
console.log("More than 2 pages visited");
setCookie("pagesVisted", 3, 365);
}
What happens is it returns "no pages visited" no matter what, and I'm not sure why. I'm very new to cookies, and I'm sure there's a cleaner way to do this, I just want to get it done (this project is making me insane).
Since I see you are already using jQuery, I will use it to as the wrapper function of which will trigger than actual logic on DOM loaded event, then you I could use sessionStorage like so:
$(function(){ // fires once a page's DOM is ready
var visitsCount = JSON.parse(sessionStorage.getItem('visitsCount'));
if( visitsCount.legnth < 3 && $.inArray( window.location.href, visitsCount ) == -1 ){
visitsCount.push(window.location.href);
sessionStorage.setItem('visitsCount', JSON.stringify(visitsCount));
}
if( visitsCount.legnth >= 3 ) // user has viewed 3 different pages
// do whatever
});
The code is storing the current URL of the page in the sessionStorage, if that URL isn't in the stored array already.
You are setting a cookie named pagesVisted, while you are reading a cookie named pagesVisited.