Javascript – Get path to image

htmljavascriptrelative-path

I wrote a javascript method to display an image dynamically depending on whether or not a plugin is installed or not. Depending on the page, the url might be deep into sub paths and i wanted to see if i can get a path back to the image without all the marky-mark.

Example

myImage src location = {root}/Content/Images/myImage.png

Now call the js to display the image on the following pages. I show the path of the example page and the image element with the src path. Notice how its different depending on how deep we are. If i use an absolute path, then i would have to change it for my test environment and production. I thought I could use ~ but i guess not. Ideas ?

http://mysite.com/sub1/sub2/<img src="../../Content/Images/myImage.png" />

http://localhost:2500/sub1/<img src="../Content/Images/myImage.png" />

Best Answer

The tilde is only relevant for .NET server side code.

An easy way to accomplish what you're looking for is to write the root path out to a javascript variable or function.

For example on the server side on your page:

public string RootPath
{
  get
  {
     return ResolveUrl("~/");
  }
}

And then use the following javascript:

<script type="text/javascript">
<!--
function getRoot()
{
   return '<%= RootPath %>';
}
// -->
</script>

You can then use the javascript getRoot function to get to the root of the website and use it for your urls.