Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 to know when to use javascript: and when not to.

Any suggestions are appreciated.

like image 920
Raja Asthana Avatar asked Jan 30 '13 13:01

Raja Asthana


2 Answers

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)

like image 188
VisioN Avatar answered Oct 05 '22 21:10

VisioN


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.

like image 34
War10ck Avatar answered Oct 05 '22 21:10

War10ck