9

Is there any difference between

<input type="submit" value="Register" onclick="javascript:submitTheForm();">

and

<input type="submit" value="Register" onclick="submitTheForm();">

Should I use javascript: before a JS function call?

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Pat Wangrungarun
  • 516
  • 4
  • 12

3 Answers3

10

javascript: inside an onwhatever="" handler is a no-op. The content of this attribute is always JavaScript so javascript: defines a label - but outside of a switch block or a loop (where you can use it to break/continue to the position of the label) it does nothing.

However, using inline event handlers is discouraged, there are better ways to register event handlers.


While not mentioned in the question, it's worth noting that using javascript: in the href attribute does work (and in there it is actually necessary) but is highly discouraged for various reasons:

  • this does not point to the element
  • Calling a function returning a value causes the browser to leave the site
  • Clicking the link with disabled JavaScript breaks
  • Trying to open the link in a new window/tab breaks

So, if you really have to use inline events, always use onclick="" etc. without javascript:.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

When you are in a onclick attribute, you shouldn't use the javascript: prefix. This is usefull when you want a link <a /> to handle a JS function, for example:

<a href="javascript:myfunc();"></a>
sp00m
  • 47,968
  • 31
  • 142
  • 252
  • 2
    `javascript:` URLs are bad. Not only do they break with disabled JavaScript but they also cause problems if the function returns a value. So better use a proper URL in the `href` (or `#` if the link does not have a non-js fallback) and `onclick` to run your javascript code (`return false;`/`preventDefault` to avoid loading the href of the link) – ThiefMaster Apr 20 '12 at 08:19
  • 1
    I agree with you. The question was about the `javascript:` prefix. – sp00m Apr 20 '12 at 08:21
1

javascript:func() is using the javascript protocol so that it could be used in an anchors href attribute. However, don't do this see Why is it bad practice to use links with the javascript: “protocol”? for more information.

Event handlers are preferable to trigger events instead of attributes.

Community
  • 1
  • 1
detaylor
  • 7,112
  • 1
  • 27
  • 46