Skip to content
Advertisement

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?

main.php

<html>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>
    <!-- and other stuff-->
    <button class="continueButton" id="btn3" value="blah"> Blah</button>
    <!-- and other stuff-->
</html>

jQuery.js

$("#btn3").click(function(){
    $("#contentbox3").load("graphic2.html");
    $.getScript("animatebug.js");//a p5 animation
});

graphic2.html

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

animatebug.js

function setup(){
    createCanvas(400, 400);
    background(200,100,0);
    img = loadImage("images/bug_small.gif");
    const myCanvas = createCanvas(400, 400);
    myCanvas.parent('p5canvas');
    image(img, 0, 0);
}

function draw(){
    background(200,100,0);
    image(img, 100, 100);
}

Answer

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("https://www.gravatar.com/avatar/ddffc30b6adba9c402d2f6d8902c47fb?s=64&d=identicon&r=PG&f=1");
    myCanvas.parent('p5canvas');
    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.

Advertisement