-1

How can I add an try catch in a addEventListener? Is there any way?

I need to use the try catch at addEventListener or attachEvent not in the inner function

    document.addEventListener("DOMContentLoaded", function (event) {
 X();
    });


    document.attachEvent("onreadystatechange", function () {
        if (document.readyState === "complete") {
            X();
        }
    });
fba_pereira
  • 196
  • 2
  • 12

3 Answers3

4
 document.addEventListener("DOMContentLoaded", function (event) {
      try {
          x();
      } catch (e) {
          alert(e.message);
      }
  });


  document.attachEvent("onreadystatechange", function () {
      if (document.readyState === "complete") {
          try {
              x();
          } catch (e) {
              alert(e.message);
          }
      }
  });

If you are facing issue with event registration due to different browser capabilities use below code

if (document.addEventListener){  
  document.addEventListener(...);
} else if (document.attachEvent){  
  document.attachEvent(...);  
} 

More generalized way

    function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // W3C DOM
      elem.addEventListener(evnt,func,false);
   else if (elem.attachEvent) { // IE DOM
      elem.attachEvent("on"+evnt, func);
   }
   else { // No much to do
      elem[evnt] = func;
   }
}
Kaushik Thanki
  • 3,334
  • 3
  • 23
  • 50
3

You can simply add it like

document.addEventListener("DOMContentLoaded", function (event) {
  try{
      X();
  }
  catch(e){
   //How you want to handle it
  }
});
Zee
  • 8,420
  • 5
  • 36
  • 58
  • We need to use the try catch at addEventListener or attachEvent not in the inner function – fba_pereira May 29 '15 at 11:48
  • Why so?! Why in this world you would need to try-catch on adding an event listener? It's as simple as `if (document) { document.addEventListener`.... – Andrey Popov May 29 '15 at 11:51
  • Because we use an softphone linked into our software by an java script function, and this addEventListener are throwing excepetions, and we believe that it may caused by an crossed injection, and the only way to confirm or discard this idea is by adding an try catch – fba_pereira May 29 '15 at 11:54
1

This should work

try
{
    document.addEventListener("DOMContentLoaded", function (event) { 
        X();
    });
}
catch(e) 
{ 
    alert('Couldnt create event listener.'); 
}

There is another example at the botton of this page:

http://www.thecssninja.com/javascript/handleevent

Sven Liebig
  • 828
  • 7
  • 18