7

What is javascript: in a JavaScript event handler?

Such as:

<input onkeydown="javascript:return false;" type="text" name="textfield" />
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • possible duplicate of [Do you ever need to specify 'javascript:' in an onclick?](http://stackoverflow.com/questions/372159/do-you-ever-need-to-specify-javascript-in-an-onclick) – Bergi Sep 08 '13 at 09:44

5 Answers5

9

It is a mistake. The pseudo-protocol is not needed in event handlers.

On a URL (a element href attribute, for instance), if you enter javascript: and follow that with javascript, the browser will run the javascript code.

For event handler, this is not needed, though the browser will not report an error.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
8

In this case it will be interpreted as label. You could also write foobar: here, it would have the same effect.

It is not really needed in JavaScript code (I have never seen it used in real code), though it could be useful:

Provides a statement with an identifier that you can refer to using a break or continue statement.

For example, you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.

In your case, the markup should just be:

<input onkeydown="return false;" type="text" name="textfield" />

But if you use it as scheme in an URI, it tells the browser to interpret and execute the URI as JavaScript:

<a href="javascript:alert(1);">Foo</a>

(I'm not saying you should do something like this.)

I assume people less familiar with JavaScript see this and think they have to put javascript: everywhere in front of JavaScript code in HTML, also in event handlers.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

You can just write return false. At that time the javascript protocol was useful in links. href attribute: <a href="javascript:return false">

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bjornd
  • 22,397
  • 4
  • 57
  • 73
0

It's something that shouldn't be there.

The javascript: prefix is primarily used for links, as the javascript: protocol in a browser would generally execute the code, for example:

<a href="javascript:alert('test')">Test</a>

In an event handler, though, it's already parsing JavaScript, thus it is not required. It's basically doing nothing.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
-1

It's just markup to tell the browser that what follows is JavaScript code. However, it is not needed, so you don't have to include it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Richard H
  • 38,037
  • 37
  • 111
  • 138