Easiest way of remembering user locale selection in HTML - javascript

I've been working on a website of mine for about a week now. I'm very good with HTML and CSS, but I'm still trying to wrap my head around Javascript, JQuery and PHP.
Basically, what I'm trying to do is create a way if remembering the users language and locale based on their selection on a language selection page. What I'd like (if possible), is for a user to select their flag on a /locale page and make that change the url of the homepage (ie. mysite.com/en-us). I'm going to be translating my website content via static pages, not active translation.
This only has to work for the homepage, not subsequent pages, however it would be awesome if it did work for pages under different directories too. You can view a live example of my newly constructed website here.
I'd prefer Javascript or JQuery, but honestly - when someone else is doing the hard part, I don't really have the right to be picky.
Thank everyone very much in advance for any assistance.

There's two ways to achieve this: Cookies or localStorage. The easiest one is localStorage:
Here's two plain Javascript functions. The first runs onbodyload and check if the previous language choice (stored in the localStorage) was Spanish. If not (or blank), the welcome appears in English.
When you click a button, it runs the second function which changes the welcome language plus stores the choice in the localStorage.
HTML
<button onclick="language('en')">english</button>
<button onclick="language('spa')">spanish</button>
<h1><span id=welcome>text</span></h1>
JAVASCRIPT
document.getElementsByTagName("body")[0].onload=function(){session()};
function session() {
var result = localStorage.getItem("session");
if (result === 'spa') {
document.getElementById("welcome").innerHTML = "Hola!";
} else {
document.getElementById("welcome").innerHTML = "Hello!";
}
}
function language(key) {
if (key === 'en') {
document.getElementById("welcome").innerHTML = "Hello!";
localStorage.setItem("session", "en");
} else if (key === 'spa') {
document.getElementById("welcome").innerHTML = "Hola!";
localStorage.setItem("session", "spa");
}
}
Codepen DEMO

Related

My JSLink script will not work

I am attempting to use JSLink ..finally.. and I am having some trouble that I cannot seem to straighten out. For my first venture down the rabbit hole I chose something super simple for use as proof of concept. So I looked up a tutorial and came up with a simple script to draw a box around the Title field of each entry and style the text. I cannot get this to work. Is there any chance you can take a look at this code for me? I used the following tokens in the JSLink box.
~sitecollection/site/folder/folder/file.js
And
~site/folder/folder/file.js
The .js file is stored on the same site as the List View WebPart I am attempting to modify. The list only has the default “Title” column.
(function () {
var overrideContext = {};
overrideContext.Templates = {};
overrideContext.Templates.Item = overrideTemplate;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
}) ();
function overrideTemplate(ctx) {
return “<div style=’font-size:40px;border:solid 3px black;margin-bottom:6px;padding:4px;width:200px;’>” + ctx.CurrentItem.Title + “</div>”;
}
It looks as though you are attempting to override the context (ctx) item itself, where you actually just want to override the list field and the list view in which the field is displayed. Make sense?
Firstly, change overrideContext.Templates.Item to overrideContext.Templates.Fields :
(function () {
var overrideContext = {};
overrideContext.Templates = {};
overrideContext.Templates.Fields = {
// Add field and point it to your rendering function
"Title": { "View": overrideTemplate },
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
}) ();
Then when the JSLink runs the renderer looks for the Title field in the List view, and applies your overrideTemplate function.
function overrideTemplate(ctx) {
return “<div style=’font-size:40px;border:solid 3px black;margin-bottom:6px;padding:4px;width:200px;’>” + ctx.CurrentItem.Title + “</div>”;
}
In terms of running multiple JSLinks on a SharePoint page, it is quite possible to run multiple JSLink scripts, they just need to be separated by the pipe '|' symbol. I use SharePoint Online a lot and I see the following formatting working all the time (sorry Sascha!).
~site/yourassetfolder/yourfilename.js | ~site/yourassetfolder/anotherfilename.js
You can run as many scripts concurrently as you want, just keep separating them with the pipe. I've seen this on prem also, however you might want to swap out '~sites' for '~sitecollection' and make sure the js files you are accessing are at the top level site in the site collection if you do so!
I have noticed when running multiple JSLinks on a list or page because they are all doing Client Side Rendering, too many will slow your page down. If this happens, you might want to consider combining them into one JSLink script so that the server only has to call one file to return to the client to do all the rendering needed for your list.
Hope this helps.

iBooks Author/iAd Producer Widget User Text Disappears

I'm using iAd producer to create HTML widgets for iBooks I'm making using iBooks Author. I've done some research and learned that I can have user input saved into local storage by way of a variable that is called every time the widget is opened. This is great except for the new problem of having to create hundreds of text box widgets all with different variables so I can use these text boxes on multiple pages. Is there a way for me to automate this using Java Script? One idea I had was to use a "while" function to tell the script to ++ the variable if the one it tried to use was not empty. Example: the variable "001" was already used so the code would ideally set the next user text to variable "002". Preferably, I'd like to be able to create one widget with this code that I could reuse anywhere else.
Here is the code I'm currently using:
/*Widget code*/
this.onViewControllerViewWillAppear = function (event) {
var theValue = this.outlets.textField;
if (localStorage.getItem("theKey102") === null) {
theValue.value = "";
} else {
theValue.value = localStorage.getItem("theKey102");
}
};
/*This is the code for one of the text boxes I'm using */
this.onControlValueChange = function (event) {
var theValue = this.viewController.outlets.textField;
localStorage.setItem("theKey102", theValue.value);
};

Keeping JS changes on DOM after refresh

So, I have this weird thing going on in my test site, where I have every "link" (be it menu,button, or anything) to show/hide divs instead of loading pages. Pretty basic right? Except whenever I refresh the page, it all reverts back to the Homepage, which is expected. Based on my search for answers, I think I have to use the local/session storage option. Session sounds better.
So here's the deal. I looked up the w3schools page on sessionStorage and I get how it works, but I don't undestand how I could apply this to my page. Basically every link on my page runs a function that hides the previous div and shows a new one with the content. So I was thinking if every time a function triggered, it would store a value on a var that would appoint the function as the last used. Then somehow use sessionStorage and make it work, but I can't built it. Any help?
Here's a short example of my current code.
EDITED
var state = null;
function show1() {
state = "home";
"use strict";
document.getElementById('snow').style.display = "block";
document.getElementById('btn').style.display = "none";
}
function ramble() {
state = "ramble";
"use strict";
document.getElementById('ramble').style.display = "block";
document.getElementById('snow').style.display = "none";
document.getElementById('tex').style.display = "none";
}
That's basically it.Onclick show/hide.
You can use the following syntax:
Save data:
sessionStorage.setItem('key', 'value');
Retrieve data:
var data = sessionStorage.getItem('key');
More info and examples: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
The same goes with localStorage, but with the persistance differences you already found
I hope my solution will help you: If you want to keep your JS changes, you need to save them to database using AJAX and also change page architecture and logic to use data from database. After that, even if you reload page you will keep all your changes.

How to change prompt responses to input boxes in JavaScript and HTML

Long Detailed Question
I put a part of my code below. It is a small javascript game I am working on. When the game wants to know something, or take an text input from the user, I use the prompt command, which as you probably know brings up an alert box that displays some text and lets the user submit a text response. I want to know how I can change it, so instead of an alert box that pops up there is just a input box on the screen that takes their text response. I assume the code needed would either be JQuery(which I do not have much experience in) or JavaScript.
Short Summarized Question
So in summary I want to know how I can make an input box that takes text inputs similar to how a prompt alert does<<<
Code
var finishAnt = prompt(
"you can either risk your life and finish him, or try to run away. Do you finish him?").toLowerCase()
if (finishAnt == "yes") {
console.log("congratulations you have killed the aint eater!")
} else if (finishAnt == "no") {
console.log(
"You run away and barley make it, you are badly hurt");
} else {
console.log("sorry thats not an option")
}
} else if (meetAnt == "no") {
console.log(
"You run past the ant eater and get to saftey. You are very lucky")
} else {
console.log("Sorry that is not an option.")
}
Either you can use Jquery for this, or you can use document.getElementsByTagName('input').value, assign it to a variable, and act accordingly. Like if the user selects yes to the first, the value of the input box will be set to the boolean: true or a string: yes. Then take those values and display a message based on the results.
There is no way to translate this code directly. You will need to make some significant changes to your code to support it.
The alert(), prompt() and confirm() Javascript functions are unique in that they block execution of scripts until the dialog is dismissed. Essentially all other methods in Javascript, including DOM methods that allow you to manipulate and respond to events in a HTML page, are all non-blocking — that is, they must execute immediately, and cannot wait for an event to occur.
To rework this code to run within a page, you will need to reformulate it as a state machine. This will entail keeping track of what state your game is in at any given point and responding appropriately to events based on that state. For instance, you might write a part of your game as:
var state;
function print(msg) {
document.getElementById("output").innerText = msg;
}
function takeInput() {
var input = document.getElementById("input").value;
if (state == "which-door") {
if (input == "left") {
print("You open the left door and fall into a bottomless pit. What now?");
state = "bottomless-pit";
} else if(input == "right") {
print("You open the right door and find yourself lost outdoors...");
state = "outdoors";
} else {
print("That isn't a door. Which door do you open?");
state = "which-door";
}
} else if (state == "bottomless-pit") {
print("You're still falling down a bottomless pit...");
state = "bottomless-pit";
} else if (state == "outdoors") {
print("Now you're back at those two doors again. Left or right?");
state = "which-door";
}
// ... etc ...
});
// Make the "go" element call the takeInput() method when clicked
document.getElementById("go").addEventListener("click", takeInput);
// Start out in the "which-door" state and display an introduction:
state = "which-door";
print("Do you open the left door or the right door?");
<div id="output"></div>
<div>
<input id="input" size="40">
<button id="go">Go</button>
</div>
See the basic framework of this code? At each step, you're taking the current state and input into account, and using those to decide how to respond (by calling print(), typically), and what state to enter next.
(Note that this structure means that it's much easier to introduce logical loops into your game, as it's no longer necessary to represent them as control structures. For instance, the "bottomless-pit" state in this example loops back to itself, and the "outdoors" state loops back to the "which-door" state.)
I don't think you can modify JS presets, but you can make mockups of them in Visual Basic (TEXT/VBSCRIPT)
Try using CSS to make a fake popup. That'll make it look real. Or embed a PNG. But be warned. Embedding a PNG could result in the user dragging it and finding out it's fake. Try using Animate.CSS to let it pop up in the Windows fashion.

What does the Javascript:OpenID.Signin('example') Does?

I always admired the stackoverflow.com website.
I also, was always curious about what the Javascript:OpenID.Signin('example') here, in the login page of the Stackoverflow.com, does.
You see, i would like to implement something similar to my website, and this one is the question that first came in my mind. (I mean provide, separate button for every different connect provider).
Please keep in mind that i am a newbie and i would prefer, if possible, simple answers.
Thank you in advance.
PS. If you are not willing to tell me what the Javascript:OpenID.Signin('example') does, could you please tell me how can i achieve the same functionality?
I am totally lost with the OpenId stuff and in any case would not like to mention the OpenID as is, in my website. I am sure it will complicate things for the users of my website too. I would prefer a solution, connect with Google, Facebook etc separate buttons.
If you view source on the page your talking about you can see a script tag for an outside file
<script type="text/javascript" src="http://sstatic.net/Js/third-party/openid-jquery.js?v=8"></script>
If you look there, you'll see it contains a global var called openid which contains a function called signin among other things.
Here's the function body if you're curious
signin: function (box_id, onload) {
var provider = providers[box_id];
if (!provider) { return; }
this.highlight(box_id);
if (box_id == 'openid') {
$('#openid_input_area').empty();
this.setOpenIdUrl("");
$("#openid_identifier").focus();
return;
}
// prompt user for input?
if (provider['label']) {
this.useInputBox(provider);
this.provider_url = provider['url'];
} else {
$('.' + box_id).css('cursor', 'wait');
if (provider['oauth_version']) {
this.setOAuthInfo(provider['oauth_version'], provider['oauth_server']);
} else {
this.setOpenIdUrl(provider['url']);
}
this.provider_url = null;
if (!onload) {
$('#openid_form').submit();
}
}
}

Categories