Onclick = "javascript: func ()" vs. onclick = "func ()"

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 calling the JS function?

+8
javascript
source share
3 answers

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

However, the use of inline event handlers is not recommended; better methods for registering event handlers are better .


Although not mentioned in the question, it is worth noting that using javascript: in the href attribute really works (and it is really necessary there), but is very discouraged for various reasons:

  • this does not point to an element
  • Calling a function that returns a value causes the browser to leave the site.
  • By clicking on the link with JavaScript breaks disabled
  • Trying to open a link in a new window / tab

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

+10
source share

When you are in the onclick attribute, you should not use the javascript: prefix. This is useful if you want the <a /> link to process a JS function, for example:

 <a href="javascript:myfunc();"></a> 
+1
source share

javascript:func() uses the javascript protocol so that it can be used in the anchors href attribute. However, do not do this; see Why is it bad practice to use links with javascript: "protocol"? for more information.

Event handlers prefer to fire events instead of attributes.

+1
source share

All Articles