Search code examples
javascriptimagelocal

How can I use local images in javascript?


Go easy on me, I'm VERY new and trying to learn. But simply I guess, trying to find a way to display images with javascript from a local file. I'm just trying to learn through tutorials and practice but any time I want to use an image, it has to be from an outside website apparently? eg - ButtonImg.src = "https://somesite/button.png";

But I would like to use just some graphics of my own. Why can't I do something like,

ButtonImg.src = "/home/username/public/button.png";

Thanks in advance for any help, would make learning so much easier.


Solution

  • When you're referencing a file on your own website, you have three options:

    • Relative path: This reference starts relative to the file you're referencing the image from. If the files are in the same folder, you only need to specify the image name itself: file.jpg. However, if it is in a parent folder, you can prefix the link with ../ to navigate to the parent folder (like you would with the cd command): ../images/file.jpg. If the file is in a sibling folder, you would reference that folder as the prefix: images/file.jpg.

    • Root-relative path: This is the same as a relative path, but prefixed with /. This refers the the root folder of the website (/var/www/html/ on Apache). /images/file.jpg will always refer to https://www.example.com/images/file.jpg, regardless of where the file is referenced from.

    • Absolute path: This is an absolute reference to the file, as it would be accessed directly from a web browser. For example: https:://www.example.com/images/file.jpg.

    There's also the ability to reference the file through the file:// protocol, though keep in mind this references a file on the local disk; it won't be accessible for anyone else viewing the website.

    Keep in mind that in all three of the cases, you'll need to ensure that the image is actually uploaded to the server (and included in the project in an integrated IDE), in addition to the file it is referenced from!