Search code examples
javascriptdom-events

Script Tag Binding Method


The following code is NOT working as expected. I am using "Script Tag Binding Method" to have the events fired. Can you please FIX this?

<html>    
    <head>    
                <title>
                    Example
                </title>    
    </head>    
    <body>    
        <input type="button" name="cmdScriptTag" value="Script Tag">    
                <script language="javascript" For="cmdScriptTag" Event="OnClick">    
                    alert("Script Tag Binding Method.");    
                </script>    
        </body>    
</html>

Solution

  • In your code you have:

    > <script language="javascript" For="cmdScriptTag" Event="OnClick">
    

    The language attribute for script elements was deprecated in HTML 4 and is removed in HTML5. The type attribute is required in HTML 4 and optional in HTML5. In practice, it's not necessary, you can just use:

    <script>
      /* content */
    </script>
    

    The for attribute for script elements is a Microsoft proprietary feature that is not part of any standard and probably not supported at all outside of IE (and possibly not supported by current IE versions). It was reserved for future use in the DOM 2 HTML spec but never implemented for script elements (as far as I know). It applied only to label elements in HTML 4.01, same in HTML5.

    As far as I'm aware, there never was an event attribute, it may have been related to the for attribute but neither are listed at MSDN.

    The event attribute is similar to the for attribute: it's an IE feature that's not widely implemented and associates the script within a script element with an event for another element. Essentially it's the same as using other standards compliant methods to associate script with elements and events but a lot clunkier.

    In any case, to associate a function with an element that will be called when the element receives a certain event, you can use a variety of methods. The most robust and widely implemented are inline listeners, e.g.:

    <input type="button" name="cmdScriptTag" value="Script Tag"
     onclick="alert('Script Tag Binding Method.');">
    

    Though generally the script body is put in a function that is called by the listener, e.g.

    <script>
      function foo(){
          alert('Script Tag Binding Method.');
      }
    </script>
    <input type="button" name="cmdScriptTag" value="Call foo"
     onclick="foo();">
    

    You can also attach listeners dynamically using various methods such as addEventListener, which is explained on the Mozilla Developer Network (MDN).