Relative Paths in Javascript in an external file

JavascriptHtmlasp.net MvcCssPath

Javascript Problem Overview


So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.

This is in an external .js file, folder structure is

Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg

then this is where the js file is included from

Site/Views/ProductList/Index.aspx

$("#toggle").click(function() {
    if (left.width() > 0) {
        AnimateNav(left, right, 0);
        $(this).css("background", "url('../Images/filters_expand.jpg')");
    }
    else {
        AnimateNav(left, right, 170);
        $(this).css("background", "url('../Images/filters_collapse.jpg')");
    }
});

I've tried using '/Images/filters_collapse.jpg' and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.

Basically, I want have the same functionallity as the ASP.NET tilda -- ~.

update

Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?

Javascript Solutions


Solution 1 - Javascript

JavaScript file paths

When in script, paths are relative to displayed page

to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:

Solution, which was employed on StackOverflow around Feb 2010:

<script type="text/javascript">
   var imagePath = 'http://sstatic.net/so/img/';
</script>

If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section

Solution 2 - Javascript

get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:

var jsFileLocation = $('script[src*=example]').attr('src');  // the js file path
jsFileLocation = jsFileLocation.replace('example.js', '');   // the js folder path

(assuming your javascript file is named 'example.js')

Solution 3 - Javascript

A proper solution is using a css class instead of writing src in js file. For example instead of using:

$(this).css("background", "url('../Images/filters_collapse.jpg')");

use:

$(this).addClass("xxx");

and in a css file that is loaded in the page write:

.xxx {
  background-image:url('../Images/filters_collapse.jpg');
}

Solution 4 - Javascript

Good question.

  • When in a CSS file, URLs will be relative to the CSS file.

  • When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).

There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:

<script type="text/javascript">

  directory_root = "http://www.example.com/resources";

</script> 

and to reference that root whenever you assign URLs dynamically.

Solution 5 - Javascript

For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:

<body>

<script>
    var templatesPath = "@Url.Content("~/Templates/")";
</script>

<div class="page">
	<div id="header">

       <span id="title">
         
		</span>
	</div>
	<div id="main">

    
		@RenderBody()
	</div>
	<div id="footer">
        <span></span>
	</div>
</div>

Solution 6 - Javascript

I used pekka's pattern. I think yet another pattern.

<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">

and parsed querystring in myjsfile.js.

[Plugins | jQuery Plugins](http://plugins.jquery.com/project/query-object "Plugins | jQuery Plugins")

Solution 7 - Javascript

Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript

<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>

Solution 8 - Javascript

I found this to work for me.

    <script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +     
    window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>

between script tags of course... (I'm not sure why the script tags didn't show up in this post)...

Solution 9 - Javascript

You need to add runat="server" and and to assign an ID for it, then specify the absolute path like this:

<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]

From the codebehind, you can change the src programatically using the ID.

Solution 10 - Javascript

This works well in ASP.NET webforms.

Change the script to

<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....

I have a master page for each directory level and this is in the Page_Init event

  Dim vPath As String = ResolveUrl("~/Images/")
    Dim SB As New StringBuilder
    SB.Append("var imagePath = '" & vPath & "'; ")
    ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)

Now regardless of whether the application is run locally or deployed you get the correct full path

http://localhost:57387/Images/chevron-large-left-blue.png

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNateView Question on Stackoverflow
Solution 1 - JavascriptJuraj BlahunkaView Answer on Stackoverflow
Solution 2 - JavascriptschoryView Answer on Stackoverflow
Solution 3 - JavascriptHandsome NerdView Answer on Stackoverflow
Solution 4 - JavascriptPekkaView Answer on Stackoverflow
Solution 5 - JavascriptVijayanand SettinView Answer on Stackoverflow
Solution 6 - JavascripttakeparaView Answer on Stackoverflow
Solution 7 - JavascriptMandeep JanjuaView Answer on Stackoverflow
Solution 8 - JavascriptJamminJamaicanView Answer on Stackoverflow
Solution 9 - JavascriptSamir AhmedView Answer on Stackoverflow
Solution 10 - JavascriptgchqView Answer on Stackoverflow