Canvas.parent() with Multiple HTML files

Hello all!

I’m sure this is a simple question but I’m having some trouble finding the answer. I have a website I am designing that has multiple HTML pages. The main page is a standard “index.html” file and the subsequent pages are filed in a folder titled “HTML”. In one of these secondary pages, I want to run my P5.js canvas.

When I was running the sketch on the “index.html” page I was using the .parent() function. In the “index.html” file I have a <div id = 'sketch-holder'> element to place the canvas on the page.

let canvas;

function setup(){
 canvas = createCanvas(650, 375);

That worked fine. Then I decided I wanted to see how the site would function with the JS canvas running on a different HTML page, so I moved that <div id = 'sketch-holder'> into one of the html files in the “HTML” directory. The canvas is not on the new page and I have a 404 File not found error in the consol.

When I am pointing to an html file in the subdirectory, do I need to put something different in the canvas.parent() function? Something like this:


Thank you all as always for the help.

Without seeing all of your project files it is hard to say exactly what the issue is. However, conceptually speaking referencing an element in one HTML file from another is not possible in the way you have described. Excluding the use of frames, the web browser loads a single HTML file and that HTML file loads JavaScript files. The code in those JavaScript files can only reference elements that are either declared in that HTML file or added to the DOM via JavaScript. So if you want to replicate your sketch from index.html to a different page you will need that other page to load the p5.js library via a <script> tag, load your sketch JavaScript via a sketch tag, and declare any elements that your sketch JavaScript might be expecting to exist. So long as the layout of the page is similar you should be able to use the same sketch JavaScript on multiple pages.

Thank you for the response!

The beginning of the secondary HTML does include the following.

<script src="libraries/p5.min.js"></script>
<script src="libraries/p5.sound.min.js"></script>
<script src="../sketch.js"></script>
<script src="../Tile.js"></script>

The sketch.js and Tile.js files both work to create the effect I’m going for on the canvas. I also includd the “…/” because the .js files are in the main directory where as the HTML for the secondary pages is in a HTML/ directory. Do I not need those and maybe that was my issue?

I thought maybe initially that I was just misusing the .parent() function.

Your usage of ../ in the paths to your javascript files makes sense if this HTML file is in a subdirectory. You should check exactly which resource is generating an HTTP 404 when the page loads. Is your libraries folder also a level above the subdirectory where this HTML file is? Perhaps you need to be using ../libraries