Reputation: 1819
Is there a particular reason programmers prefer not to use onClick function in Javascript?
Upvotes: 2
Views: 259
Reputation: 43619
Is that true that we don't use onclick? No that's not true.
FYI, onClick is a event handler to a HTML element.
We may be using onclick, but because of the ease and habit of using frameworks, you may not see the actual code.
Thus there may be variations.
This is one:
<div onclick="alert('yes');"></div>
This is another:
<div id="clickable"></div>
<script type="text/javascript">
document.getElementById('clickable').onclick=function(){alert('yes');};
</script>
This is using jQuery:
<div id="clickable"></div>
<script type="text/javascript">
$('#clickable').click(function(){alert('yes');});
</script>
Upvotes: 0
Reputation: 625037
Your question is unclear. What criticism are you referring to? The only thing that springs to mind is the move towards unobtrusive Javascript. The idea is simply to keep your markup as simple as possible and to put all your code in one place. So instead of:
<a id="link" href="..." onclick="open_new_window(); return false;">Open Window</a>
you have:
<a id="link" href="...">Open Window</a>
with something like jQuery:
$(function() {
$("#link").click(function() {
open_new_window();
return false;
});
});
This is much more maintainable and easier to read.
Upvotes: 6
Reputation: 123791
When javascript is disabled, normal <a
tag will still work, but not onclick
Upvotes: 1