I have a query.
I use to call a function on javascript event in 2 ways.
-
Inside HTML tag like:
<div id='someid' onmouseover='callFunc()'>Some Text</div> -
Outside tag like in script tag/ external file:
document.getElementById('someid').onmouseover=function(){ alert('hi'); }
Now I think both serve the same purpose, then is there any difference between the two ways? Which one is better? What are the pros and cons of both? Second, is there any other way to call this function?
Both are bad. You want addEventListener. A library like jQuery will make this much easier, like so:
Putting JavaScript inline in HTML is never a good idea; it’s hard to write (you have to worry about escaping) and hard to maintain.
Assigning directly to
on*is ok, but then you can’t have multiple event handlers for the same event on the same element. If some other code tries to add a handler later, it’ll wipe out your handler.