There are two pages in my tomcat server.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="onBtnClick()">jump to child</button>
<script>
const msg = {
name:'index.html',
ifor:'I am your parent!'
};
function onBtnClick() {
const childWindow = window.open('./child.html');
childWindow.msg = msg
}
</script>
</body>
</html>
child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="msg-panel"></div>
<script>
const msgPanel = document.querySelector('#msg-panel');
msgPanel.innerHTML = `<span>${msg.name}</span><br><span>${msg.ifor}</span>`
console.log(window.msg);
</script>
</body>
</html>
I want to pass some message( the msg Object in index.html) from index.html to child.html, by the way above.
When I click the button in index.html to open the child.html, sometimes I can get the msg object in child.html, but sometimes I can't.
make the button type="button"
you set the message after opening. Sometimes the computer will be faster and not pass the message before it is shown. Use a timeout to show the message in the child OR
store the message in sessionStorage before calling window.open OR
have the child read the message from the parent:
const msgPanel = document.querySelector('#msg-panel');
msgPanel.innerHTML = `<span>${opener.msg.name}</span><br><span>${opener.msg.ifor}</span>`
console.log(window.msg);
Because you sometimes get that message and sometimes not try to put code from script from index.html in this:
document.addEventListener("DOMContentLoaded", function(event) {
//your code...
}
I think your html is not loaded and you click the button too fast.
Although this is already solved. Another alternative for sending data to a child would be localstorage. Getting and setting is really easy and IE11 is also supported.
localStorage.setItem('msg', 'something important');
let msg = localStorage.getItem('msg');
With that you would also have the ability to send data back and forth by setting event listeners on the localstorage change event like
window.addEventListener('storage', function(e) {
//do some cool stuff here
}
Just in case you want to have a more complex exchange between parent and child.
Related
I am trying to set the element #welcome_banner by using a function in javascript that takes a form submission and sets it to localStorage and then pulls that info and sets it onto an <h1> tag. Apparently it works but only changes the tag for a millisecond and then it disappears! I have tried doing the .innerHTML setting in various places inside and outside of the function clickHandler() and in the main body of the script. I am certain this is something superbasic I am missing.
<!DOCTYPE html>
<html>
<head>
</head>
<script >
//set display name to form submission, set welcome banner to display name
function clickHandler () {
document.querySelector('#display_name').onsubmit = function() {
localStorage.setItem('dn', dn);
document.querySelector('#welcome_banner').innerHTML=changeWelcomeBanner;
}
};
function changeWelcomeBanner () {
var dn = localStorage.getItem('#dn').value;
var welcomeBanner = document.getElementById('#welcome_banner');
welcomBanner.innerHTML = `Hello ${dn}`;
}
</script>
<title>Project 2</title>
<body style="background-color:#ff3300;">
<h1 id="welcome_banner"></h1>
<form id="display_name">
<input id="dn" autocomplete="off" autofocus placeholder="" type="text">
<button>set display name</button>
</body>
</html>
The steps to do this are as follows:
Store the typed text in localStorage, you're doing this in the event handler for the form submission: localStorage.setItem('dn', dn);
When you submit the form, the page is going to refresh from the server. This is why you're only seeing the text briefly, then the page reloads from the server with no knowledge of what was there before.
Look for information about page events and write a handler for the DOMContentLoaded event like you did for your submit event handler. DOMContentLoaded is well supported these days. Something like: document.addEventListener("DOMContentLoaded", function(event) {
// code to check local storage goes here...
});
In that handler you want to check localStorage like you're doing here: var dn = localStorage.getItem('dn').value; and if there is a value there, set the innerHtml of the <h1> to that value, like you're doing here: welcomBanner.innerHTML = 'Hello ${dn}';
I think you might have had a stray # character in your localStorage.getItem call that I removed in the steps above. You might also want to have default text you post if there's nothing found in localStorage when you check.
Here's a simplified example:
If you are calling a function to get the value from Local Storage, be sure you have a return
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1 id="welcome"></h1>
<input type="text" id="something">
<button type="button" id="click">CLICK ME</button>
<script>
document.getElementById("click").addEventListener("click", function(){
var x=document.getElementById("something").value;
document.getElementById("welcome").innerHTML=x;
localStorage.setItem('x', JSON.stringify(x));
document.getElementById("welcome").innerHTML = getData();
});
function getData(){
var retrieve=localStorage.getItem('x');
return JSON.parse(retrieve); //Now return the value
}
</script>
</body>
</html>
Hello I'm new to javascript, and I'm try to write out some code for a test site and I'm having some problems, dow below is my code and I keep getting this error and i can't figure out why.
TypeError: null is not an object (evaluating 'document.getElementById("h3").innerHTML = "<h3>You Are up to date!</h3>"')
This is my second method i tried using. what I'm trying to do it have a have a version list this first one i had was that it would pull a .js file and build a table, but that didn't work so i thought i would try this, but guess what happened? not working
my code that I'm using now is below. if you can help that would be amazing.
thanks, Dakmessier
var current = "1.0";
function get_latest(){
document.getElementById("bob").innerHTML = current;
}
if (local != current){
document.getElementById("Get").innerHTML = "<button>Get the Latest Update!</button>";
} else if (local == current){
document.getElementById("h3").innerHTML = "<h3>You Are up to date!</h3>";
} else {
document.getElementById("h3").innerHTML = "<h3>Sorry, unable to check for update.</h3>";
}
document.getElementById(id) finds an element with a given id value in your HTML. An id value looks like this:
<div id="myHeader">Some Content</div>
And, then you can find that element with:
document.getElementById("myHeader");
ID values must be unique in each document so there should only ever be one element with a given ID.
If an id isn't what you really want, you can find elements other ways, by tag type, by class name, by attribute, etc... using CSS selectors with document.querySelectorAll().
For example, if you wanted to find all <h3> tags, you could do this:
var items = document.querySelectorAll("h3");
Here are some other reasons that document.getElementById(...) might fail to find what you want it to find:
The Javascript code is running before the DOM elements have been parsed and loaded so thus the element is actually not there yet when you're running the code. This is common with code run from the <head> section of the document.
You have an HTML error in how you are specifying the id value in the HTML.
You have an HTML error that causes the browser not to parse your HTML properly.
You have a script error that cause your script to abort before it gets to the part you want to run.
Indeed document.getElementById returns null if it can't find an element with the Id specified.
Also the statement:
if (local != current){
// ..
} else if (local == current){
// ..
} else {
// ..
}
is a bit odd. If local != current is false then local == current must be true. The else if (...) is redundant and the else part will never be run.
hey man the bast thing you should do is the following example, feel free to copy it on your snippet of code:
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
<!DOCTYPE html>
<html>
<body>
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
</body>
</html>
I WILL EXPLAIN YOU THIS ANSWER: this is an html + an inline script that makes the inner html work. As far as concerned with your answer it was unclear where your code stopped, anyway test my snippet of code and let me know
I know it's an old question, but I was having the same issue and was trying hard to find the solution for some time.
The problem was that I was executing the script before the page loaded. Thus it wasn't able to find the object that we're trying to catch.
So either use jquery document.ready function or else move your script to the end of the html.
I hope this helps
fix an error of getting the value of a as null
Uncaught TypeError: a is null
code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script>
let a = document.getElementById('i');
document.addEventListener('mouseup',function(){
a.innerHTML='clean';
})
</script>
<body>
<h3 id="i">not clean</h3>
</body>
</html>
this shows as error in console as
Uncaught TypeError: a is null
you can fix it by making your script tag before
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3 id="i">not clean</h3>
<script>
let a = document.getElementById('i');
document.addEventListener('mouseup',function(){
a.innerHTML='clean';
})
</script>
</body>
</html>
this might fix!!
I wrote the following code in JavaScript to open a popup window when a button is pressed, and then use setInterval to move the window every 2 seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "utf-8">
<title> Javascriptin' Some Codes </title>
<script>
function hi() {
var printOut = window.open("http://www.google.com","_blank", 'height=200, width=200');
setInterval(function() { printOut.moveBy(10,10);}, 2000)
window.alert("hi");}
</script>
</head>
<body>
<button onclick="hi()"> Try me </button>
</body>
</html>
The window opens, but the setInterval doesn't appear to work- the window does not move after being launched. I was wondering why my code doesn't work, and what I could do to make it function the way I'd like it to.
The opened url has to be on the same domain as stated in this answer (DEMO).
For example on jsfiddle, this works:
var printOut = window.open("http://fiddle.jshell.net","_blank", 'height=200, width=200');
And that one doesn't:
var printOut = window.open("http://www.google.com","_blank", 'height=200, width=200');
You should also remove the alert, although it works in chrome it seams to break it in for example opera.
I want to be able to open a popup using window.open and subscribe to page events (onload etc) of the popup in the opener. So i'd want a method in my opener (parent page) to execute when the popup's onload or ready fires. Is this possible using plain js or jquery? Pls don't ask me why i want to do this - this can solve a lot of issues for me.
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>
Works for me...
I allow the user to store a domain in local storage (e.g. http://192.168.1.104). My method of pulling the domain out of local storage is like this:
<script type="text/javascript">
domain = localStorage['domain'];
function DOMAIN(dive) {
window.location=domain+dive;
}
</script>
and I can open it like this:
CLICK HERE
or
CLICK HERE
but I can't seem to get it to allow opening in a new tab (chrome v13). It's driving me nuts, any suggestions?
Try this:
CLICK HERE
Lets see if this works for you:
CLICK HERE
Okay, I figured it out, but it's a little hacky and restless. Make a dummy html document, say /html/home.html for instance. Call the js-function inside the dummy doc:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Ripping Status</title>
<script type="text/javascript">
domain = localStorage['domain'] || '';
function init() {
window.location=domain+'/';
document.getElementById( 'box' );
};
</script>
</head>
<body onload="init();">
<div id="box"></div>
</body>
</html>
where 'domain' is stored as, say, http://192.168.1.101. Now, call /html/home.html inside the main html document via
CLICK HERE
and it allows right click > open new tab, window, etc as you would expect.