I'm creating a function that opens an existing html template page of which I want to update the data "passed as argument" from the function itself.
(I'm doing this to avoid hardcoding multiple pages, so to dynamically create a page for the client based upon what he clicks from a menu, not sure is this is the right way to go about it, but this is what I come up with).
Is it possible with Vanilla JavaScript , if so and how?
Here is my code example:
<!DOCTYPE html>
<html>
<head>
<script src="js/tester.js"></script>
<title>Document</title>
</head>
<body>
<button onclick="load('dpdate one', 'update two', 'update three')"> Update </button>
</body>
</html>
This is the template page:
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<script src="js/tester.js"></script>
</head>
<body>
<p class="one">Not updated</p>
<p class="two">Not updated</p>
<p class="three">Not updated</p>
</body>
</html>
This is my JavaScript function:
function load(one, two, three) {
console.log('Loadin new page with data!');
window.location.href = 'http://127.0.0.1:5500/newPageTemplate.html';
// window.location.assign('http://127.0.0.1:5500/newPageTemplate.html');
// window.location.replace('http://127.0.0.1:5500/newPageTemplate.html');
const dataOne = document.getElementsByClassName('one')[0];
const dataTwo = document.getElementsByClassName('two')[0];
const dataThree = document.getElementsByClassName('three')[0];
dataOne.innerText = one;
dataTwo.innerText = two;
dataThree.innerText = three;
}
When clicking the button it does redirect but it does not update the data.
How to do that?
FYI: If this is achieved what will happen if multiple user click the same at the same time?
I found an hacky solution that works however.
I save the data I need into local storage like so:
localStorage.one = 'Anything you want to save';
localStorage.two = 'Anything you want to save';
localStorage.three = 'Anything you want to save';
This data will persist even after page redirect and can be utilized in a window.onload function like so:
window.onload = (event) => {
console.log(localStorage.one);
console.log(localStorage.two);
console.log(localStorage.three);
}
This solution works, however before using check as not really sure about security issues or other. Use at your own risk.
Related
Totally new to JavaScript. As in, today.
From an .html file on my MacBook desktop, I want to open TWO webpages. The first is the file itself, say from the command line, as follows:
open ~/Desktop/first.html
The second webpage is one that I call from the first.html file:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>JavaScript stuff</title>
</head>
<body>
<script>
w = window.open('https://fireship.io/courses/javascript/beginner-js-where-to-run/');
const elements = w.document.querySelectorAll('*');
const count = elements.length;
alert(count)
elements.forEach((elem) => {
console.log(elem)
});
</script>
</body>
</html>
WHAT I WANT TO BE HAPPENING is that w.document.querySelectorAll('*') is getting all elements in the second webpage, meaning https://fireship.io/courses/javascript/beginner-js-where-to-run/. WHAT'S ACTUALLY HAPPENING, though, is that the elements from first.html are returning. This is confirmed by inspecting the console output of first.html.
So, my general question is --- How do I loop through the elements of one webpage from scripting that resides in another?
Any help or direction is much appreciated!
Justin
I´m a beginner and for my first project I´d like to make a text based game.
I´d like the player to input his name into a field and then display his name on following pages.
I choose to to this with localStorage because I do not know any server-side programming yet.
If possible, I would like to not use a javascript library.
I think, I´m gettin the value of the user the right way:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
// Gets input value
var uName = document.getElementById("myInput").value;
// Saves data to retrieve later
localStorage.setItem("userName", uName);
// Updates HTML
updateHTML();
}
</script>
</head>
<body>
set user name:
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
</body>
</html>
The second page looks like this:
<!DOCTYPE html>
<html>
<head>
<script>
function getName() {
return localStorage.getItem("userName");
}
function updateHTML() {
var uName = getName();
document.getElementById("storedName").innerHTML = uName;
}
</script>
</head>
<body class=backgroundcomputer001>
"Welcome back <p id="storedName"></p>
</div>
</body>
</html>
I don't know what I am doing wrong, and I already spent more than two days on this problem.
Any help appreciated.
( I know that I should keep the javascript and the html seperated, but it is more easy for me to visualize what is happening.)
So first the updateHTML function is not called anywhere. You have declared it but haven't called it. You can add updateHTML(); to the end of your script and it will be executed. The second problem is that even in this case the code wouldn't be able to display the name because of the following error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
This means that at the moment the function was executed the document wasn't still completely loaded. As a solution you can put your script just before closing body tag.
<!DOCTYPE html>
<html>
<head>
</head>
<body class=backgroundcomputer001>
<div>
Welcome back <p id="storedName"></p>
</div>
<script>
function getName() {
return localStorage.getItem("userName");
}
function updateHTML() {
var uName = getName();
document.getElementById("storedName").innerHTML = uName;
}
updateHTML();
</script>
</body>
Instead of using the function updateHTML(); what you need is to redirect to the following HTML and you have to do it with this instruction:
window.location.href = "index.html"; // name of your html that presents the username
And for the HTML where it presents the user name, add a function that is executed when it finishes reloading the HTML, like this:
<script>
window.onload=function() { //This function is executed when loading the page
var uName = localStorage.getItem("userName");
document.getElementById("storedName").innerHTML = uName;
}
</script>
And to present the name and this next to the welcome you can do it like this
<p>"Welcome back <span id="storedName"> </span></p>
Sorry for my english but i hope i have solved your problem. Happy quarantine :D
I am building a website in which I have added a function to change the theme. However, the issue is that I have many pages in my websites and, when I move to the next page, it resets the default value. I want to select the theme only once and then keep it in my whole website.
You can use localStorage to persist data. It will be accessible from each page of your site.
This is a barebones example, and I urge you to do more research on localStorage, such as how to determine whether there is enough space to store data. And also do some checks to determine whether the data you're looking for exists.
Source: https://snippets.cacher.io/snippet/fdc6f8a598f1395092e7
Sample:
Page 1:
<!doctype html>
<html lang="en-us">
<head>
</head>
<body>
<p id="paragraph">Hello</p>
<p id="loadedText"></p>
<button onclick="load();">Load</button>
<button onclick="save();">Save</button>
Next page
<script>
function load() {
var element = document.getElementById("loadedText");
element.innerHTML = localStorage.getItem("text");
}
function save() {
var text = document.getElementById("paragraph").innerHTML;
localStorage.setItem("text", text);
}
</script>
</body>
</html>
Page 2:
<!doctype html>
<html lang="en-us">
<head>
</head>
<body>
<p id="loadedText"></p>
Previous page
<script>
var element = document.getElementById("loadedText");
var text = localStorage.getItem("text");
element.innerHTML = text;
</script>
</body>
</html>
So my c# application downloads a page from my website, that's fine and all but i want to control what values it downloads, as an example, i have a page that has 2 buttons, 'run' and 'stop', depending on which button i click, it sets the title of the page, i want the c# application to download the page and either get 'run' or 'stop' but heres the problem.... im only getting the default set value 'My title' instead of the buttons values... i asked other people and they told me you need to make a dynamic/server-side page, but im not sure how to do it...
here's the page (index.html)
<!DOCTYPE html>
<html>
<head>
<title>My title</title>
</head>
<body>
<button onclick="myFunction()">Run</button>
<button onclick="myFunction2()">Stop</button>
<script>
function myFunction() {
document.title = "run";
}
function myFunction2() {
document.title = "stop";
}
</script>
</body>
</html>
so yea i click 'run' or 'stop' and that sets the name of the title, however, c# application downloads page and does not *consider the button change effect
static void Main(string[] args)
{
WebClient web = new WebClient();
String html = web.DownloadString("http://www.adanyeva.org");
MatchCollection m1 = Regex.Matches(html, #"<title>\s*(.+?)\s*</title>", RegexOptions.Singleline);
//html text: <strong>Tampa, FL</strong>
// \s*: multiple spaces til it finds something
//(.+?): look for any character
//var kim = m1[0];
Console.WriteLine(m1[0]);
Console.ReadKey();
}
when this runs, i get this output:
<title>My title</title>
what should have been outputted:
<title>run</title>
or
<title>stop</title>
I need to have the Javascript written by the user on one page to be saved and used for the next page. By this, I mean, I need to grab the contents of a div, and somehow save that into a .JS file, which wil automatically run as the next page loads. Is there a way in which I could do this, Or is there another way in which this could be achieved?
Basically, something along the lines of what Codecademy has done, but not live?
If you are just working on a local project (nothing server side). you could store the value to localStorage.
// page 1
<!DOCTYPE html>
<html>
<body>
<div contentEditable="true" id="i1"></div><button id="b1">open next page</button>
</body>
<script>
var div = document.getElementById('i1'), text = "desired value";
div.innerText = text;
document.getElementById('b1').onclick = function(){
localStorage['div value'] = div.innerText; window.open('page2.html'); window.close('page1.html');
}
</script>
</html>
// page 2
<!DOCTYPE html>
<html>
<body>
<p id="p"></p>
<button id="b2">go back</button>
</body>
<script>
p.innerText = localStorage['div value']? localStorage['div value']: "There is no value in your div";
b2.onclick = function(){ window.open('page1.html'); window.close('page2.html'); }
</script>
</html>
If you are ready to change the architecture, I have a question as your answer. Have you tried single page JS applications through AngularJS, EmberJS, Backbone etc?
you don't need to save into a .JS file
you need to post the JS to the server, then render it to the next page
i'm the next page
<script>
// user's code
</script>