92

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?

Nate
  • 30,286
  • 23
  • 113
  • 184
  • Is your application directory different in development compared to the server? Visual Studio's in built web server sets the default path to '/' if your server has say '/MyApp' you might have inconsistent behaviour. Try setting your visual studio path to '/MyApp' – sarvesh Feb 02 '10 at 22:31
  • That is exactly the problem! Depending on where the virtual directory is located, I don't want to have to update my javascript every time I switch from dev to production... – Nate Feb 02 '10 at 22:32
  • Seems like this, http://www.superexpert.com/blog/archive/2009/02/18/asp.net-mvc-tip-47-ndash-using-resolveurl-in-an-html.aspx, is what you are looking for. – sarvesh Feb 02 '10 at 22:37
  • I'm using javascript to dynamically change the background image of a div tag. I'd like to avoid putting the code back into the master page file, since it's much more clean its own external .JS file... – Nate Feb 02 '10 at 22:43
  • There is nothing like ~ for javascript. You could have a helper function in JS. For example you would call MyJs.Url('Images/filters.jp') and this prefix your virtual directory and return the string. This way you will only need to change it one location on deploy. – sarvesh Feb 02 '10 at 23:02
  • Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file? – Nate Feb 02 '10 at 23:03

10 Answers10

143

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

Juraj Blahunka
  • 17,913
  • 6
  • 34
  • 52
48

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')

schory
  • 631
  • 5
  • 5
  • $("#FkngDiv").load(jsFileLocation+"../FkngFolder/FkngPage.aspx") Worked like a charm for me. I'm using it this way to go back one folder level and then I just point to my desired path. – daniloquio Feb 22 '12 at 13:53
  • 6
    very good answer. I'd change the `.replace` expression to `jsFileLocation.replace(/example\.js.*$/, '')` in case there's a query string like a version number after the `.js` – yitwail Jul 22 '12 at 21:42
  • 1
    You dear sir, are my newest hero! Used this solution to find my css path on the server in an ASP.NET MVC Application, which is dynamically loaded from a folder one way sideways from my javascript folder... – Hutjepower Jun 11 '15 at 07:20
27

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');
}
Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173
  • 6
    This doesn't work if I'm using a non-css attribute. For example: ``. I can't set this src attribute by css. – Reza Sep 19 '13 at 14:42
14

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.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
5

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>

Vijayanand Settin
  • 826
  • 11
  • 13
4

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

takepara
  • 10,413
  • 3
  • 34
  • 31
2

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>
Mandeep Janjua
  • 15,583
  • 4
  • 29
  • 24
2

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)...

0

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.

0

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
gchq
  • 1,603
  • 2
  • 27
  • 52