Reference is Null, p5 load order?

Hello,

at the moment i am trying to reference a div object from my index.html witin the p5 sketch but i keep getting an object is null error.Capture

I think this happens because the script is loaded too early and the object has not been set up in html yet.

What is the best way to fix this?

If i simply move the p5 scripts to the bottom of the page, it does not appear to read them and tells me the function does not exist.

image

the Code:

p5

var projectContainer = document.getElementById('projectContainer');

function setup() {
projectContainer.hide();
}

HTML

  <div  id="projectContainer"></div>

thanks in advance,
Skranker

1 Like

hide() is a method from class p5.Element: p5js.org/reference/#/p5.Element/hide

However your variable projectContainer refers instead to an HTMLDivElement object:

In order to get a p5.Element wrapper object, use select() inside setup(): p5js.org/reference/#/p5/select

projectContainer = select('#projectContainer');

1 Like

This could be relevant: [SOLVED] Accessing html elements defined into .html file?

Make sure you are including p5.dom.js as it is not clear in the code you provided.

Kf

Thanks, that fixed it. I just kind of assumed that p5 and html elements are the same thing.

Ended up using div.style.display since the p5 method show() seems to reset the style to the default inline, and i wanted to use a different one.

Problem solved.