marco
marco

Reputation: 826

referencing dynamically loaded things from a previously loaded jquery script

let's say that i have something like this:

<head><script src="script1.js" ...></script></head>
<body><div id="div1"></div></body>

which i call index.html, and div1's content is loaded dynamically, like

$("#div1").html ("div1.html");

where div1.html is something like

<div id="div2"><canvas id="canv1" ... /></div>

and i want to reference canv1 somehow in script1.js; by just operating on $("#canv1") nothing happens because script1.js is loaded before div1.html; is there a way (e.g. $(document).on(...)) to "do something as soon as [..] is loaded"? i tried

$(document).on ("load", "#canv1", ...);

but it doesn't work. it's worth noticing that $(document).on ("click", "#canv1", ...) works, but it's not what i want (as in, i want to draw something in the canvas before caring of what happens on click...); any ideas?

Upvotes: 1

Views: 122

Answers (1)

jimw
jimw

Reputation: 2598

Presumably you're loading your content with a AJAX call, then doing your append in the callback. If you put the $('#canv1')... after the append, within the callback, it should work.

Edit based on the OP's comment below:

$.ajax (
    {url: "div1.html",
     cache: false}).
done (function (html){
    $("#div1").append (html);
    $("#canv1").click(...);
 });

Upvotes: 1

Related Questions