Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Andrew Young
PLUS
Andrew Young
Courses Plus Student 639 Points

html2canvas issue

I am using the following code for my project

<html>
<head>
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="javascript">
$("#conv").click(function() {
//var testdiv = document.getElementById("testdiv");
    html2canvas($("#testdiv"), {
        onrendered: function(canvas) {
            // canvas is the final rendered <canvas> element
            var myImage = canvas.toDataURL("image/png");
            window.open(myImage);
        }
    });
});
</script>
</head>
<body>
<div id="testdiv" contenteditable>

</div>
<button id="conv">Convert</button>
</body>
</html>

But the button click can't convert to an image but when you change button click to document ready it works why?

1 Answer

Keith Kelly
Keith Kelly
21,326 Points

One comment I have is that you should be putting your scripts just before the closing body tag. This allows the entire DOM to load before the scripts are loaded and executed.

The reason it is not working in your current setup is because the script is running before the DOM loads and can't find the button because it doesn't exist yet. That is also why it is working when you use document ready.

So the two options you would have would to move the scripts to just before the closing body tag or to run the script with document ready.