0

I have seen at many locations that people use javascript: before functions(classes) or using attributes? E.g., javascript:Blob, javascript:void(0).

I'm wondering what are the situation when using this notation can be necessary? Or what're the best practices regarding using or not using this?

Expanding scope of my question:

Can it be useful to use it without href. I.e., in JS file directly?

Does ECMAScript have to do anything with it?

Muhammad Imran
  • 734
  • 7
  • 21
  • 6
    It really shouldn't be necessary at all; inline JavaScript is not a recommended practice. – Ja͢ck Jul 07 '15 at 04:40
  • 1
    Maybe you can find an useful answer here http://stackoverflow.com/questions/134845/href-attribute-for-javascript-links-or-javascriptvoid0 – ncubica Jul 07 '15 at 04:42
  • 1
    It is to tell the browser that the `href` contains Javascript code. Browsers normally expect to find a URL there. You should not put Javascript inside HTML attributes, so now you can forget about this. How fun. – Sverri M. Olsen Jul 07 '15 at 04:49
  • 1
    if you see `onclick="javascript:doSomething()"`, that's just "wrong", likely an amateur mistake (using labels for a non-loop expression). – dandavis Jul 07 '15 at 04:53

2 Answers2

2

"javascript:" is a URL protocol. When the browser loads a javascript: URL, it takes the rest of the URL as JavaScript code and executes it. Thus, you can put this in an href attribute on an <a> tag.

It's generally better to not do this, though - instead, you can set href='#' and put your JS code in the onclick attribute. (Some recommend setting href='javascript:void(0)', which is similar but subtly different. See here.)

Community
  • 1
  • 1
celticminstrel
  • 1,637
  • 13
  • 21
0

This is usually used for HTML a tag HREF's ie <a href="javascript:function();">LINK TEXT</a>

Eric Witchin
  • 574
  • 2
  • 8
  • He asked about best practice, this is totally beyond of bad practice please read http://stackoverflow.com/questions/134845/href-attribute-for-javascript-links-or-javascriptvoid0 – ncubica Jul 07 '15 at 04:43
  • Read the question carefully before answering.The question is why and not where javascript: is used – AkshayJ Jul 07 '15 at 04:44
  • No, the question was "what are the situation when using this notation can be necessary" - it is never necessary to have JavaScript URIs inside a `href`` attribute, as attaching event handlers is a preferred mechanism. – Amadan Jul 07 '15 at 04:53