Inline assignment the function is represented as a string (in all the below, the highlighted is a function):
Code:
<a href="whatever.htm" onclick="alert('You Clicked Me!'); return flase;
">Click</a>
Basic assignment by javascript and getElementById the function is a true function:
Code:
<a id="mylink" href="whatever.htm">Click</a>
<script>
document.getElementById('mylink').onclick = function(){alert('You Clicked Me!'); return false;}
;
</script>
Or the less favored, back to representation as a string:
Code:
<a id="mylink" href="whatever.htm">Click</a>
<script>
document.getElementById('mylink').onclick = new Function("alert('You Clicked Me!'); return false;
");
</script>
With the two string methods, nested quotes are more limited because the function itself is a quoted string. And evaluation by the browser's script parser is more time consuming and generally more subject to type errors.
With all three of the above methods, the link may have one and only one onclick event. If another is assigned with the basic or less favored methods later, it overwrites the previous one.
Using add/attach methods (actually the preferred method for ordinary javascript because more than one event of the same type can be assigned to an element), and we're back to a true function at least:
Code:
<a id="mylink" href="whatever.htm">Click</a>
<script>
function myfunc(e){
e = e || event;
if(e.preventDefault){e.preventDefault();}
e.returnValue = false;
alert('You Clicked Me!');
}
if (window.addEventListener){
document.getElementById('mylink').addEventListener('click', myfunc, false);
}
else if (window.attachEvent){
document.getElementById('mylink').attachEvent('onclick', myfunc);
}
</script>
Which is one reason why jQuery can be attractive (multiple events can be assigned this way too, and we have a true function):
Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
$('#mylink').click(function(e){
e.preventDefault();
alert('Ahh, jQuery');
}
);
});
</script>
<a id="mylink" href="whatever.htm">Click</a>
And, believe it or not, there are at least several other ways to do this.
Bookmarks