Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!us.feeder.erje.net!newsfeed.fsmpi.rwth-aachen.de!weretis.net!feeder4.news.weretis.net!news.teledata-fn.de!newsfeed.arcor.de!newsspool4.arcor-online.net!news.arcor.de.POSTED!not-for-mail Content-Type: text/plain; charset="UTF-8" Message-ID: <5294499.JCWY7Ix9cy@PointedEars.de> From: Thomas 'PointedEars' Lahn Reply-To: Thomas 'PointedEars' Lahn Organization: PointedEars Software (PES) Date: Thu, 29 May 2014 22:35:40 +0200 User-Agent: KNode/4.12.4 Content-Transfer-Encoding: 8Bit Subject: Re: Event target in browsers Newsgroups: comp.lang.javascript References: <69413$5387765f$6def49ce$18425@nntpswitch.blueworldhosting.com> MIME-Version: 1.0 Lines: 72 NNTP-Posting-Date: 29 May 2014 22:35:41 CEST NNTP-Posting-Host: 710441e7.newsspool3.arcor-online.net X-Trace: DXC=6kiMjQi?ZhB2jYf>V4L0gLMcF=Q^Z^V3H4Fo<]lROoRA8kF > […] > var el = document.getElementById('btn') […]; > > function getEventTarget(e) { > var target = e.target; > if (target) { > if (target.nodeType !== 1) { > target = target.parentNode; > } > } else { > target = e.srcElement; > } > return target; > } > > function getElementNodeName(el) { > var nn = 'unknown'; > > if (el.tagName) { > nn = el.tagName; > } else if (el.nodeName) { > nn = el.nodeName; > } > > return nn.toLowerCase(); > } > > function listener(e) { > var tar = getEventTarget(e); > if (getElementNodeName(tar) === 'img') { > tar = tar.parentNode; > } > […] > } > > el.addEventListener('click', listener, false); > […] > In Firefox 29.0.1 and IE 11 I am getting as a target HTML "button" > element, but in Chrome 35.0.1916.114 m I am getting HTML "img" element. > […] > My understand is because different browsers implementing different way > how the events works. > http://www.w3.org/wiki/Handling_events_with_JavaScript#How_events_work > > Is my approach correct? No. The “click” event bubbles in all DOM implementations, and getElementNodeName() is overkill. getEventTarget() does not work because where only “srcElement” is available, the reference to the event object is _not_ passed as first argument to the listener (IE/MSHTML < 9 or Compatibility Mode in IE 9), and “window.event” must be accessed instead. But since EventTarget::addEventListener() is not implemented in the latter case, and you would not want to augment host objects, getEventTarget() is superfluous. As you are relying on the W3C DOM API already, just use “currentTarget” instead of “target”. (Works in Chromium 34. I need NSAPI plugin support, so I cannot test in Chromium 35 for the time being.) -- PointedEars FAQ: | SVN: Twitter: @PointedEars2 | ES Matrix: Please do not Cc: me. / Bitte keine Kopien per E-Mail.