Possible Duplicate:
Do you ever need to specify javascript: in an onclick?
To execute JavaScript on a DOM event, you could use something like this:
<div onclick="alert('Alert');">Alert</div>
Something like this seems to work as well:
<div onclick="javascript: alert('Alert');">Alert</div>
However, I’ve heard that the second example is “bad” and that the first example should be used over the second.
Is this bad? If so, why is this bad? What is the difference between alert('Alert') and javascript: alert('Alert')?
What about using it in <a> tags (if it is any different)?
<a href="javascript: alert('Alert');">Alert</a>
Edit: To clarify, I am asking about the javascript: part specifically, and not how I have inline JavaScript mixed in with my markup. Sorry about the confusion.
Oh the wonderful confusing world of JavaScript. The code you posted probably doesn’t do what most programmers think it’s doing.
There is a difference between each of the following lines:
although they all will alert
Hello World!.The first (V1) has an inline
clickevent bound via the[onclick]attribute. It may also contain an[href]attribute that navigates to another location after the[onclick]attribute has executed, or any number of otherclickevents bound in the code, assuming the default behavior hasn’t been prevented.The second (V2) has an executable
javascript:url set as the[href]attribute. It might also contain an[onclick]attribute or otherclickevents bound in external scripts.The first and second examples (V1 & V2) have identical code executed, which is:
The third example (V3) has an inline
clickevent bound via the[onclick]attribute, just like V1, however the code being executed is different. The executed code is:Although it looks like a
javascript:url, it’s actually just using a label in javascript.Labels in JavaScript are useful for skipping out of nested loops, as in the following example code:
In most inline JavaScript, it’s misused because the author doesn’t understand the difference between the three formats.
That’s a leading question. It assumes that using
javascript: <code>is bad.javascript: <code>isn’t bad. It’s a tool. Tools aren’t inherently good or bad, only the people using the tools are. You wouldn’t call a hammer “bad”, even if someone used it as a weapon.javascript: <code>has some nice uses. You shouldn’t use it for most cases because it’s the wrong tool for the job, however if you’re writing a bookmarklet, you’d be required to use thejavascript: <code>format.Additionally, there are a few niche contexts where it could make sense to leave javascript inline. An example of this would be to add a simple
printbutton to the page:Although even this example could be easily replaced by a class and externalizing the javascript: