Reputation: 32157
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>
Upvotes: 20
Views: 6823
Reputation: 10955
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.
Upvotes: 0
Reputation: 159668
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
).
Upvotes: 19
Reputation: 19446
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.
Upvotes: 9
Reputation: 1795
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>
Upvotes: 12