Unbeleivable, same Javascript code do not behave the same way in JSFiddle - javascript

I wrote the same code in two JSFiddle, and they do not behave the same way :
HTML:
<p id='complete'></p>
JS:
document.onreadystatechange=fnStartInit;
function fnStartInit()
{
var state = document.readyState
if (document.readyState === 'complete')
{
document.getElementById('complete').innerHTML = 'Document completely loaded'
}
}
Working JSFiddle: https://jsfiddle.net/Imabot/toujsz7n/9/
Non working JSFiddle: https://jsfiddle.net/Imabot/3sLcpa0y/7/
Why do they not behave the same way?

Your first link has the load setting "No wrap - bottom of <head>".
This is equivalent to having HTML like
<head>
<script>
// YOUR SCRIPT HERE
</script>
<head>
<body>
// YOUR HTML HERE
</body>
Your second link has the load setting "On Load":
This is equivalent to having HTML like
<head>
<script>
window.onload = function() {
// YOUR SCRIPT HERE
}
</script>
<head>
<body>
// YOUR HTML HERE
</body>
You can see this if you Inspect the iframe in the lower right. So by the time the second script runs, readystatechange never fires again, so fnStartInit never runs.
Here's a Stack Snippet demonstrating the same problem:
window.onload = () => {
console.log('onload');
document.onreadystatechange = () => {
console.log('ready state just changed');
};
};

Related

How can I run code in the onload event in a file and in a script tag

I wish to add code to a click event in a file and a script tag. But they seem to conflict. How can I achieve this?
javascript:
window.onload = function()
{
document.getElementById("button3").addEventListener("click", respond3);
}
function respond3(e)
{
alert("Way to go!!");
}
html:
<head>
<title>Second Javascript</title>
<script src="Second.js"></script>
<script>
window.onload = function()
{
document.getElementById("button2").addEventListener("click", respond);
}
function respond(e)
{
alert("getting better");
}
</script>
</head>
<body>
<h1>The quick brown fox jumps over the lazy dogs</h1>
<button onclick='alert("bad practice");'>Inline</button>
<button id='button2'>Script tag</button>
<button id='button3'>Separate file</button>
</body>
Per Quentin's suggestion I changed the script tag to this:
<script>
window.addEventListener('load', AddClick2)
function AddClick2()
{
document.getElementById("button2").addEventListener("click", respond);
}
function respond(e)
{
alert("getting better");
}
</script>
The on* properties can only have one function assigned to them. It's not so much a conflict as you are simply overwriting the first onload function with the second.
While you could do something along the lines of checking to see if there is already a function there, then copying it to a new variable, then calling it from the new variable inside your new onload function … that gets messy.
Use addEventListener instead.
window.addEventListener('load', a_function);
window.addEventListener('load', a_different_function);

Multiple Javascript files are not working

I'm new to Javascript. I would like to include more than two js(javascript) file. When I type something(text) on the input filed particuar function is not executing.
only last js file(three.js) is working. what I'm missing please let me know.
my code:
Text.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>Myweb</title>
</head>
<script src="one.js" type="text/javascript"></script>
<script src="two.js" type="text/javascript"></script>
<script src="three.js" type="text/javascript"></script>
<style>
</style>
<body>
<h1>Hello World!</h1>
<input type='text' placeholder='enter name' id='name'><br><br>
<input type='text' placeholder='enter uname' id='uname'><br><br>
<input type='text' placeholder='enter fname' id='fname'>
</body>
</html>
one.js
window.onload = initPage;
function initPage() {
document.getElementById("name").onchange=namefun;
}
function namefun(){
var name=document.getElementById("name").value;
alert("name:"+name);
}
two.js
window.onload = initPage;
function initPage() {
document.getElementById("uname").onchange=unamefun;
}
function unamefun(){
var uname=document.getElementById("uname").value;
alert("uname:"+uname);
}
three.js
window.onload = initPage;
function initPage() {
document.getElementById("fname").onchange=fnamefun;
}
function fnamefun(){
var fname=document.getElementById("fname").value;
alert("fname:"+fname);
}
Any help
Thanks
you are resetting the window.onload function each time. so that the only last one is executing.
Try this one:
window.onload = initPage;
function addEventHandler(obj, eventName, handler) {
if (document.attachEvent) {
obj.attachEvent("on" + eventName, handler);
} else if (document.addEventListener) {
obj.addEventListener(eventName, handler, false);
}
}
function initPage() {
addEventHandler(document.getElementById("name"), "change", namefun);
addEventHandler(document.getElementById("uname"), "change", unamefun);
addEventHandler(document.getElementById("fname"), "change", fnamefun);
}
That is because the last file redefines the initPage function and reassigns window.onload.
You can't have multiple functions with the same name and if you want to use multiple callbacks for the load event you'll have to set them using .addEventListener.
All the files write things to the global scope of JS names, which means that your initPage function overwrite each other, and as consequence, only the last one is used. You also overwrite the value of onload, so only one of them would be called anyway. Try using addEventListener instead, like here: https://stackoverflow.com/a/25984032/1832228 .
you are resetting the window.onload function each time.
You have initialized window.onload 3 times means you are resting it so that the only last one is an assignment that is assigned to window.onload so that last one is only executed.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(func1);
addLoadEvent(func2);
addLoadEvent(func3);
Here's what I learned that I wish someone would have told me when I been surfing the internet for days because I had a similar problem to yours. Where I had multiple js files in one HTML, and only one of them would work.
So here's the thing:
window.onload overrides other window.onload events. So if I had for example.
one.js:
window.onload = function(){
elem1.innerHTML = "Hello world ONE"
}
two.js:
window.onload = function(){
elem2.innerHTML = "hello world TWO"
}
Whichever loads last will override all the onload events that previously loaded. So in the above two codes, the output would more likely be hello world TWO considering that it would load last.
SOLUTION:
IS ... using
window.addEventListener("load", function(){
// your code goes here
)}
Using window.addEventListener("load", function(){ ... }), you can have as many files in the same html file as you would like.
for more reference https://adnan-tech.com/difference-between-window-onload-and-window-addeventlistener/

javascript postmessage doesn't work

i have 2 sites, and i want to use javascriptpostMessage between them.
on my main site i write the following code in an emty html file :
<html>
<script>
window.addEventListener("message",listener_,false);
function listener_(event) {
console.log('ok!');
<html>
<script>
window.addEventListener("message",listener_,false);
function listener_(event) {
console.log('ok!');
//console.log(event);
//console.log(event.data);
}
</script>
</html>
and in other site that i want to call the postmessage from the i write the following code:
<script type="text/javascript">
window.onload = function() {
testfunction();
};
function testfunction(){
var childWin = window.open("http://my-main-site.com/indexjava2.html","child");
childWin = postMessage('message','*');
console.log(TipaltiIframeInfo.height);
}
</script>
but it doesn't work after a lot of tries. i mean
console.log('ok!'); or console.log(event); console.log(event.data);
doesn't trigger on console of main site,
what to do?
thanks
Aside from the fact that you've got a <script> and an <html> tag in the middle of your code for the receiving page and you're defining and adding the event listener twice, you're also not use postMessage correctly. Instead of this:
childWin = postMessage('message', '*');
...it should be this:
childWin.postMessage('message', '*');
If you want to learn more about postMessage, read this.
The other issue is that the message won't be received by the newly-opened page unless the page is opened before the message is sent. You're trying to send the message immediately after opening the new page, and the message is reaching the new page before the event listener is added. You could get around this with a setTimeout, but if the new page takes longer to load then this might also be unreliable.
// This is what NOT to do:
setTimeout(function() {
childWin.postMessage('message', '*');
}, 1000);
Instead, the better way is for the child page to tell the parent page when it's loaded. Then the parent and child can communicate reliably.
Here is the full corrected code, sending page first:
<script>
var childWin;
window.addEventListener('message', messageListener, false);
function messageListener(event) {
if(event.data == 'ready') {
childWin.postMessage('hello second page', '*');
}
}
window.onload = function() {
childWin = window.open('http://my-main-site.com/indexjava2.htm', 'child');
};
</script>
And the receiving page:
<script>
window.addEventListener('message', messageListener, false);
function messageListener(event) {
console.log(event.data);
}
window.opener.postMessage('ready','*');
</script>

I can't figure out how to get my javascript onclick event to work

When I click on the button nothing happens unless I call the function in the html. I am trying to remove all inline javascript. I have included the commented-out section of html that works. Thanks in advance for the help!
JavaScript:
var welcomeString;
const TEST = 1;
function setWelcomeString() {
"use strict";
welcomeString = prompt("Please enter your name: ", "nobody");
}
function writeOutput() {
"use strict";
document.getElementById("demo").innerHTML = "Hello, " + welcomeString;
}
function main() {
"use strict";
setWelcomeString();
document.getElementById("sayHi").onclick = writeOutput();
}
main();
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>**SET TITLE**</title>
<link href="css/style.css" rel="stylesheet">
<script src="firstScript.js"></script>
</head>
<body>
<h1 id="wiggles">TEMPLATE</h1>
<!--<button id="sayHi" onclick="writeOutput()">Say Hi</button>-->
<button id="sayHi">Say Hi</button>
<p id="demo"></p>
</body>
</html>
When you assign a function as a handler for an event, you need to assign the function itself, not execute the function and assign it's return value as you are doing. Change this:
document.getElementById("sayHi").onclick = writeOutput(); // parens
To this:
document.getElementById("sayHi").onclick = writeOutput; // no parens
Here is a jsfiddle link with a working example.
You have to add your whole code inside load, like this
window.load = function(){
// your javascript here
};
Also, as jbabey mentioned, use either
document.getElementById("sayHi").onclick = function(){ writeOutput();};
Or
document.getElementById("sayHi").onclick = writeOutput;
You have two issues.
The first being covered by jbabey.
The second is that firstScript.js appears before your button. This is problematic as when you are assigning the onClick handler to it. It doesn't exist in the dom.
Try putting the entire main script inside window.onload = function () { ... } or moving it to the bottom of the markup.

Detaching and AppendingTo on Window Resize

So I am trying to detach and appendTo a div based on window size. The following is what I currently have.
I am creating a function with a variable SOCIALBAR assigning it equal to #SOCIALMEDIA and detaching it. Then based on window size for (document).ready and (window).resize, I call the SOCIALBARPlACEMENT function and #SOCIALMEDIA is either appendeto the #TOP or #LEFT divs.
This works fine and dandy on (document).ready but does not work for (window).resize.
In fact, if I remove document.ready, and leave window.resize, the function still runs on page load, but doesn't work on page resize.
Any thoughts would be appreciated. Thank!
function socialbarplacement() {
var socialbar;
socialbar = $("#socialmedia").detach();
if (jQuery(window).width() < 1384) {
socialbar.appendTo("#top");
} else {
socialbar.appendTo("#left");
}
};
$(document).ready(socialbarplacement());
$(window).resize(socialbarplacement());
You are calling the functions immediately rather than passing them as event handlers, try:
$(document).ready(socialbarplacement);
$(window).resize(socialbarplacement);
/*
someFunction() <-- invokes the function and resolves to the returned value
someFunction <-- resolves to the function reference
*/
I would probably do something along these line (untested code):
$(window).resize( function(){
var wnd = $(window), soc = $('#socialmedia');
return function(){
// might add a check to make sure you are not appending to the current parent.
soc.appendTo( $(window).width() > 1384 ? '#left' : '#top');
}
});
Resize will get fired when the page loads so you don't need to have both on ready and resize.
Also looking at it, you are executing the method when you really should be passing it in by name.
I,ve try like this... Enjoy!
$(function () {
if (matchMedia) {
var mq = window.matchMedia('(max-width: 1384px)');
var socialmedia = $("#socialmedia");
mq.addListener(WidthChange);
WidthChange(mq);
}
function WidthChange(mq) {
if (mq.matches && socialmedia) {
socialmedia.appendTo("#top");
socialmedia = null;
} else {
socialmedia = $("#socialmedia").detach();
socialmedia.appendTo("#left");
}
};
});
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="top">
<div id="socialmedia">SOCIALMEDIA</div> <br>
**TOP**
</div>
<div id="left">
<br>
**LEFT**
</div>
</body>
</html>

Categories

Resources