Posts Tagged ‘Cross-browser’

Which HTML element is the target of the event

Mozilla, Safari and Internet Explorer handle differently which HTML element is the target of the event. Here is a simple code snippet that allows you to get what you want.

function myFunction(e) {
  var element;
  if (!e) var e = window.event;
  if (e.srcElement) element = e.srcElement;
    else if (e.target) element = e.target;
  if (element.nodeType == 3) // defeat Safari bug
    element = target.parentNode;

  // Here you can get the property of the element

}

In Safari if an event takes place on an element that contains text, this text node, and not the element, becomes the target of the event. Therefore we check if the target’s nodeType is 3, a text node. If it is we move to its parent node, the HTML element.

Read the rest of this entry »