ResolveUrl in Javascript

Posted: May 31, 2011 in JavaScript

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s