6

What is javascript: in a JavaScript event handler?

Such as:

<input onkeydown="javascript:return false;" type="text" name="textfield" />
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
  • 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

8

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
  • 477,625
  • 97
  • 867
  • 998
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
  • 756,363
  • 169
  • 1,062
  • 1,111
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,030
  • 21
  • 100
  • 124
bjornd
  • 21,619
  • 4
  • 53
  • 70
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,030
  • 21
  • 100
  • 124
Rudi Visser
  • 20,568
  • 5
  • 66
  • 95
-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,030
  • 21
  • 100
  • 124
Richard H
  • 36,221
  • 37
  • 107
  • 137