Ad

Inline JS Callback Syntax Vs Internal JS Callback Syntax

Inline callback JS syntax looks like:

<h3 id="h3style" onMouseOver="changeColor();">     
      Rollover
</h3>

Internal callback JS syntax looks like:

<script>
     document.getElementById('h3style').onMouseOver = changeColor;
     function changeColor(){ } 
</script>

I understand that first syntax is evaluated by browser engine and second syntax is evaluated by JS engine.

But, Why html attribute onMouseOver has value as function call(with parenthesis) unlike second approach? Why html attribute syntax(onMouseOver="changeColor;") is not allowed?

Note: It is difficult to remember, two different syntax

Ad

Answer

Lets start by looking at the pure js version.

document.getElementById('h3style').onMouseOver = changeColor;
function changeColor(){ } 

Now in this situation, assigning a function is the only thing that you are able to do. You could obviously assign something weird like a value, but that just amounts to the code doing nothing (no errors even). The point is that you cannot assign a variable "some javascript" to complete, you can only create a function that contains "some javascript". In other words you can't do this:

elem.onMouseOver = 'changeColor();'; // technically legal but does nothing (just assigns a string)

However javascript does have eval() which is able to execute string versions of javascript. For example:

eval('changeColor();');

So now to the DOM. When you assign something to an attribute, the thing on the right hand side is a string (not actual javascript). Because it is a string, behind the scenes the system is only able to do something like eval().

The main takeaway point is that in the html case, the stuff you are writing inside the attribute is not javascript, but rather just a string. A string that gets evaluated at run time and converted into javascript.


Also to answer your final question: "Why html attribute syntax(onMouseOver="changeColor;") is not allowed?", well technically it is allowed. However it is equivalent to doing this in javascript:

onMouseOver = function(){
    eval('changeColor;');
}

Which clearly doesn't do a whole lot.

Ad
source: stackoverflow.com
Ad