Skip to content

jQuery getScript() and a div element id

I am using jQuery to add a div to a page that I’d want to then use as a location for content produced by another script (in this case ,p5). It will work fine if I assign include a static div with the id=’p5canvas’ but when I use jQuery to add dynamic content (see below), nothing happens and I don’t understand why. Can anyone explain what I am getting wrong/what’s missing?


    <script src=""></script>
    <!-- and other stuff-->
    <button class="continueButton" id="btn3" value="blah"> Blah</button>
    <!-- and other stuff-->


    $.getScript("animatebug.js");//a p5 animation


<div id="p5canvas"></div>


function setup(){
    createCanvas(400, 400);
    img = loadImage("images/bug_small.gif");
    const myCanvas = createCanvas(400, 400);
    image(img, 0, 0);

function draw(){
    image(img, 100, 100);


The order of execution is really important here, and that’s where things are going wrong. The p5 script in your header is looking for a setup() function to call at a time when you haven’t yet loaded your <div id="p5canvas"/> target element or your animatebug.js file containing the function.

You need to make sure that both of those two events happen — html loaded and script loaded — and then you can execute the script correctly.

You can control when the p5 functions are called by using p5 instance mode.

const animateBug = function(p) {
  let img;

  p.setup = function() {
    const myCanvas = p.createCanvas(400, 400);
    p.background(200, 100, 0);
    img = p.loadImage("");
    p.image(img, 0, 0);

  p.draw = function() {
    p.background(200, 100, 0);
    p.image(img, 100, 100);

Then you execute this by calling

new p5(animateBug);

You’ll most likely want to call new p5(animateBug); in your jQuery so that you can make sure that load() and getScript() have both finished first. But I’m not a jQuery pro so I can’t help you with that part.