Pages manipulation with JavaScript - javascript

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>

Related

How to open a new page with new data with Vanilla Javascript?

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.

How to get reference to the iframe from which script html tag was generated?

I have small snippet that is inside iframe and generates script html tag and appends it to the window.top.document.head.
Now I want to know how do I check from within potato.js from which iframe it was generated from once it is already loaded?
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<iframe>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
(function() {
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src','https://test.com/potato.js');
window.top.document.head.appendChild(s);
})();
</script>
</body>
</html>
</iframe>
</body>
</html>
Edit: I can not change this code inside the iframe
That information isn't stored automatically.
The only way I can think of would be to add an expando-prop to the script with a reference to the current window (i.e. the frame's window)…
s.sourceWindow = window;
… then read that from within potato.js …
const sourceWindow = document.currentScript.sourceWindow;
… and then loop over all the frames (window.frames) looking for a match.
Since you are using window.top and not window.parent you might need to be recursive there.

How do I call the JavaScript function properly?

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Example</title>
<script>
function displayString() {
return "<h1>Main Heading</h1>"
}
displayString();
document.write("Execute during page load from the head<br>");
</script>
</head>
<body>
<script>
document.write("Execute during page load from the body<br>");
</script>
</body>
</html>
So this is my problem. No matter where I put the displayString(), the h1 just never seems to show up on the browser. Can anybody please help me see where I am wrong? I am new to JavaScript. Oh, and what I am trying to do is to call the function.
You need to write the returned String to the document:
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Example</title>
<script>
function displayString() {
return "<h1>Main Heading</h1>"
}
document.write(displayString());
document.write("Execute during page load from the head<br>");
</script>
</head>
<body>
<script>
document.write("Execute during page load from the body<br>");
</script>
</body>
</html>
No matter where I put the displayString(), the h1 just never seems to
show up on the browser.
If you wish to add a new element to a document, several approaches are available:
document.write (effectively deprecated)
.innerHTML (sometimes useful, but can be slow)
DOM API - recommended approach
The recommended approach is to use the DOM API.
DOM stands for Document Object Model. Essentially it's the markup of your document represented as a tree-like structure of nodes. There are many DOM API functions which allow you to:
add
remove
append
prepend
insert
update
new DOM nodes.
Any DOM node may be added, removed or updated, including:
parent elements
child elements
sibling elements
element attributes
ids, classNames, classLists
custom data-* attributes
text nodes
Here is an example:
function displayMainHeading () {
let mainHeading = document.createElement('h1');
mainHeading.textContent = 'Main Heading';
document.body.prepend(mainHeading);
}
displayMainHeading();
<p>Paragraph 1</p>
<p>Paragraph 2</p>
Further Reading
This is a good primer to get you started:
A Beginners Guide To DOM Manipulation by Iqra Masroor

Browser ignores Javascript [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
Rookie alert!
Would you tell me why my Javascript code doesn't update the message. The browser runs HTML but ignores the Javascript code. What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>
</body>
</html>
You're running the Javascript before you've loaded the body, the message element doesn't exist yet. Either move the script to the end of the <body>, or change the last line to:
window.onload = updateMessage;
so that the function will be loaded after the HTML is loaded.
If the <script> tag is in the <head> element, it gets executed before the HTML elements in the <body> are created. You can put your script tag inside the <body> element, at the end of it, to solve the issue.
Assuming you don't simply have javascript disabled, you could add a window.onload=function(){ surrounding your code.
window.onload=function(){
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
}
The reason for doing this is because your javascript code is inside your <head>. Thus, the javascript is loaded before the body. When the browser attempts to execute the javascript code, the message element isn't loaded yet and doesn't exist. By adding window.onload=function(){ to surround your code, your entire code will wait until the body is loaded before executing.
When you call your javascript code, the 'message' element isn't already there. I would suggest one of the following two things:
+Put your javascript code at the end of the body ( note that it only need to be after 'message', but putting it at the end is generally the best option )
+Replace your call with window.onload = updateMessage, which will wait until all the page is loaded to execute your javascript
There are already lots of duplicate answers here but there is another way, especially if you want to keep your Javascript code in a script tag in the head. And that is, wrap your Javascript function call in setTimeout -- this causes the function to be executed after the DOM has been parsed, but before the entire window has been loaded.
It's a neat little trick that can be used when you don't have a framework's (such as jQuery) document/ready functionality. window.onload or putting the script at the bottom might cause significant delays if there is lots of heavyweight content (large images?) in the page.
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
setTimeout(updateMessage);
</script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site!</div>
<img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
</html>
Notice I have added a very large image to the page, but the updated message displays before the image fully loads.
If however instead of setTimeout(updateMessage); you use window.onload = updateMessage; as suggested in the currently accepted answer, your message will not get updated until the entire image loads (if you try this out, make sure you do a hard refresh after the first time so you are not getting it from your cache). Same goes for moving the script too far down the page (below the very large image for instance) as below. I honestly think, if you don't have a framework's document/ready functionality, using setTimeout in a script block in the head is the best solution.
MESSAGE NOT UPDATED UNTIL AFTER IMAGE LOADS:
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site!</div>
<img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</html>
You are trying to make the changes before the DOM is loaded. See the code below,
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>
</body>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</html>

Javascript access to other page

Can I have access from javascript on one page to elements on other page the script has created before? Something like this:
var win=window.open("http://www.ftwars.com/battle",'myWindow');
win.document.getElementById('center').onClick();
Simply yes - you can , via variable reference, you cannot reach reference if you not created it in your javascript
You are correct. From the context you have given above, win is like any other object.
First page (x.html):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var w = window.open('y.html', 'w');
w.document.getElementById('target').onclick = function () { alert('!'); };
</script>
</body>
</html>
Second page (y.html):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="target">target</button>
</body>
</html>

Categories

Resources