Showing HTML within an iFrame

ambuli
ambuli used Ask the Experts™
on
Hi there,
I want to print a pie chart inside an iFrame.  I have the following code.  When executed,  I am getting an exception saying
"Cannot read property 'getContext' of null"

I am using Charts.js library for creating the pie chart.
Can you please help me with this one.  Thank you.


// in a function I have the following code segment
if(response.success)
{
    generateReport();
}
And I just want to display the pie chart in the iFrame.

function __pieChartExample() {
        var div = document.createElement("div");
        var canvasDiv = document.createElement("canvas");
        canvasDiv.id = "chartArea";
        div.appendChild(canvasDiv);
        var ctx = document.getElementById("chartArea").getContext("2d");

        var data = [{
            value : 300,
            color : "#F7464A",
            highlight : "#FF5A5E",
            label : "Red"
        }, {
            value : 50,
            color : "#46BFBD",
            highlight : "#5AD3D1",
            label : "Green"
        }, {
            value : 100,
            color : "#FDB45C",
            highlight : "#FFC870",
            label : "Yellow"
        }];

        var pieOptions = {
            segmentShowStroke : false,
            animateScale : true
        };
        new Chart(ctx).Doughnut(data, pieOptions);
        div.appendChild(canvasDiv);
        return div;

    }
 function __generateReport() {
        var iFrame = document.createElement("iframe");
        iFrame.id = "iFrameID";
        iFrame.style.display = "none";
        document.body.appendChild(iFrame);
        iFrame.contentWindow.document.write(pieChartExample().innerHTML);
        var result = iFrame.contentWindow.document.execCommand("save", false, null);
        if (result === false) {
            iFrame.contentWindow.focus();
            iFrame.contentWindow.print();
        }
    }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
you have the error in:

var ctx = document.getElementById("chartArea").getContext("2d");

Open in new window


document.getElementById("chartArea") is null so you need to be sure that you have that element in your document and execute your code after the element is loaded with:

window.onload = function(){
__pieChartExample()
}

Open in new window

Author

Commented:
Thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial