HTML element no defined in Javascript - javascript

I have an html element:
<img alt="" src="../Images/ERROR.jpg" id="live1x4" height="288" style="width: 360px;
display: block;" /
If i refer to this control in javascript which is in the same html page:
live1x4.src = src;
Where src is the location of an image the script works.
If move that javascript to an external js file I get 'live1x4' is undefined.
This occurs ONLY in Internet Explorer.
Wjat can be causing this error?

You have to target your element, not simply refer to the ID:
document.getElementById("live1x4").src = ....

The reason is that the JavaScript code is executed before the img element has been parsed. Whether this happens depends on many things. There are different ways to ensure that it does not happen. A simple way is to wrap your code inside an even handler that is triggered after the document has been loaded:
window.onload = function() {
// your code here, here all elements are available, e.g.:
live1x4.src = src;
}
It is generally regarded as bad coding style to use id attribute values as if they were global variables (partly because they stop working ifsynonymous global variables are added), so document.getElementById("live1x4") is preferable to live1x4. However, this is a different topic.

Related

addEventListener on a body element does not get executed

I am using MS Edge in IE11 compatibility mode and have an HTML page in which I have:
<input id="onLoadAttributeHiddenId" type="hidden" value="schadenAuswahl.setCustomCheck();schadenAuswahl.createArrays();">
Further below, I have also:
<script language="JavaScript1.1" src="../js/table_head_uip.js"></script>
And in the table_head_uip.js, I have:
document.body.addEventListener('load', customOnLoadFunction, false);
function customOnLoadFunction(){
var onLoadAttributeFunctStr = document.getElementById("onLoadAttributeHiddenId").value;
var onLoadAttributeFunct = new Function(onLoadAttributeFunctStr);
onLoadAttributeFunct;
}
Now, when I put breakpoints in the table_head_uip.js, the line.
var onLoadFunct = document.body.addEventListener('load', customOnLoadFunction, false);
It gets executed, but the function customOnLoadFunction never gets completed. Also, I do not receive any errors in the console.
Any help will be appreciated.
load events only fire on elements which load things (like an <img> with a src attribute) and the window object (for when the entire document, including its dependencies, has loaded).
The body element doesn't load anything.
The equivalent of the obsolete onload attribute for the body is a load event that fires on the window object. That attribute only existed because, since window isn't an element, you couldn't put attributes on it.
Additionally, the statement onLoadAttributeFunct doesn't do anything. To be useful you need to, for example, put () after it to call it.
new Function(onLoadAttributeFunctStr) is effectively a time delayed eval and is considered dangerous, slow, and hard to debug. You should reconsider the design of your application if you need that.

Javascript not finding Button with ID

In my HTML, I have a simple button defined, like so:
<button id="toggleButton">Stop</button>
I am trying to grab it with the following code:
buttonElement = document.getElementById("toggleButton");
with the goal of assigning an event to it, like so:
buttonElement.onclick = stopTextColor();
The problem is that the getElementById is returning null, even though I can see it in the DOM. What am I doing wrong here?
For clarity, I posted the full code at http://cdpn.io/sqEuH
The problem, probably, is that you're including the JS in the head. What's happening there is the JS is running before the page gets loaded, so the button doesn't show up. Move it to right before the </body> tag, and this problem will be solved, or wrap it with a window.onload() event.
The code you post will work unless the javascript cannot access the given DOM element.
The main possibilities:
The javascript runs before the DOM is parsed (IE if you run it in the head of the document without any code to instruct it to wait till the DOM is ready)
You can usually get around this by placing your script at the bottom of the body rather than in the head or midway through the body. The essential thing to understand here though is that JS can't access an element till the browser has parsed the DOM. The browser parses HTML top-down, and JS scripts run top down, so if you run the JS before the element is parsed, it won't be available to the javascript function yet.
The javascript runs in a context where it can't access the element (inside an iFrame for instance). In this case it would be a question of whether the element is really under the "document" object that you're referring to. If the element is inside an iFrame it will be underneath the iFrame's document object.
Try putting your script just before closing your <body> tag. The DOM is probably not fully loaded when your script is run.
Also, I think you have an error in your Javascript. It should be
buttonElement.onclick = stopTextColor;
instead of
buttonElement.onclick = stopTextColor();
Altough it shouldn't throw any error, it's good practice.
If you want to keep your Javascript before <body>, you can use a listener to wait for the DOM to be loaded and then execute your script, like this :
window.addEventListener("DOMContentLoaded", function() {
buttonElement = document.getElementById("toggleButton");
buttonElement.onclick = stopTextColor;
}, false);
[edit]
The snippet above doesn't work in IE < 9. If you need to support it, use document.load instead, it should give the same result, like so :
document.onload = function() {
buttonElement = document.getElementById("toggleButton");
buttonElement.onclick = stopTextColor;
}
The differece between both, besides browser compatibility, is that window.addEventListener("DOMContentLoaded", function() {...} will fire when the DOM is loaded, but window.load will fire when the DOM AND all other resources (images, stylesheets, etc.) are loaded (slower, and not necessary in your case).

JavaScript AddedToStage equivalent

What is the closest thing to ActionScripts ADDED_TO_STAGE event.
I need to know when a dynamically generated div has been added to another div
var myDiv = document.createElement("div");
$(someContainer).append(myDiv);
If you're using a function such as appendChild to add static text to the DOM, that's a synchronous event. It will be added and rendered by the time your function returns.
If you're appending a child that depends on an external resource, you're looking for the onload event. This works for the main document (window.onload = function() { ... }), and according to What html tags support the onload/onerror javascript event attributes?, body, frame, frameset, iframe, img, link and script. (They apparently get their information from http://www.w3schools.com/jsref/event_onload.asp, which is not nearly as good as straight from the spec, but I couldn't find the details in there.)

Javascript onload in HTML

I want to ask a question about the Javascript’s onload.
I’m writing a JSP page with the code <%# include file ="body.jsp". The included body.jsp contains:
<table onload="function()">
This should load the javascript function, but it doesn't appear to have any effect on the page. Is onload only usable on the body tag?
Onload can only be used for <body>, <img>, <script>, <iframe> tags, because it tells you when an external resource (image, script, frame) or the whole page (body) has been loaded
Since HTML5 these can also fire a load event: <link>, <style>, <input type=image>, <object>
Support for these can still be a hit or miss though (e.g. older Android browsers)
Why not just include it via a <script tag>?
Inside your .jsp file
<script>
window.onload = function() {
alert("Hello!");
}
// or to execute some function
window.onload = myFunction; //notice no parenthesis
</script>
As the other guys already stated the onLoad event will not fire on a table. What you can do ist attaching the onLoad-handler to the body element (which will then fire, when the page is loaded) and manipulate the table by for example assigning an id to the table.
<body onload="function() { var table = document.getElementById("table-id"); ... }">
<table id="table-id"></table>
</body>
Are you using some javascript framework?
"onLoad" may be used on body- and frameset-tags.
To see some action you may use:
<body onload="function(){alert('This is an action!')}">
The easiest way i find is to use an external javascript file and jquery.
// Variables and functions you want to declare
var socket = io.connect();
// .....
// Function you want to run on load
$(function() {
$('#submit').click(function() {addUser();});
// ... any other functions you want to run on load
});
This is a code snippet from something that i was working on. The variable is declared before the code runs (It creates a web socket).
Then there is the jquery document selector ($) which runs on load and calls the init function to modify my html. I use it to call an anonymous function which runs right away.
You can throw a <script> tag right after your table with code. Once it gets to the script tag it would mean that the DOM for the table element above it has been loaded and can now be accessed in your script below it.
Note: The following below isn't applicable to the question but rather the other answers being given.
I recommend using the addEventListener function in javascript for adding the event. This makes sure that you are not overwriting or going to be overwritten by anyone else wanting to listen to the event.
Example
var iframe = document.getElementsByTagName('iframe')[0];
iframe.addEventListener('load', function(event){ console.log("iframe Loaded", event); })

parent.iframePDF is undefined

I get 'parent.iframePDF is undefined' JavaScript error when i use the below code in Firefox and an 'object expected' error in IE.
Can someone tell me what it is that i'm doing wrong? Thanks
function PrintFrame(xFile){
parent.iframePDF.location.href = xFile;
document.getElementById("spanMess").style.display = "block";
parent.iframePDF.onload = new function() {
setTimeout("parent.iframePDF.print();parent.document.getElementById('spanMess').style.display='none';",10000);
}
}
<iframe id="iframePDF" src="about:blank" style="display:none"></iframe>
<input type="image" onclick="PrintFrame('525.pdf')" src="../../cms_res/DisneyChannel/playhouse/images/buttons/printer.png" />
<span id="spanMess" style="display:none;color:red;">
<h3>Preparing Document For Print</h3>
</span>
You should use name="iframePDF" instead of id="iframePDF".
In that way, you can use window.iframePDF (-> window.frames.iframePDF).
If you use document.getElementById('iframePDF'), then you can't use .location.href on that.
Edit: Tim is right, no parent is needed here.
Your code may not work for succeeding calls of PrintFrame on other browsers, the problem is that the onload event on iframe may not fire anymore.
You may try this:
function frameLoaded(frame){
frame.contentWindow.print();
document.getElementById('spanMess').style.display='none';",10000);
}
function PrintFrame(xFile){
var holder = document.getElementById('iframePDFHolder');
holder.innerHTML = '<iframe onload="frameLoaded(this)" src=" + xFile + '"></iframe>';
}
<div id="iframePDFHolder" style="display:none;"></div>
<input type="image" onclick="PrintFrame('525.pdf')" src="../../cms_res/DisneyChannel/playhouse/images/buttons/printer.png" />
<span id="spanMess" style="display:none;color:red;"><h3>Preparing Document For Print</h3></span>
First problem is that parent refers to the window object of the document containing the current document and you actually want to call a function in the current document, so the parent is not required.
Second, you should use document.getElementById("iframePDF") rather than relying on IE's nasty featrue of creating properties of the global object corresponding to IDs of elements in the page. To get the iframe's window object you can use the (non-standard but widely supported) contentWindow property. Alternatively, assign a name to your iframe instead of an id and use window.frames["iframePDF"].
Third, new function() {...} is not what you want: the new there is not necessary and confusing; drop that.
Fourth, assigning an onload property to an iframe object will not work in all browsers. You need to handle the load event within the document loaded into the iframe and call a function in the main document, using parent to get hold of the containing document.

Categories

Resources