[javascript] Relative Paths in Javascript in an external file

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?

This question is related to javascript html asp.net-mvc css path

The answer is


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>

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.


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


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

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

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>


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


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


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to path

Get Path from another app (WhatsApp) How to serve up images in Angular2? How to create multiple output paths in Webpack config Setting the correct PATH for Eclipse How to change the Jupyter start-up folder Setting up enviromental variables in Windows 10 to use java and javac How do I edit $PATH (.bash_profile) on OSX? Can't find SDK folder inside Android studio path, and SDK manager not opening Get the directory from a file path in java (android) Graphviz's executables are not found (Python 3.4)