JavaScript onload and DOM - javascript

I have this example document:
<html>
<body>
<script type="text/javascript">
document.body.onload = myFunc();
function myFunc() {
element = document.getElementById('myDiv');
element.innerHTML = 'Hello!';
}
</script>
<div id="myDiv"></div>
</body>
</html>
Why 'element' is null if myFunc is a callback of document.body.onload?
If, instead, the script is inserted after the div, it works:
<html>
<body>
<div id="myDiv"></div>
<script type="text/javascript">
document.body.onload = myFunc();
function myFunc() {
element = document.getElementById('myDiv');
element.innerHTML = 'Hello!';
}
</script>
</body>
</html>
My question is: if I use the onload event within the handler function, should I have the entire DOM, or not? Why should I not?

The problem is that you are calling the function immediately (and assign its return value).
Assign the function instead and it will work:
document.body.onload = myFunc;
You should also use var element in your function to avoid creating a global variable.
Or if you want to confuse people:
document.body.onload = myFunc();
function myFunc() {
return function() {
var element = document.getElementById('myDiv');
element.innerHTML = 'Hello!';
};
}
But let's not do that. It makes no sense here. ;)

Use this instead
document.body.onload = myFunc;
Or
document.body.onload = function() {
myFunc();
};

Related

Why my function is running before window resizes?

I want the header to change it's colour when the window is re-sized. But the changeColor() runs immediately after I load the site. Can anyone explain, why my changeColor() function is running before window re-sizes?
<body>
<h1>JavaScript</h1>
<script>
var heading = document.querySelector("h1");
function changeColor(colour) {
heading.style.color = colour;
}
window.onresize = changeColor("red");
</script>
</body>
You are executing "changeColor" function in your way.
Try this:
<body>
<h1>JavaScript</h1>
<script>
var heading = document.querySelector("h1");
function changeColor(colour) {
heading.style.color = colour;
}
window.onresize = function() {
changeColor("red")
};
</script>
</body>
You are invoking the function.
use this:
window.onresize = changeColor.bind(this,"red");
Right now, the execution of your program is:
changeColor(red) --> assign its return value to window.onresize
You're assigning the result of a call to changeColor to window.onresize, not the function changeColor itself. Your code is equivalent to:
var temp = changeColor("red"); // undefined, because changeColor doesn't return anything
window.onresize = temp;
What you can do is create a function that returns a function which uses the desired color:
function createColorChangeCallback(color) {
return function() {
heading.style.color = color; // color variable captured from enclosing function
};
}
window.onresize = createColorChangeFunction("red");
Or you can use .bind or a lambda:
window.onresize = function() {
changeColor("red");
};
Which are both equivalent to:
window.onresize = function() {
heading.style.color = "red";
};
you should try something like this and that should do the trick
<body onresize="changeColor('red');">
$(document).ready(function(){
$(window).resize(function(){
heading.style.color = "red";
});
});
Try this....

Uncaught TypeError: undefined is not a function

Button.js:
(function () {
function Button(label) {
console.log(label);
}
}());
demo.html:
<html>
<head>
<script src="../../lib/easeljs-0.7.1.min.js"></script>
<script src="Button.js"></script>
<script>
window.onload = function() {
var canvas, stage, button;
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
button = new createjs.Button("Anything");
stage.addChild(button);
stage.update();
}
</script>
</head>
<body>
<canvas id="canvas" width=200 height=200>Canvas is not supported</canvas>
</body>
</html>
for the line
button = new createjs.Button("Anything");
Error: Uncaught TypeError: undefined is not a function
Why i am getting this error?
It is because the Button is not in a global scope or window.
You don't need IEFE here. Remove it:
function Button(label) {
console.log(label);
}
If you want it with IEFE, then do this:
$(function () {
window.Button = function (label) {
console.log(label);
}
});
If you want to access Button by using createjs.Button, then you must create Button on the createjs object:
createjs.Button = function(label){
console.log(label);
};
The above will work in any scope, including the global and your function expression, because createjs is in the global scope. Now you can do:
button = new createjs.Button("Anything");

HTA Javascript - why is object out of scope in onbeforeunload?

This is a bit of a strange one. I have been trying to call a function in a child object from the parent object but it seems to be going out of scope in onbeforeunload function. These function calls work outside of a onbeforeunload, so it only fails when called in onbeforeunload. I can fix it by making the child object a global but I was trying to avoid that. Anyone know why my childobject is out of scope when called in onbeforeunload? Notice I call that same function in windows onload event and it works fine. Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Broken HTA</title>
<HTA:APPLICATION
ID="Broken HTA"
APPLICATIONNAME="Broken HTA"
BORDERSTYLE = "flat"
CAPTION="Yes"
CONTEXTMENU = "no"
INNERBORDER = "no"
MAXIMIZEBUTTON = "no"
MINIMIZEBUTTON = "yes"
NAVIGABLE = "No"
SCROLL = "auto"
SCROLL FLAT = "Yes"
SELECTION="no"
SYSMENU="yes"
SHOWINTASKBAR="yes"
SINGLEINSTANCE="yes"
VERSION = "1.0"
BORDER="thick"
>
<script language="javascript" type="text/javascript">
var myparent;
function windowLaunch()
{
myparent = new parent();
myparent.getchildvalue();
window.onbeforeunload = myparent.getchildvalue;
window.resizeTo(500, 610);
}
function parent()
{
this.mychild = new childobject("myinput");
this.getchildvalue = function()
{
var tmpval = this.mychild.returnvalue();
};
}
function childobject(thename)
{
this.myprop = thename;
this.returnvalue = function()
{
return (document.getElementById(this.myprop).value);
};
}
</script>
</head>
<body id="thebody" onload="windowLaunch();">
<div id="outerdiv">
<span title="This Input Box">My Input:</span><br />
<input id="myinput" style="width: 290px"/>
</div>
</body>
</html>
this is based on how a function is called. Calling myparent.getchildvalue() is fine, but as soon as you assign myparent.getchildvalue as a handler, it will be called out of context. You can demonstrate this simply:
var obj = { val: 42, fn: function(){ alert(this.val) } };
ref = obj.fn;
alert(obj.fn === ref); // true, so expect the following to do the same thing...
obj.fn(); // 42, so far so good
ref(); // undefined. uh oh...
You can get around this by wrapping:
...
window.onbeforeunload = function(){ myparent.getchildvalue(); };
...
or binding:
...
window.onbeforeunload = myparent.getchildvalue.bind(myparent);
...

Replace text with on page load

I know how to replace text with getElementById() function in such situation:
<script type="text/javascript">
function go(){
var p = document.getElementById('ccc');
p.firstChild.nodeValue = 'AAA';
}
</script>
<div id='ccc'>o</div>
go
When I click on go link 'o' replaces on 'AAA'.
But I want to replace text when page loading to browser without any clicking. So user do not have to know that there was some text 'o' in div 'ccc'. He must see only 'AAA' from the beginning.
How to do that?
You can use the onload event:
window.onload = go;
// or better
window.addEventListener("load", go);
You can also use an anonymous function:
window.onload = function()
{
// ...
}
window.addEventListener("load", function()
{
// ...
});
use onload attribute like this:
<body onload="go()">
handle window.onload event, it fires up when the page loads.
<script type="text/javascript">
function doLoad() {
go1();
go2();
// ...
}
if ( window.addEventListener ) {
window.addEventListener( "load", doLoad, false );
}
else
if ( window.attachEvent ) {
window.attachEvent( "onload", doLoad );
} else
if ( window.onLoad ) {
window.onload = doLoad;
}
</script>
Alternatively you can just put your script at the bottom of the page, all elements will be loaded then.
<div id='ccc'>o</div>
<script type="text/javascript">
var p = document.getElementById('ccc');
p.firstChild.nodeValue = 'AAA';
</script>

Javascript doing something strange? works in IE but not firefox?

I'm trying to create an element onclick and hide the element when it is clicked but it does nothing?
Why does the hide() function do nothing?
<script type="text/javascript">
function show(){
var a = document.getElementById('foo');
var b = document.createElement("div");
b.setAttribute('id', 'bar');
b.setAttribute('onclick', 'hide()');
a.appendChild(b);
b.innerHTML = 'TEXT CONTENT';
b.onclick = function() {
hide();
};
}
function hide() {
var x = document.getElementById('foo');
var z = document.getElementById('bar');
x.removeChild(z);
}
</script>
<div id="foo" onclick="show()">CLICK ME</div>
Add
b.onclick = function() {hide();};
If this is occurring under IE, then see Stackoverflow - Why does an onclick property set with setAttribute fail to work in IE?
you can use jquery method to register function it will work in both IE,FF
A sample for u
$(b).click(function() {
//call your function like hide() i have made a separate function for cleaner code and re usability
});
function hide()
{
}

Categories

Resources