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 to know when to use javascript:
and when not to.
Any suggestions are appreciated.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With