JavaScript AddedToStage equivalent - javascript

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

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.

Links not working in chrome-extension after I've moved them to a different position

My google-chrome-extension moves certain div to a different place after page loaded:
var div = $('div.joinContributors').first();
if (div != null) {
div.insertAfter($('div.filmRateBox').first());
}
and links that are stored inside that div aren't working anymore. When I inspect html code using Chrome developer tools I can see:
<li><a class="link" href="link_to_another_subpage" rel="nofollow">name_of_the_link</a></li>
But when I create new link and add it there everything works just fine:
$("<a>", {"href": "link_to_another_subpage", "text": "name_of_the_link"}).insertAfter($('div.filmRateBox').first());
Any ideas why aren't they working?
Since the contents has normal links with proper URLs that must be handled correctly by default, the most likely reason is that the site uses custom click event handlers with parent node checks inside.
A simple solution is to insert as HTML to recreate the exact layout but strip all event handlers:
var $div = $('div.joinContributors').first();
if ($div.length) {
$('div.filmRateBox').first().after($div.prop('outerHTML'));
$div.remove();
}
Note that document.querySelector is much faster than $('...').first() because it doesn't build the entire collection.
Another solution, quite shaky, would be to remove the event handlers, but it'll work only for jQuery events accessible via jQuery._data(element, 'events') or .onxxxxx DOM properties.

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

Is there any way to get "global" events when working with nested iframes?

My problem is I need to capture a keypress but at any given time the user can be inside of an iframe inside of an iframe inside of an iframe.
At first, I thought I could just put the listener on document but that doesn't work if the user is inside of one of those iframes.
Next I thought of attaching the handler to window but ie doesn't support attaching event handlers to window. I'm not even sure if that would work though or it would be the same problem as with document.
Next, I thought I could just go through all the iframes and add individual handlers there but eventually realized that wouldn't work because the iframe doesn't have any html in the dom so there is no way to access iframes nested in it.
One other possible solution is to go to the js of all the iframes and add this code manually but that is way too extreme.
Any other ideas?
I keep answering my own questions but oh well. If you come across this problem I figured out the answer. This uses jquery but you could port it to straight js if you had to.
var myFunction = function () {
alert("hello world");
};
var $myWindow = $(myWindow /*dom object*/);
$myWindow.bind("mouseover", myFunction);
var getNested_iframes = function (document_element) {
$.each(document_element.find("iframe"), function () {
var iframeDocument = $(this).get(0).contentWindow.document; // may need to change this depending on browser
iframeDocument.onkeyup = myFunction;
getNested_iframes($(iframeDocument));
});
}
getNested_iframes($myWindow);

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

Categories

Resources