Language switcher - Javascript/jQuery and Cookies - javascript

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.

Related

Save website theme (eg. dark mode) across pages

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

Set cookie in MTurk HIT

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

Set cookie after closing div [duplicate]

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.

Weird behaviour with cookies and firefox

Edit: This only happens in firefox, it works fine in chrome.
Edit 2: Due to there apparently not being a solution to this (sessionid breaks when there are other cookies present) i've decided to use localstorage instead (it's also a much better approach)
I have an audio player on my website (website powered by django) and I want to store the current time, the source and the state (is it playing or not) in cookies. So when you refresh the page while music is playing, it'll continue where you left off. I have a timer set to update the cookie track_time every second. And it works, however:
When you try logging into the website a second time, while audio is playing, it won't let you. It says in my console that the login happened, but firefox doesn't seem to store the session. When I disable the script that is writing the cookies, it works again.
Here's proof:
http://puu.sh/nkqIX/23160ce67e.png
What in the world is happening here? I'm not recieving any errors, it just doesn't work.
Code:
This snippet here creates, reads, and deletes cookies.
/** Cookies **/
function createCookie(name, value, days) {
'use strict';
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);
}
In audio.js I have the following functions:
// Cookie? //
function audioCookie() {
'use strict';
var track, track_time, track_state;
track = readCookie('track');
track_time = readCookie('track_time');
track_state = readCookie('track_state');
if (track !== null) {
track = JSON.parse(track);
audioCurrent = new AudioTrack(track.src, track.artist, track.title, track.genre, track.type);
audioCurrent.setSrc();
if (track_state === '1') {
audioCurrent.play();
}
setTimeout(function () {
audioCurrent.time(track_time);
audioSetProperties();
audioViewUpdate();
audioElementUpdatePlayButton();
audioAnalyserInitialize();
}, 250);
}
}
And
var audioTimeUpdate = function () {
'use strict';
if (audioSource.paused === false) {
audioSetProperties();
createCookie('track_time', audioSource.currentTime, 360);
setTimeout(function () {
audioTimeUpdate();
}, 500);
}
};
Create the cookie containing the AudioTrack object (source, name, etc)
// Play the track that is being viewed
var audioPlayFromView = function () {
'use strict';
audioCurrent = audioFromView;
var audioCurrentString = JSON.stringify(audioCurrent);
createCookie('track', audioCurrentString, 360);
audioCurrent.setSrc();
audioCurrent.play();
if (analyserInitialized === true) {
source.disconnect();
source = context.createMediaElementSource(audioSource);
}
audioViewUpdate();
};

Fire function when a user visits 3 or more pages

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.

Categories

Resources