I have a very internationalised website, however I need to produce a pop-up specifically for our UK customers.
What I require is:
On page load: Is the user from the UK?
If yes then show div.
Else
Div remains hidden.
You can do this using freegeoip.
Since you mentioned that you want to use plain JavaScript (not jQuery), you should use JSONP to get the country:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>UK localisation</title>
</head>
<body>
<div id="myDiv" style="display:none">
<h1>Kittens</h1>
</div>
<script>
function toggleDiv(content) {
console.log(content.country_code);
if(content.country_code === 'GB') //Or GBR, or UK, I'm not sure.
{
document.getElementById('myDiv').style.display = "inline";
}
else
{
alert("You are not from UK, you are from " + content.country_code);
document.getElementById('myDiv').style.display = "none";
}
}
window.onload = function()
{
// create script element
var script = document.createElement('script');
// passing src with callback name
script.src = 'http://freegeoip.net/json/?callback=toggleDiv';
// insert script to document and load content
document.body.appendChild(script);
}
</script>
</body>
</html>
Related
I want to change its script in the head section of the HTML dynamically on clicking the button and want to reload the page with a new script(with its new values) replacing previous one with JavaScript.
/* To change the root api */
function passRoot(data) {
const parsedData = JSON.parse(data);
var newScript = document.createElement("script");
newScript.id = "someID";
newScript.setAttribute("data-root", parsedData["data-root"]);
newScript.setAttribute("api-root", parsedData["api-root"]);
newScript.setAttribute("src", parsedData["src"]);
document.head.appendChild(newScript);
window.location.reload();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script id="someID" api-root="some-api-value" data-root="some-data-value" src="some-src-value"></script>
</head>
<body>
script change:
<textarea style="font-size: 9px; width: 90%; height: 30%" id="passroot">
{"api-root": "enter new value", "data-root": "enter new value", "src":"some-new-src-value"}</textarea
>
<div>
<button onclick="passRoot(document.querySelector('#passroot').value)">
Submit to change script
</button>
</div>
**************html-starts***********************************<br>
stuff I manage with bundle, here I want to load new bundle after providing new url in the src of script tag
</body>
</html>
Please open view frame source in the code snippet to see the script tag.
Please help!
Why you want to change the script tag. If you want to load your js on some event. Let's say button click. Please go for Dynamic import that will run your script file.
When you reload the page the script will be removed. So you need to use localStorage to keep current script attribute:
let scriptData = localStorage.getItem('script');
if (scriptData)
craeteScript(scriptData);
function craeteScript(data) {
localStorage.setItem('script', data)
const parsedData = JSON.parse(data);
var newScript = document.createElement("script");
newScript.id = "someID";
newScript.setAttribute("data-root", parsedData["data-root"]);
newScript.setAttribute("api-root", parsedData["api-root"]);
newScript.setAttribute("src", parsedData["src"]);
document.body.appendChild(newScript);
}
function passRoot(data) {
craeteScript(data);
window.location.reload();
}
So I am running some tests with JS and HTML right now, and one of the things I am doing is appending text to the page with JS every time the button is pressed. How do I keep the html the same after reloading the page? Is there a way to save it's current state so the added text doesn't go away? I'm sorry if this was answered before, I couldn't find any answers on this, nor do I know if it's possible. Thanks in advance!
<!DOCTYPE HTML> <HTML>
<HEADER>
<link rel="stylesheet" type="text/css" href="indexcss.css">
<center>
<b>
<TITLE> </TITLE>
<div id='parentID'>
</div>
<script>
prompt("prompting");
var button = document.createElement("button");
button.innerHTML = "Do Something";
// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
// 3. Add event handler
button.addEventListener ("click", function() {
var div = document.getElementById('parentID');
div.innerHTML += 'Extra stuff';
});
</script>
<h1>
</h1>
</b>
</center>
</HEADER>
<BODY>
</BODY>
use localStorage
set()
document.body.innerHTML += Math.random()
save()
function save() {
localStorage.setItem("html", document.body.innerHTML)
}
function set() {
let content = localStorage.getItem("html")
if(content) {
document.body.innerHTML = content
}
}
<body>
hi
</body>
I want to make a footer credit protection using javascript. I've seen one using jquery. But it didn't worked properly. I want to apply that code to my blogger templates. I've written the following javascript code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function lol(){
var footer = document.getElementById("mycreditlink");
if (footer.hasAttribute("href")) {
footer.setAttribute("href", "http://grplusbd.net");
}
if (footer == null){
window.location.href = "http://grplusbd.net";
}
}
window.onload = function(){lol();};
</script>
</head>
<body>
<div>
Powered By <a href='http://google.com' id='#mycreditlink'>My Site</a>
</div>
</body>
</html>
But it isn't working properly either. I want it to make the footer url change automatically and if the id="mycreditlink" is removed by the client, it will redirect automatically to my website home. I need help immediately. If the code works, I will enode it and add to my templates.
<div>
Powered By <a href='http://google.com' id='mycreditlink'>My Site</a>
</div>
There is a error here: id='#mycreditlink' need to be like: id='mycreditlink'
And
function lol(){
var footer = document.getElementById("mycreditlink");
if (footer.hasAttribute("href")) {
footer.setAttribute("href", "http://grplusbd.net");
}
if (footer == null){
window.location.href = "http://grplusbd.net";
}
}
window.onload=function(){lol();};
or
window.onload=lol();
You can make use of jQuery as I have done below...
<script type="text/javascript">
function lol(){
var footer = jQuery("#mycreditlink");
if (footer) {
jQuery(footer).attr("href", "http://grplusbd.net");
}
else {
window.location = "http://grplusbd.net";
}
}
window.onload = function(){lol();};
</script>
There's something wrong with my script, it doesn't render the JS correctly. I tried to pinpoint the problem but cannot find any typo. If i load the page, the tag is blank, making all css & other JS disabled. But suprisingly the data is loader correctly. If i remove the script, everything went to normal.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui.js"></script>
<script>
// Create a connection to the file.
var Connect = new XMLHttpRequest();
// Define which file to open and
// send the request.
Connect.open("GET", "Customers.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
// Place the response in an XML document.
var TheDocument = Connect.responseXML;
// Place the root node in an element.
var Customers = TheDocument.childNodes[0];
// Retrieve each customer in turn.
$("#middle").ready( function () {
document.write("<ul class='product'>");
for (var i = 0; i < Customers.children.length; i++)
{
var dul = "wawa"+[i];
//document.getElementById(dul).addEventListener('click', storeData, false);
var Customer = Customers.children[i];
// Access each of the data values.
var Pic = Customer.getElementsByTagName("pic");
var Name = Customer.getElementsByTagName("name");
var Age = Customer.getElementsByTagName("tipe");
var sex = Customer.getElementsByTagName("country");
var checked = window.localStorage.getItem("selected"+i);
// Write the data to the page.
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write(".jpg'><a href='display.html?id="+i+"'>");
document.write(Name[0].textContent.toString());
document.write("</a><div class='age'>");
document.write(Age[0].textContent.toString());
document.write("</div><div class='sex'>");
document.write(sex[0].textContent.toString());
document.write("</div><div class='cex'>");
document.write("<input name='checkbox' type='checkbox' id='wawa_"+i+"'");
if (!checked) {
document.write(" onClick='cbChanged(this, "+i+")'");
} else {
document.write("checked onClick='cbChanged(this, "+i+")'");
}
document.write("></div></li>");
}
document.write("</ul>");
});
function cbChanged(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
</script>
</head>
<body>
<div class="container">
<div class="content" id="middle">
</div>
<div class="content" id="footer">
</div>
</div>
</body>
</html>
Ok here's the full source.
You don't close the HTML img tag right
Change
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write("'.jpg><a href='display.html?id="+i+"'>");
// ^ this quote
To
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write(".jpg'><a href='display.html?id="+i+"'>");
// ^ should be here
If you open the developer console you can usually see where errors like this take place. It will also output and javascript errors that you come across so it will make that part a whole lot easier. Do you have any errors in your console?
The dev consoles are:
Chrome: It is built it.
Firefox: Firebug
Safari: It's built it
EDIT:
Don't do var functionName = function() {..} unless you know about how hoisting works. This is contributing to you problem so change
cbChanged = function(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
To
function cbChanged(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
Without the above changes the function cbChanged is not hoisted. So if you call it before it is reached you will get an error.
There are several other things that stand out to me on this. You might want to spend some more time on your javascript fundamentals. Read up on why document.write is a bad thing. Try removing parts of the script to narrow down what is causing the problem. It would have made this easier to fix if you had made a fiddle.
Look at the below code, this JavaScript is used to take a string (in a language other than English) and convert it into English.
<script type="text/javascript">
google.load("language", "1");
function initialize() {
var content = document.getElementById('translation');
// Setting the text in the div.
content.innerHTML = '<div id="text">HELLO WORLD<\/div>
<div id="translation"/>';
// Grabbing the text to translate
var text = document.getElementById("text").innerHTML;
// Translate from Spanish to English, and have the callback of
// the request put the resulting translation in the
// "translation" div. Note: by putting in an empty string for
// the source language ('es') then the translation will
// auto-detect the source language.
google.language.translate(text, '', 'en', function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
google.setOnLoadCallback(initialize);
</script>
I want that the string "HELLO WORLD" must be entered by user at run time in a text field and then that string is passed to the div id text. So is this possible?
Hope you are referring to the document below:
http://code.google.com/apis/language/translate/v1/getting_started.html
Please refer to the section "Getting Started" where it says about "Signing up for an API key". This needs to be done before you could implement the code in your page.
Once done, make the modification to the script file which you include in the html page with your key.
Here, replace your key with "MY_KEY_STRING" in the bottom code and get started.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Language API Sample</title>
<script src="https://www.google.com/jsapi?key=MY_KEY_STRING"></script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
//Show the translate button
document.getElementById("translateButton").style.display = "";
}
google.setOnLoadCallback(initialize);
function translate() {
var text = document.getElementById("fromText").value;
google.language.translate(text, 'es', 'en', function(result) {
var translated = document.getElementById("toText");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
From:<input type="text" id="fromText"/>
To:<span id="toText"></span>
<input type="button" value="Translate" onclick="translate()" style="display: none;" id="translateButton">
</body>
</html>
HTML:
<form id="translate">
<textarea id="translate-me"></textarea>
<input type="submit" />
</form>
JavaScript:
var form = document.getElementById('translate')
var textarea = document.getElementById('translate-me')
form.onsubmit = function () {
google.language.translate(textarea.value, ...)
return false; // prevent default action (form submission)
}
Using jQuery or something similar would make this easier, of course.