9

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.

Community
  • 1
  • 1
Zhihao
  • 14,758
  • 2
  • 26
  • 36
  • 7
    Many people contend that mixing your JavaScript with you HTML is bad in general. (I tend to agree.) – FishBasketGordo Jul 25 '12 at 18:07
  • 2
    As @FishBasketGordo said, these are considered bad practice all around and they are outdated. Maintenance-wise, they are a headache. HTML is for structure, CSS is for style, and JavaScript is for functionality and interactivity. Keeping them separate simplifies your code, improves readability, and helps maintenance. – Jeff B Jul 25 '12 at 18:14
  • There are uses for inline JavaScript, but I personally would limit it to a single function call for maintenance. At that point, there's little difference between... `onclick="func()"`, and the common approach of adding a dedicated class to hook into... `class="a_class func_class"`. –  Jul 25 '12 at 18:42

2 Answers2

10

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:

<a onclick="alert('Hello World!')"...>example</a> //V1
<a href="javascript: alert('Hello World!')"...>example</a> //V2
<a onclick="javascript: alert('Hello World')"...>example</a> //V3

although they all will alert Hello World!.

The first (V1) has an inline click event 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 other click events 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 other click events bound in external scripts.

The first and second examples (V1 & V2) have identical code executed, which is:

alert('Hello World!')

The third example (V3) has an inline click event bound via the [onclick] attribute, just like V1, however the code being executed is different. The executed code is:

javascript: alert('Hello World')

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:

label: for (i = 0; i < 5; i++) { //labeled line
    for (j = 0; j < 5; j++) {
        console.log(i, j);
        if (i === 2 && j === 3) {
            break label; //this jumps out of both for loops
        }
    }
}

In most inline JavaScript, it's misused because the author doesn't understand the difference between the three formats.


Why is using javascript: <code> bad?

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 the javascript: <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 print button to the page:

<a href="#" onclick="window.print(); return false">Print</a>

Although even this example could be easily replaced by a class and externalizing the javascript:

<a href="#" class="print">Print</a>
<script>
     //jQuery used for brevity
     $(document).on('click', '.print', function () {
         window.print();
         return false;
     });
</script>
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Thanks for the excellent explanation. I suppose a better question would have been "what is this and what does it do?" – Zhihao Jul 25 '12 at 18:32
2

There's no real problem with using the javascript: labels. It's just considered bad style most of the time.

  • an onclick-handler already is JavaScript, so repeating that is just senseless, redundant information (in fact, it's chaging the code thats executed by adding a label named javascript - but in most cases this shouldn't have any effect).
  • JavaScript code in a href attribute would be placed more appropriately in an onclick handler, so you can use the href to provide a link for users that have JavaScript disabled. This is called Progressive Enhancement.

For more detailed information, you may want to take a look at this great blog-post about "The useless javascript: pseudo-protocol"

Community
  • 1
  • 1
oezi
  • 51,017
  • 10
  • 98
  • 115