Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html div on load event for a dynamically added div element

How i can make some thing like this?

<div id='myDiv' onload='fnName()'></div>

can't use

window.onload = function () {
    fnName();
};

or

$(document).ready(function () {fnName();});

the div element is dynamic. The div content is generated by xml xsl.

Any ideas?

like image 251
Harold Sota Avatar asked Feb 17 '11 08:02

Harold Sota


2 Answers

I had the same Issue, and after searching I found this.

In my case, the javascript appends the head of the index html to load a tab content html file, and onload I want to add that tab to the dom, display it and make other js stuff to change the tabs style.

I added the line with .onload = function(event) {...}

var link = document.createElement('link');
link.rel = 'import';
link.href = 'doc.html'
link.onload = function(event) {...};
link.onerror = function(event) {...};
document.head.appendChild(link);

This worked like a charm, and maybe it helps some other researcher :)

I found it on HTML5 Imports: Embedding an HTML File Inside Another HTML File

like image 139
murthag11 Avatar answered Oct 15 '22 17:10

murthag11


The onload attribute probably wouldn't fire on the <div> if you're injecting it dynamically (as the document is likely already loaded, but maybe it'd still work...?). However you could either poll for the element by simply doing something like this (similar to YUI's onContentAvailable):

// when the document has loaded, start polling
window.onload = function () {
    (function () {
        var a = document.getElementById('myDiv');
        if (a) {
            // do something with a, you found the div
        }
        else {
            setTimeout(arguments.callee, 50); // call myself again in 50 msecs
        }
    }());
};

Or you could change the markup (I know nothing about XSL) to be something like this:

Earlier on in the page:

<script type="text/javascript">
    function myDivInserted() {
        // you're probably safe to use document.getElementById('myDiv') now
    }
</script>

The markup you generate with XSL:

<div id="myDiv"></div>
<script type="text/javascript">
    myDivInserted();
</script>

It's a bit hacky but it should work.

like image 27
Dan Beam Avatar answered Oct 15 '22 17:10

Dan Beam