Reputation: 76
In JavaScript I want to load an image file from a different directory. My file structure is as such:
Project/js/script.js
Project/img/1.png
In script.js
I want the following:
document.getElementById("image").src = "Project/img/1.png";
How do I make this work?
Upvotes: 1
Views: 11534
Reputation: 809
The browser doesn't ever know what root folder the files are in - it only knows what it sees from the URL. It seems like your project's root is in the Project folder, and everything lives under that. (like when you go to http://example.com/, your web daemon is configured to look in your 'Project' folder?)
so you should be able to do:
document.getElementById("image").src = "/img/1.png";
the first slash says "go to my root folder, whatever that is on the web server", and then the rest is just the remaining path.
Upvotes: 1
Reputation: 707178
Your HTML file establishes the base path by which other relative paths are evaluated. So, if your HTML file path is "http://example.com/something/Project/index.html"
, then the Project directory is already the default location so you can access other things relative to the Project
directory like this:
js/script.js
img/1.png
Any relative path that does not start with a domain or with /
will have http://example.com/something/Project/
prepended to it.
Upvotes: 1