JavaScript event handlers

I am trying to figure out how to programmatically add an event handler to a JavaScript object. More specifically, I am trying to add an event handler to the onunload event of a window object. I am trying to do this without any luck:

var url = "www.somelocation.com"; var specs = "location=0,menubar=0,status=0,titlebar=0,toolbar=0"; var dialogWindow = window.open(url, "dialog", specs, true); dialogWindow.onunload += myEventHandler; function myEventHandler(e) { // Do stuff } 

I assume that my syntax is incorrect. However, I cannot find any documentation about this. Can someone please help me?

+4
source share
2 answers

dialogWindow.onunload + = myEventHandler is invalid. It really should be:

 dialogWindow.unload = myEventHandler; 

Or save existing handlers:

 var oldHandler = dialogWindow.unload; dialogWindow.unload = function (e) { if (oldHandler) { oldHandler(e); } myEventHandler(e); } 

And, of course, use jQuery .

+6
source

Javascript only manages objects. HTML DOM elements, including HTML5, are objects, we can classify them as follows:

  1. Window object with all events
  2. An IFRAME object as complete as Window (which is why it is used by Youtube)
  3. DOM objects that have only control events, click, mouseup, mouseDown ... as well as their own events (audio, video, DIV BLOCK), etc.

Creating JAVASCRIPT objects is a bit like Visual Basic or C ++.

Events are easy to manage, we can mix the events of smartphones and computers. To provide support for older SAFARI, IE browsers, simply avoid using specific keywords such as (LET, =>, or values ​​in function parameters such as X = 1).

Event Management:

  var mouseup = (!('ontouchstart' in document.documentElement))? 'mouseup':'touchend'; var winresize = (!('ontouchstart' in document.documentElement))? 'resize':'orientationchange'; var mouseover = (!('ontouchstart' in document.documentElement))? 'mouseover':'touchstart'; var mouseout = (!('ontouchstart' in document.documentElement))? 'mouseout':'touchend'; 

To ensure compatibility:

  var Event_mouseup = function (e)( Code mouseup....... }; if(object.addEventListener){ object.addEventListener(mouseup,Event_mouseup,{passive:true}); //passive true not return event }else if(object.attachEvent){ object.attachEvent(mouseup,Event_mouseup); }else{ object['on'+mouseup]=Event_mouseup; }; 

The Window object works exactly the same.

Event loading is really special on the HTML page.

Objects that handle this event are objects that load data, such as IMG, VIDEO, AUDIO, etc.

In general, when an object has a load event, it also has a load event with an error.

To understand the DOM and the browser, you must compare it, for example, with a C ++ window.

Window ----------------------- event Load -------- Object 1 HTML DOM --------- event1 Object --------- event2 Object -------- Object 2 HTML DOM --------- event1 Object --------- event2 Object ---------------------- event unload Window

+1
source

All Articles