menu

Questions & Answers

Colon operator ":" before function call (javascript)

I was looking at the source to a website and I saw this strange href attribute in a link and I can't figure out what it's doing. It doesn't look like valid javascript. I thought maybe the colon operator here was being used as a way to access the function property popDocWin in the object javascript but when I tried to emulate that syntax on a test function it wouldn't work.

<a href="javascript:popDocWin('aviewdocument.aspx?t=4704396');">Exterior Adjustable</a>
Answers(3) :

javascript: is a psuedo-protocol meaning "run the code following this." You can use it (in a browser context) anywhere a URL is valid. In this case, clicking the link "follows" the link, and the act of following the link runs the JavaScript rather than going anywhere. (This is also how bookmarklets work.) So the javascript: part of that isn't JavaScript, just the part after it.


However, something that looks like that is valid JavaScript: If it weren't in a URL, it would create a labelled statement. The primary use of labelled statements in JavaScript is breaking outer loops from within inner ones, like this:

var x, y;
outer: for (x = 0; x < 5; ++x) {
    for (y = 0; y < 5; ++y) {
        if (x === 2 && y === 3) {
            break outer;
        }
        snippet.show("x = " + x + ", y = " + y);
    }
}

Output:

x = 0, y = 0
x = 0, y = 1
x = 0, y = 2
x = 1, y = 0

Note how the x loop was terminated from within the y loop.

var snippet = {
  show: function(msg) {
    document.body.insertAdjacentHTML("beforeend", "<p>" + msg + "</p>");
  }
};

var x, y;
outer: for (x = 0; x < 3; ++x) {
    for (y = 0; y < 3; ++y) {
        if (x === 1 && y === 1) {
            break outer;
        }
        snippet.show("x = " + x + ", y = " + y);
    }
}

The colon is not before the function call, its after the word javascript!

It is telling your browser it should execute the javasript code after the colon.

Well, href isn't a place where your browser would expect javascript code, so javascript: tells the browser that it should treat whatever is after it as javascript.