ResolveUrl in Javascript

This is something that is super easy, yet I get asked about it quite often.

Here’s how you do it:

In the master page for the site, put this:

<script type="text/javascript">
        var baseUrl = "<%= ResolveUrl("~/") %>";
</script>

Then, in your javascript file, put this function:

function ResolveUrl(url) {
    if (url.indexOf("~/") == 0) {
        url = baseUrl + url.substring(2);
    }
    return url;
}

 

You could have put the function right in the master page, but then you wouldn’t get intelli-sense on it for the rest of your code.

Now you can call ResolveUrl with ~/ right from javascript. 

Super easy, but also super useful!

If you use themes, you might even want to write something that does a “get themed url” where the current theme is output from the master page via Page.Theme.

 

more later – joel.

Published Friday, July 17, 2009 2:00 PM by joelvarty
Filed under: ,

Comments

# ResolveUrl in Javascript | ASP Scribe

Friday, July 17, 2009 3:10 PM by ResolveUrl in Javascript | ASP Scribe

Pingback from  ResolveUrl in Javascript | ASP Scribe

# re: ResolveUrl in Javascript

Friday, July 17, 2009 3:12 PM by David

Neat and nice time-saving trick!

Experienced some issues with placing it in the header (runat=server) but got it resolved here:

leedumond.com/.../the-controls-collection-cannot-be-modified-because-the-control-contains-code-blocks

# re: ResolveUrl in Javascript

Wednesday, August 19, 2009 4:57 AM by arandall

brilliant little tip, has really helped to clean up my Javascript code!  Definitely going to be using this a lot in the future.

Many thanks :)

Leave a Comment

(required) 
(required) 
(optional)
(required)