Why JS Error IN IE6 (not var variables) - javascript

I coded the following JS
<html>
<body>
<img id="img" src="http://example.com/img.jpg" />
<script type="text/javascript">
//<![CDATA[
(function(){
img = document.getElementById("img");
img.src = "http://example.com/img.png";
})();
//]]>
</script>
</body>
but on IE6
some js errors are occured.
Because Should I use var img?
incidentally
<body>
<img id="img" src="http://example.com/img.jpg" />
<script type="text/javascript">
//<![CDATA[
(function(){
var img = document.getElementById("img");
img.src = "http://example.com/img.png";
})();
//]]>
</script>
</body>
</html>
is no problem
I can't get the reason why
Could you explain me?

If you omit var when you're declaring a variable, and that variable doesn't exist in current local scope, one of two things will happen:
you'll declare a new "global" variable, to which every function will have access to -> don't do this
you'll set an already existing global variable to a new value; if some other function relies on this variable, you could wreak havoc
So, don't use global variables and use var whenever possible. As Tomas already pointed out, your script could be run before the structure is loaded by the browser.

The script is running before the whole body structure is loaded by the browser. So, your function can't find the img element.
Invoking your function at the onLoad body event would fix the error.
I.e:
<html>
<head>
<script type="text/javascript">
//<![CDATA[
function loadImage(){
img = document.getElementById("img");
img.src = "http://example.com/img.png";
}
//]]>
</script>
</head>
<body onLoad="loadImage();">
<img id="img" src="http://example.com/img.jpg" />
</body>
</html>

The only problem is that you're not using var to declare the img variable. There is no problem with the fact that the rest of the body may not have been parsed, so don't worry about that.
The reason that the absence of var is causing a problem here is that img is colliding with property of the global object created for you by the browser. In IE, each element with an ID creates a property of the global object (which is therefore accessible everywhere) corresponding to that ID. This property is read-only, so if you try and assign to it, you get an error. If you declare it first, you create a new variable which doesn't interfere with IE's global property and it will work as you expect.
You would also find that changing the variable name not to collide with an ID or property of window would fix the problem:
banana = document.getElementById("img");
banana.src = "http://example.com/img.png";
... but this is not a good idea either since you're automatically polluting the global scope with your banana, which could have consequences in other code, and in ECMAScript 5 strict mode you would get an error.
Finally, unless you're using XHTML (which you almost certainly shouldn't be and your example doesn't have an XHTML doctype), there's no need for the CDATA mark-up. You should remove it.
Moral of the story: always declare your variables.

Related

Altering CreateElement method via Javascript doesn't work for iframes

I would like to globally redefine a createElement method, but unfortunately it only works in a main document, and is ignored in iframes. Let's take this example code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
old_createElement = document.createElement;
document.createElement = function(el_type) {
new_el = old_createElement.call(this, el_type);
new_el.style.color="red";
return new_el;
};
</script>
</head>
<body bgcolor="white">
<iframe id="iframe1"></iframe>
<script type="text/javascript">
window.setTimeout(function(){
iframe_el = document.getElementById("iframe1").contentDocument.createElement("div");
iframe_el.innerHTML = 'inside iframe';
document.getElementById("iframe1").contentDocument.body.appendChild(iframe_el);
},50);
no_iframe_el=document.createElement('div');
no_iframe_el.innerHTML = 'outside of iframe';
document.body.appendChild(no_iframe_el);
</script>
</body>
</html>
When i open in in a browser, the element created in a main document has red color, as expected, but the one in the iframe is black.
The problem is that I only have control on the script contained in the HEAD section of the document. In other words, i don't know how many iframes there will be later on in the HTML source, or how they will be names, or if they are added via user's Javascript.
My question is: how can i change the method globally, so all elements created in iframes also use this new style?
Thanks a lot!
Each frame has it's own separate Javascript context. If you want to change that frame's context, you have to do it specifically for that frame.
In your specific example, each frame has its own document object so it should be no surprise that each document has its own .createElement property.
You cannot generically change things in a way that will affect all frames. And, in fact if it's a cross-origin frame, you can't change it at all.

html code that executes wsh code through javascript

I'm stuck on this code...I'm trying to get the html page to, when you click the link, call the bms function, which should open internet explorer, go to google, and fill the search textbox with the word "test". This isn't exactly the website or word I want to use, but I needed to change it since the actual website/words are sensitive information. I want to use this through IE since our processes go through this browswer, specific with also using the -nomerge function. My code is below. Thanks for the help!
<html>
<head>
<script>
var WshShell = new ActiveXObject("WScript.Shell");
function BMS()
{
WshShell.Run("iexplore.exe -nomerge http://google.com");
WScript.Sleep (5000);
WshShell.SendKeys ("test");
WScript.Quit();
}
</script>
</head>
BMS
<br /><br />
DAY
</html>​
Dont be thrown off by jade; it's just quicker. Just note I'm placing scripts just before the closing body tag.
html
head
title foo
body // body tag added
p notice that i've not declared script yet. Preference/good practice.
a#bsdTrigger(href='#') foo
a#ssddTrigger(href='#') bar
//- scripte here
The Important-ish part: here's a pen
(function() {
// now the variable will not pollute your global ns
var WshShell = {}; //ignore the OR only because there is no Active thing
WshShell.log = function() { // fake behavior for testing
console.log(arguments);
}
var bsd = function BSD() {
WshShell.log("foo");
window.alert('foo!');
return false;
}
document.getElementById("bsdTrigger").addEventListener('click', bsd);
})();
I hope this helps... It's very generic and contrived, but you'd employ the exact same methods in doing what you're trying to do.

Assign value to Javascript variable

I am trying to assign value to javascript variable without refreshing page but its not working.
Consider example:
<head>
<script type="text/javascript">
var id='';
var source='';
function assignvalue(_id,_source){
//open div load in dialog box
id = _id;
source = _source;
}
</script>
</head>
<body>
<div id='load'></div>
<script>
_login.push(['login', 'callback_uri', 'http://localhost/Login/index/?source='+source+'&id='+id']);
</script>
</body>
In head define some variable globally and onclick of a tag I am opening div with load id and having global varible with new value.But new value is not assign to it below divs javascript.Any suggestion.
Thanks.
you are declaring two global variables id and source, but in your function definition you declare two local variables with the same name, so your desired changes to global variables are applied to local ones. Just rename the variables in the function definition.
For instance:
var id, source;
function assignvalue (_id, _source) {
id = _id;
source = _source;
}
Because the way you pass value cannot be
function assignvalue(id,source)
cause id and source in the function here will become local variable instead.
Please replace the variable in parsing to other name so that it work, i.e
function assignvalue(passID,passSource){
id = passID;
source = passSource;
console.log(id+" "+source);
}
then the global variable value will change.
You are declaring id and source twice: once in the global scope, and once as function parameters.
To overwrite the values of the global variables inside the function, you need to use a different name for the parameters.
Try
function assignvalue(_id, _source) {
id = _id;
source = _source;
}
To execute the _login function when the link is clicked, you could simply call it in assignValue:
function assignvalue(id, source) {
_login.push(['login', 'callback_uri', 'http://localhost/Login/index/?source='+source+'&id='+id']);
}
In that case, it wouldn't be a bad idea to rename the function assignvalue to login
Yes, whatever you have written is correct.
But when you click on an HyperLink it will automatically refreshes the page.
Here you want to disable that auto refresh when you click on the Hyper link.For that you could amend your code like this:
<html>
<head>
<script>
var id,source;
function assignValue(_id,_source){
id = _id;
source = _source;
alert(_id+" and also "+_source);
}
</script>
</head>
<body>
<script>
alert(id+" I am in Body "+source);
</script>
Hello
</body>
OR alternatively you can try this
<html>
<head>
<script>
var id,source;
function assignValue(_id,_source){
id = _id;
source = _source;
alert(_id+" and also "+_source);
return false;
}
</script>
</head>
<body>
<script>
alert(id+" I am in Body "+source);
</script>
Hello
</body>
Extra Info:
To override the default browser functionality, just you have to return false.
Not only here, almost you can apply this in many situations.
One such situation is disabling right click(simply) is just
oncontextmenu= return false;
and another such situation is disabling a KeyPress Event and so on.
So, you can apply this almost anywhere.

Why doesn't my code work despite the placement of my external JavaScript file?

This is the basis of how my document is written out. I have an external JavaScript file positioned at the top of the head element. Below it, I have code the references content from it. I would expect since the code is below the file it would work but it doesn't. It only works if I wrap the code in a window.onload() function. Or if I put the code in a script in the body element.
<html>
<head>
<script type="text/javascript" src="myJavaScript.js"></script>
<script type="text/javascript">
console.log(w); // w is a variable inside myJavaScript.js but throws an error stating "w is not defined".
</script>
</head>
<body></body>
</html>
Why does this code behave this way? I have the file written on top of the code that calls content within it yet it still doesn't work.
EDIT: I found the error and it was that I wasn't defining the code in myJavaScript.js in the global scope. That's why the variable w never got through.
You'd have to show us the relevant code in myJavaScript.js for us to know what's really going on, but it's fairly clear that either w isn't defined at the global scope in myJavasScript.js or myJavaScript.js isn't being loaded successfully.
Most likely w is not actually a globally scoped variable like you think it is.
I can't reproduce your problems. You haven't probably define your "w" variable or you defined it away from global scope
http://sandbox.phpcode.eu/g/686fb
try to add at the top of head:
var w = "";
Dollars to doughnuts, the w is being set in an onload.

document.getElementById in IE

When I use document.getElementById in Internet Explorer I get this error:
Mensaje: El objeto no acepta esta propiedad o método
Translation:
Object does not support this property or method
and the execution stops
Html:
<div id="contenedor">
...
</div>
JavaScript:
contenedor = document.getElementById("contenedor");
This works ok in Firefox and Chrome.
There is a misfeature in some(?) versions of IE where it defines global constants for every id value in the document. So when you write contenedor = document.getElementById("contenedor") — notice that it uses the div's name for the variable — it sees you're trying to set that global variable and complains that you can't. What you should do is declare a new variable instead of setting a global: var contenedor = document.getElementById("contenedor")
If it's simply document.getElementById('someid') that gives you this message, may be placing your script at the bottom of the HMTL (right before the closing </body> tag) will help.
if you want to be shure the element is loaded before you assign it to a variable, use
window.onload = function(){
contenedor = document.getElementById("contenedor");
};
It looks like your javascript is executing before DOM is ready. Many javascript libraries include a mechanism for adding an event when DOM is ready, otherwise, one can use the body onload event.
You can try to put your javascript at the bottom of your document, but this is no guarantee that the code won't be executed before the page has loaded sufficiently to allow the browser to build the DOM tree. You're much better off either using a framework with the ready or domready event (like mootools or jquery), OR using the body onload event as mentioned.
Example:
<html>
<head>
<script type="text/javascript">
var initPage = function() {
// do stuff
}
</script>
</head>
<body onload="initPage();">
<!-- page content -->
</body>
</html>

Categories

Resources