Skip to content Skip to sidebar Skip to footer

Why Do You See Colons While Calling A Javascript Function In Html Sometimes?

A lot of the time I see people calling javascript functions using colon (:). Like onclick='javascript:functionname();' The same function works without javascript: and I'm curious t

Solution 1:

javascript: prefix is extremely important when you put code to anchor href attribute:

<a href="javascript:func();">Anchor</a>

Whereas in inline event attributes (like onclick, onsubmit, onmouseover, etc.) javascript: prefix is not important.

However, you should note that both approaches given here are not good to implement and you should use alternative ways (e.g as @Paul S. stated in the comments)


Solution 2:

This is not as commonly seen in onclick events as these events already execute javascript. You will may see something like the following quite a bit:

<a href="javascript: functionname(); return false;">Link</a>

The reason for such code is that by default an href attribute is trying to change the location or redirect. This tells the browser that the default href action will be javascript that is run. Otherwise, the function will not run and the page will refresh which is quite annoying.

Page refreshing is a common issue when using javascript like this in an anchor tag since an anchor tags default action is to refresh or load another page. The return false; at the end signals that the default action (i.e. refresh or load) should not fire.

Hope this helps.


Solution 3:

I believe the javascript: prefix is left over from when there were many other script types bouncing around on the web (vbScript, for example) and in order to differentiate between them in HTML you needed to provide these prefixes.

That being said, these tags do absolutely nothing in any browser other then IE anymore, and even in IE you generally can omit them.

Also notice that this entire question is moot since you should be binding event handlers through javascript, not in HTML.


Post a Comment for "Why Do You See Colons While Calling A Javascript Function In Html Sometimes?"