body onload and window.onload at the same time - javascript

Can I use body onload and window.onload at the same time? I've tried it using this code
<body onload = "alertFirst()">
</body>
<script>
window.onload = alertSec;
</script>
But it didn't work. I just need someone to confirm it to me. Many thanks

The answer to your question is "no". However there are ways around it.
Adding both calls to one onload function is ideal, but if you /have/ to add an onload handler after one is already added, and you are not using a framework which facilitates this, you can get by like this:
<html>
<head>
<script type="text/javascript">
function alertFirst(){
alert('First');
}
function alertSec(){
alert('Second');
}
</script>
</head>
<body onload="alertFirst();">
content
</body>
<script>
var func = document.body.onload;
window.onload=function(){
func();
alertSec();
}
</script>
</html>

You can (by adding event handler(s)) but you should NOT have both
Instead add the call to the window.onload:
<html>
<head>
<script>
window.onload = function() {
alertFirst();
alertSec();
}
</script>
</head>
<body>
</body>

No, document.body.onload is actually mapped to window.onload. You can check yourself—when you have <body onload="a()"> and to console.log(window.onload), a() is printed out into the console.
What you can do is to have one onload event handler that calls two other functions.
window.onload = function () {
a();
b();
};
or two event listeners
window.addEventListener('load', a, false);
window.addEventListener('load', b, false);

If one or more of the scripts you want to use has the event handler in the BODY HTML tag, you can still move it to into javascript code. See the example below:
Script #1:
<script language="javascript">
function start(){
...code for script #1...
}
</script>
<body onload="start()">
Script #2:
<script language="javascript">
function init(){
...code for script #2...
}
window.onload=init;
</script>
Result:
<script language="javascript">
function start(){
...code for script #1...
}
function init(){
...code for script #2...
}
window.onload=function(){
start();
init();
}
</script>
<body>
I think it may can help you.

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);

JavaScript: Call iFrame Function from Developer Console

I need to call a function which is in iFrame from developer console. But I'm unable to do that.
I tried the following and I get a error that its not a function.
document.getElementById('firstWindow').contentWindow.document.myFunction()
window.frame["firstWindow"].myFunction()
The scritp is inside
document.getElementById('firstWindow').contentWindow.document. But how do I call it?
Here is how the code looks like:
<html>
<body>
<--- Content from iFrame -->
<iframe id="firstWindow" name="firstWindow" src="/test">
<html>
<head>
<script>
myFunction(){
console.log('test');
};
</script>
</head>
<body>
some text
</body>
</html>
</iframe>
</body>
</html>
There are several ways to call the iframe function.
Way 1
In your case, you can use document.getElementById("firstWindow").contentWindow.myFunction() to trigger.
Way 2
Use window.frames.
window.frames is an array, you can set the iframe name with window.name="this is iframe test" in "test.html"
Then you can iterator the array, and compare the name, then trigger it.
for (let i = 0; i < window.frames.length; i++) {
if (window.frames[i].name === "this is iframe test") {
window.frames[i].myFunction()
}
}
Way 3
Use postMessage.
In the way1 and way2, you need to assign function in the window object.
<body>
<script>
// this one
window.myFunction = function(){}
// or this one
function myFunction(){}
</script>
</body>
In the Way3, you can hide the myFunction then you also can trigger it.
Here is an example.
// a.html
<html>
<body>
<iframe id="firstWindow" src="/b.html">
</iframe>
<script>
setTimeout(function(){
document.getElementById("firstWindow").contentWindow.postMessage({data: "hi"});
}, 500)
</script>
</body>
</html>
// b.html
<html>
<body>
<script>
(function() {
function myFunction() {
console.log("test");
}
window.addEventListener("message", (event) => {
myFunction()
})
})()
</script>
</body>
</html>
Then in a.html, you can try use the way1 or way2, like document.getElementById("firstWindow").contentWindow.myFunction().
myFunction will not be called becuase the scope problem.

Onload function for change style doesn't work

Well, i want that when body is completely loaded then call a function for show a hide image. I tryed a lot of things and searched a lot but anything work. I think it's pretty simple and easy but i don't know why doesn't work...I wish that anyone be able to help me.
<body onload="start()">
<div id="bg" style="display:none"></div>
</body>
function start() {
document.getElementById("bg").style.display = 'block';
}
Here Jsfiddle link
you have to option:
1- add script at before starting
<script type="text/javascript">
$(document).ready(function () {
//Add your code here to run after fully page load
document.getElementById("bg").style.display = 'block';
});
</script>
2- or add your script at end of <body> before ending </body> tag:
<script type="text/javascript">
//Add your code here to run after fully page load
document.getElementById("bg").style.display = 'block';
</script>
just remove onload="start()" from your body and replace your function start for
<script>
window.onload=function() {
document.getElementById("bg").style.display = 'block';
};
</script>
if you want use jquery, then
<script>
$(document).ready(function (){
$("#bg").css("display", "block");
});
</script>
That's because you need to run your Javascript inside the body tag. Actually at the end.
Conversely, the start function will be undefined and nothing happens:
<body onload="start()">
<div id="bg" style="display:none"></div>
<script>
function start() {
document.getElementById("bg").style.display = 'block';
}
</script>
</body>

How to call a function that is in a js file from another js file

I know this question has been answered many times but the solutions in those questions aren't working for me. I have a function in lets suppose, a.js. This function is outside the document.ready function and here is its format:
function thisIsFromAnotherFile(){
alert("This alert is from another js file");
}
I'm calling this function from the other file, b.js this way:
var openFile = function(context){
thisIsFromAnotherFile();
}
openFile is an onclick function.
onclick = "openFile(this)"
When I run this code I'm getting an
Uncaught ReferenceError: thisIsFromAnotherFile is not defined. Please help me out. Thanks.
It seems likely there's a few things you're not telling us.
The following code provides a minimal, functioning example.
file1.html
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
}
</script>
<script src="filea.js"></script>
<script src="fileb.js"></script>
<style>
</style>
</head>
<body>
<button onclick='fromFileA();'>Fire func in filea.js</button>
</body>
</html>
filea.js
function fromFileA()
{
fromFileB();
}
fileb.js
function fromFileB()
{
alert("now in fileb.js");
}
A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.
You declare function fn1 in File1.js, and then in File2 you can just have fn1();
File1.js
function thisIsFromAnotherFile() {
alert("working");
}
File2.js
function openFile() {
thisIsFromAnotherFile();
}
**HTML**
<html>
<head>
<script src="File1.js" type="text/javascript"></script>
<script src="File2.js" type="text/javascript"></script>
</head>
<body>
<button onclick="openFile()">Click me</button>
</body>
</html>
you need to load a.js before you call the function
<head>
<script type="text/javascript" src="path/to/a.js"></script>
</head>

Error is not caught by jquery start() function

[Update. I need to be more precise, I see...]
See the following example in javascript:
<html>
<head>
<script>
window.onerror = function() {
alert('error'); // this one works
try {i.dont.exist += 0;}
catch(e) {
// do some stacktrace stuff, this does not trigger
alert(e.stack);
}
};
</script>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js' type='text/javascript'></script>
<script>
$(document).ready(function() {
foo[1]++;
});
</script>
</head>
<body>
<p>Hello world.</p>
</body>
</html>
The 2. alert is not triggered. Why?
If I replace "foo[1]++" by "this is a bogus line" everything works and both alerts are triggered. Is there some run-time error problem?
The alert is not triggered because your error handler function was not successfully defined, due to your Javascript error :-) That block of code can't be parsed correctly so it isn't run.
Set it up this way:
<script>
$(function() {
window.onerror = function() {
// ...
};
});
</script>
If it's in its own script tag, then it'll be OK. Now, you may want to reconsider delaying the definition of your error handler to the "ready" event handling, since you may have errors before that point is reached.
[edit] OK here is a complete example, and it works fine for me:
<html>
<head>
<script>
window.onerror = function() {
alert("OH NO THERE HAS BEEN AN ERROR!");
};
</script>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js' type='text/javascript'></script>
<script>
$(function() {
here is some bogus stuff that will cause Javascript parse errors.
});
</script>
</head>
<body>
<p>Hello world.</p>
</body>
</html>

Categories

Resources