A link to the same URL with a different port

Let’s say, that you need to make a <a href=""></a> link, that will point you to the very same URL (as page, in which have this link), but to a different port. Even though there are no reasons for not implementing support for links like <a href=":8080">jump</a>, as of writing this, such support is not implemented in any known browser. And thus, neither this link work nor pure-HTML solution is available.

You must hire Javascript to resolve this problem.

First scenario is, that you only need to point to the very same URL, but to a different port. For example, your page (with HTML links) is served at http://www.example.com/ and you want a link, that will point to http://www.example.com:8080/. In this case, the solution is quite easy. Here it comes (a modified version of this post):

document.getElementById('cp-link').onclick = function(event){window.location.port = 8080; return false;};

Things get a little bit more complicated, when you need to make a link, that contains both different port and some relative URL part. In this case, we use quite similar technique, but a bit more code (a bit changed version of this post):

document.getElementById('download-station-url').onclick = function(event) {
    var target = event.target;

    if (target.tagName.toLowerCase() == 'a') {
        var port = target.getAttribute('href').match(/^:(d+)(.*)/);
        if (port) {
            target.href = port[2];
            target.port = port[1];
        }
    }
};

That’s all, folks! :>

Leave a Reply