Question

Just struggling with a Javascript class being used as a method for some cometishian code, how do I have a constructor for this code? The following code is invalid:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">    
<html>    
    <head>    
        <link rel="Stylesheet" href="gStyle.css" />            
        <script type="text/javascript" language="javascript">    
            // Gantt chart object
            function ganttChart(gContainerID) {    
                this.isDebugMode = true;
                this.gContainer = document.getElementById(gContainerID);    
                if (this.isDebugMode) {
                    this.gContainer.innerHTML += "<div id=\"gDebug\">5,5 | 5.1</div>";
                }    
            }                
            var myChart = new ganttChart("chart1");                  
        </script>            
    </head>    
</html>    
<body>    
    <div id="chart1" class="gContainer"></div>    
</body>    
</html>

this.gContainer is null

Was it helpful?

Solution

That is because you are running the script before the page is ready, i.e. chart1 doesn't exist yet when you call new ganttChart("chart1");. Wrap the code inside window.onload = function() { } or run it at the bottom of the page.

OTHER TIPS

The problem is that your script is running too early, it's looking for an element that doesn't exist in the DOM yet, either run your script onload, or place it at the end of the <body> so your id="chart1" element is there to be found when it runs.

Problem is that you run your code before the page has loaded yet, and thus the DOM element with id chart1 does not exist at the moment the code is executed.

use

window.onload = function(){myChart = new ganttChart("chart1");};

Note that using window.onload like that will override all previously stated window.onload declarations. Something along the following lines would be better:

<script type="text/javascript">
var prevOnload = window.onload || function () {};
window.onload = function () {
prevOnload();
// do your stuff here
};
</script>

Also, untill al images are fully loaded onload will not trigger, consider using jquery & $(document).ready or similar.

:)

Regards, Pedro

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top