Shawn
Shawn

Reputation: 1183

HTML vs Javascript.. How does filepathing to images work?

I am noticing that in HTML, the image source starts wherever my page location (base) is located at. So if my pictures or images are in another folder, I can short hand the src by saying the following:

<img src="avatars/dwarf14.jpg">

However I noticed in javascript, I CANNOT do the same thing. I had to type out my entire C directory to find the same image. Why is this? I assumed the starting location for my image path would be where my javascript file was located.

dom.el("playeravatar").innerHTML = '<img src="C:/Users/Q/Desktop/Gaming Project/avatars/warrior4.jpg">';

Upvotes: 0

Views: 103

Answers (3)

Abhijit Annaldas
Abhijit Annaldas

Reputation: 667

<img id='img' src='img.jpg' style="max-height: 200px; max-width:200px" /> <br />
<img id='imgJS' style="max-height: 100px; max-width:100px" /> <br />
<div id='divJS' />
<script type="text/javascript">
    document.getElementById('imgJS').src = 'img.jpg';
    document.getElementById('divJS').innerHTML = '<img src="img.jpg" style="max-height: 50px; max-width:50px" /> <br />';
</script>

I was able to load the image from javascript. The above code sets the same image on an img tag and adds a new img tag with source set inside a div tag, used different sizes to distinguish. Place this code and the image in same folder, it works.

David has given an apt explanation. DOM handles the path and is relative to the document, not to the JavaScript file.

Upvotes: 0

AkshayJ
AkshayJ

Reputation: 769

No its not the case.The starting location for your image path would be the html page where the .js file is loaded :)

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129832

The script simply adds an img tag to the DOM. The browser will then parse this tag just like one that was hard coded or added by any other means. How the src attribute will be interpreted has no relation to the javascript.

For this reason, it is of no interest where the javascript file is located. Your paths should be relative to the document to which you insert the image.

Upvotes: 2

Related Questions