views:

732

answers:

3

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>
+6  A: 

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
<a href="#" onclick="alert('some text');">link</a> 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
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
This is good information, but not an answer to my question.
Heath Borders
Sorry, I misunderstood.
James Socol
+6  A: 

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
+9  A: 

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?

Shog9
::Whacks self on head::Thanks!
Heath Borders