20

I know that you can use a javascript: pseudo protocol for URLs in an <a> tag. However, I've noticed that Firefox and IE will both allow 'javascript:' to precede javascript code within a <script> tag. Is this valid syntax? Does it change the scoping rules?

Examples: I've seen this many times:

<a onclick="javascript:alert('hello world!');">Hello World!</a>

But is this legal/valid syntax and does it do anything special:

<script type="text/javascript">
javascript:alert('hello world!');
</script>
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Heath Borders
  • 30,998
  • 16
  • 147
  • 256

4 Answers4

19

Outside of the href attribute (where it is a protocol specifier), name: just creates a label (such as one might use with a continue or break).

See: Do you ever need to specify javascript: in an onclick?

Community
  • 1
  • 1
Shog9
  • 156,901
  • 35
  • 231
  • 235
12

You need the javascript: "protocol" when you want to put JavaScript in the href attribute of a link.

<!-- does not work -->
<a href="alert('some text');">link</a>

<!-- does work -->
<a href="javascript:alert('some text');">link</a>

<!-- also works -->
<a href="#" onclick="alert('some text');">link</a>

As far as I know (and please, if I'm wrong, someone correct me) there is no difference in scope, but there is a very important difference about this.

<!-- does not work -->
<a href="alert(this.href);">link</a>

<!-- alerts "undefined" -->
<a href="javascript:alert(this.href);">link</a>

<!-- works as expected, alerts "<url>#" -->
<a href="#" onclick="alert(this.href);">link</a>
James Socol
  • 1,795
  • 10
  • 11
  • link is considered best practice. conceptually, the url bar should be for urls, not scriptlets. javascript: will change the url bar, onclick will not. Good answer though, +1 – Matt Briggs Feb 18 '09 at 15:56
  • Agreed. Though for some cases, using href="#" will cause your page to jump around. When that happens, I'm OK with href="javascript:;" or href="javascript:void();". – James Socol Feb 18 '09 at 16:06
9

One thing to consider, our testers would always ding us if we did something like


<a href='javascript:openwindowmethod("url");'> stuff </a>

Rather than


<a href='url' onclick='return openwindowmethod(this.href);'> stuff </a>

The first method would only work if you click on it but not if you shift or alt clicked on it, or right clicked and went to open in a new window.

The second method would support all of that, as well as the ability to function the way it intended if the user just plain clicked the link.

Allen Rice
  • 19,068
  • 14
  • 83
  • 115
0

The javascript: syntax can be used anywhere in a URL and executes the following string as a script. It is part of the HTML spec and AFAIK is supported by all current major browsers.

qwr
  • 9,525
  • 5
  • 58
  • 102