Skip to content
Advertisement

Javascript: How to use a unique URL taken from different directories

Sorry if the title is not clear I clarify what I want to do.

I have a main.js which is used by all my pages. In this main.js I have some URLs: let’s say

var myImgUrl = "/img/thisPicture.png";

The problem is that main.js is used by different pages which are in different directories respect to main.js. This means that the path should be different.

For example, let’s say my directories’s like this

  • js > main.js
  • img > thisPicture.png
  • index.html
  • bio > mybio.html
  • activities > myActivity.html

now, of course from pages "myActivity.html", "mybio.html" and index.html there will be three different paths to get to thisPicture.png but they all three use main.js as script file.

Question: is it possible to write a for myImgUrl which will be unique for all files? And, if so, how can I do it?

Advertisement

Answer

Use the full path to the file you are wanting to reference instead of a relative path.

var myImgUrl = "https://www.example.com/img/thisPicture.png";
Advertisement