JavaScript
  Home arrow JavaScript arrow Page 5 - Exception Handling in JavaScript: Addressi...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Exception Handling in JavaScript: Addressing Browser Incompatibilities
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2005-10-11

    Table of Contents:
  • Exception Handling in JavaScript: Addressing Browser Incompatibilities
  • JavaScript-based http requests: implementing cross-browser object instantiation
  • Cross-browser object instantiation: browser detection through exceptions
  • Proprietary event handlers: implementing browser-independent event handling
  • Assigning events to objects: using exceptions to manipulate event handlers

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Exception Handling in JavaScript: Addressing Browser Incompatibilities - Assigning events to objects: using exceptions to manipulate event handlers


    (Page 5 of 5 )

    As I said before, JavaScript exceptions are useful enough to be applied in different conditions. Particularly when working with event handlers, exceptions can be implemented directly, in order to deal with proprietary event handling methods. Considering the above listed example, which checks for support of specific methods, it’s feasible to write a new script that utilizes exceptions to handle raised errors. Here’s what it looks like:

    // Event Handler assignation using exceptions
    var obj=document.getElementsByTagName('div')[0];
    if(!obj){alert('Failed to get object!')};
    try{
        // browser is Firefox, Nestcape, etc
        // use addEventListener() method
        obj.addEventListener('click',processEvent,false);
    }
    // catch thrown error
    catch(e){
        try{
            // browser is Internet Explorer
            // use attachEvent() method
            obj.attachEvent('onclick',processEvent);
        }
        // catch thrown error
        catch(e){
            alert('Failed to add event handler');
        }
    }
    function processEvent(){
        alert('Event handler successfully attached!');
    }

    There are several points worth mentioning about the above code. First, the script attempts to attach to the <div> element an “onclick” event handler through the “addEventListener()” method, by executing the code within a “try” block.  As with XMLHTTP objects, if the code is successfully processed, the handler is tied to the proper object. Otherwise, if the attaching method is not supported by the JavaScript parser, an error will be triggered and trapped inside the corresponding “catch” block.

    Returning to program flow, a new “try” block is used to attach the event handler by using the “attachEvent()” method, which is supported by Internet Explorer. Finally, if all attempts fail, a warning is displayed since no handler was successfully attached. Before I continue with the code explanation, a brief note is in order here: there is a known issue with the “addEventListener()” method for IE 5 on Mac, which fails silently when invoked, so if you’re still getting many visitors using this browser, consider using another cross-browser solution that addresses this particular case too.

    By this point, hopefully you’ve understood the underlying logic of the above script, so there is plenty of room to experiment with different browser proprietary methods, for the sake of solving other incompatibilities. Of course, the whole script can be easily customized through a containing function, which would be much more useful than its current incarnation. As usual, feel free to use the above example and introduce your own improvements.

    For the sake of completeness, below is the full example, which also roughly implements exceptions to attach an “onload” event handler to the “window” object:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>EXCEPTION-BASED EVENT HANDLING ASSIGNATION</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />
    <script language="javascript">
    // Event Handler assignation using exceptions
    function processEvent(){
        alert('Event handler successfully attached!');
    }
    function addEventHandler(){
        var obj=document.getElementsByTagName('div')[0];
        if(!obj){return false};
        try{
            // browser is Mozilla, Nestcape, etc.
            // use addEventListener() method
            obj.addEventListener('click',processEvent,false);
        }
        // catch thrown error
        catch(e){
            try{
                // browser is Internet Explorer
                // use attachEvent() method
                obj.attachEvent('onclick',processEvent);
           }
            // catch thrown error
            catch(e){
                alert('Failed to add event handler');
            }
        }
    }
    // assign 'onload' event handler to window object
    try{
        window.addEventListener('load',addEventHandler,false);
    }
    catch(e){
        try{
            window.attachEvent('onload',addEventHandler);
        }
        catch(e){
            alert('Failed to add event handler');
        }
    }
    </script>
    </head>
    <body>
    <div>EXAMPLEPAGE</div>
    </body>
    </html>

    Conclusion

    Finally, we’re done. Over this series I’ve discussed in detail the use of exceptions in JavaScript programs, ranging from core concepts to advanced implementation, such as multiple errors handlers, custom error object creation and practical application on form validation and cross-browser scripts.

    Hopefully, the overall experience has been instructive enough for those developers that want to start out quickly using JavaScript exceptions within client-side applications. Even when exception-based programs take up some additional lines of code, giving a try is really worthwhile, due mainly to the fact that errors are handled through a more professional and robust built-in mechanism. There you have it, so take advantage of it!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · The last part of the series uses JavaScript exceptions for addressing some browser...
       · Wouldn't you agree that exceptions are not for a regular control flow and should be...
       · Thank you for posting your comments on my JavaScript article. Yeap, I agree with you...
     

    JAVASCRIPT ARTICLES

    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget
    - Ajax Hack for Entering Information Without R...
    - EXT JS 2.1 Overview
    - Using the Style Object for Zebra Tables with...
    - Binary Searching
    - An Improved Approach to Building Zebra Tables
    - Assigning Background Colors Dynamically to Z...
    - Building Zebra Tables with CSS and JavaScript
    - JavaScript: Array Objects
    - A Closer Look at Smart Markers with Yahoo! M...
    - Using Polylines and Smart Markers with Yahoo...







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway