I have been using onclick to execute my javascript code for a long time, but I was told by many folks not to use this inline javascript, and I don't know the disadvantage of it
Asked
Active
Viewed 79 times
0
-
I wonder whether any short comings of inline javascript @Gyandeep – kesong Feb 23 '14 at 21:56
-
2Maybe after reading http://www.quirksmode.org/js/events_early.html and http://www.digital-web.com/articles/separating_behavior_and_structure_2/, you will have a better idea of the issues. – Felix Kling Feb 23 '14 at 21:57
-
You should not use inline javascript in your HTML file, but better use a library like jQuery which allows you to set the events in a separate file. – htatche Feb 23 '14 at 21:57
-
4@htatche: You don't need jQuery to bind event handlers with/in JavaScript. – Felix Kling Feb 23 '14 at 21:57
-
1@FelixKling I never said you do :) – htatche Feb 23 '14 at 21:58
-
@htatche: You kind of did. "jQuery allows you to do X" can imply that X is not possible otherwise. – Felix Kling Feb 23 '14 at 21:59
-
@FelixKling Sorry for naming jQuery then. – htatche Feb 23 '14 at 22:00
-
@Quentin: I might just move my answer over there, what do you think? The answers there don't seem to cover what I explained. – Felix Kling Feb 23 '14 at 22:30
-
@FelixKling — Yours is the better answer. I'd lean towards doing that, especially if it looks like this one will be closed. – Quentin Feb 23 '14 at 22:32
-
I copied my answer to the other question and will delete mine here. As for the problem mentioned in one of your comments, check out event delegation: http://learn.jquery.com/events/event-delegation/. – Felix Kling Feb 23 '14 at 22:38
-
@Quentin: Ah actually [bobince linked to](https://stackoverflow.com/questions/6941483/onclick-vs-event-handler#comment8273183_6941483) [another question](http://stackoverflow.com/questions/5127037/disappearing-google-map/) which exactly explains what I wrote. Anyways, I'll leave it now as it is. – Felix Kling Feb 23 '14 at 22:41
1 Answers
0
If you mean the difference between these, the second is far clearer and cleaner, because it separates the behaviour from the content.
Method 1:
index.html:
<div onclick="alert('div clicked!');this.innerHTML='Clicked!';">Not clicked...</div>
Method 2:
index.html:
<div id="123">Not clicked...</div>
<script src="js/scripts.js"></script>
js/scripts.js:
var elem = document.getElementById("123");
elem.onclick = function(e) {
alert('div clicked!');
this.innerHTML = 'Clicked!';
};

Toothbrush
- 2,080
- 24
- 33