3

Possible Duplicate:
Do you ever need to specify javascript: in an onclick?

What is better to write in MVC3 when on the onclick event for example we call function with functionName()? javascript:functionName() or just functionName()?

Community
  • 1
  • 1
Unknown
  • 1,377
  • 1
  • 15
  • 33
  • Your answer is here: http://stackoverflow.com/questions/372159/do-you-ever-need-to-specify-javascript-in-an-onclick Please use search :) – Oyeme Mar 05 '12 at 07:29
  • Thanks, I used the search but after 10 minutes of searching javascript: and other similar things I gave up and wrote the question. – Unknown Mar 05 '12 at 08:02

4 Answers4

4

Actually the best is to not mix javascript and markup. So you could attach this onclick event handler unobtrusively using javascript in a separate file. But as far as your question is concerned, you don't need the javascript: prefix.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

javascript: means different things depending on where it appears.

In a URI, it means to execute the JavaScript to get the resource. This is not progressive or unobtrusive and should be avoided.

In JavaScript (which the value of an onclick attribute is), it is a label:

  • There is no point in labelling anything except while, do, for and switch.
  • Most of the time, if a label would be useful, refactoring the code would be better.
  • javascript is a terrible label for a statement in a JavaScript program.
  • If you have a while, do, for or switch in an onclick attribute, then you need to break it out into a function for the sake of your own sanity when you come back to read it later.
  • onclick attributes are not unobtrusive and should be avoided anyway.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

It's better to not use javascript in your HTML, for separation of concerns and unobtrusive javascript.

If you want to add an onclick event, use the following:

document.getElementById('element').onclick = functionName

In your javascript file. This way, the presentation layer (HTML) is separated from the logic layer (Javascript).

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
1

Separating javascript from markup (aka behavioral separation or unobtrusive javascript) is the way to go. When you put your javascript within the markup (as in <div onclick="[javascript:]startMyFunction()" ...>), the expression has to be eval-ed, which spawns another interpreter.
So it's more efficient to put the scripting where it belongs: within the javascript tag.

KooiInc
  • 119,216
  • 31
  • 141
  • 177