Search code examples
javascriptimagemap

How to prevent Image map area click from propagating to link?


I have an HTML image map which has a few areas with links. I also have some Javascript functionality which, in certain cases, overrides the default functionality of the image map for some specific areas.

I have attached my function to the areas I want through this function (where el is the element, eventName is the name of the event and the eventHandler is the actual function):

function bindEvent(el, eventName, eventHandler) 
{
  if (el.addEventListener)
  {
    el.addEventListener(eventName, eventHandler, false); 
  } 
  else if (el.attachEvent)
  {
    el.attachEvent('on'+eventName, eventHandler);
  }
}

So through my custom handler I am doing something like this:

    function onAreaClick(e)
    {
             //my custom code here

        e.cancelBubble = true;
        if(e.stopPropagation) 
               e.stopPropagation();

        return false;
    }

    //...
    //assume looping through all areas of the imagemap here, with each element referred to by the variable area
    bindEvent(area, 'click', onAreaClick);

The onAreaClick function in fact triggers OK, however I can't get the event to stop propagating. I tried cancelBubble, stopPropagation, and return false, but the link is still followed through. I also tried to change the phase from bubbling to capturing in the addEventListener() function call in bindEvent().

How can I stop this event from triggering the default action of the image map?


Solution

  • OK, so after some more experimentation I seem to got it working on all browsers without JS errors (or so it seems).

    I created a function that stops the default handler, and I called it with the event as argument. This function looks like this:

    function stopDefaultHandler(e) 
    { 
        if (e)
        {
          e.cancelBubble = true;
          e.returnValue = false;
    
          if (e.stopPropagation)
            e.stopPropagation;
    
          if (e.preventDefault) 
           e.preventDefault();
        }
    
        if (window.event && window.event.returnValue)
           window.eventReturnValue = false;
    }
    

    It seems to work OK, but comments appreciated.