views:

411

answers:

0

I have a page defining a link ('a' tag) and some onclick events associated with it.
I am trying to add an arbitrary HTML element (in this case a div) with the ability to respond to click events by firing the click events of the link.
The code below describes all that.

The end goal is to trigger exactly the same actions whether the click was on the link or on the div without modifying the link or its onclick events.

My problem is that browsers don't respond in a consistent way when the div is clicked:

-Google Chrome fires all 3 events and then follows the link href,
-Firefox and IE fire the 3 events but do not follow the link href. In that case I can just add "window.location = link.href" to the div onclick handler.

Is it possible to make all browsers work the same way, whether it is the 1st or 2nd case ?
If it is not possible, do you have any suggestion that doesn't require modifying the link onclick events (event.stop()) or testing for the browser engine (if (not chrome) { window.location = link.href })?

Edit: Safari works the same way as Chrome, so I suppose this is a webkit issue.

<!DOCTYPE  HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; 
<html lang="en"> 
  <head> 
    <title>test</title>
    <META http-equiv=Content-Type content="text/html; charset=utf-8"> 
    <script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt; 
    <script type="text/javascript">google.load("prototype", "1.6.1.0");</script>
  </head>
  <body> 
    <div>
       <a id="google_link" href="http://google.com" target="_blank">click to go to google</a>
    </div>
    <div id="google_link_proxy">click here to do the same as the link above</div>

    <script type="text/javascript">
      function fireEvent(element,event) {
        if (document.createEvent) {
            // dispatch for firefox + others
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent(event, true, true ); // event type,bubbling,cancelable
            return !element.dispatchEvent(evt);
        } else {
            // dispatch for IE
            var evt = document.createEventObject();
            return element.fireEvent('on'+event,evt)
        }
      }

      $("google_link").observe("click", function(){alert("action 1");});
      $("google_link").observe("click", function(){alert("action 2");});
      $("google_link").observe("click", function(){alert("action 3");});

      $("google_link_proxy").observe("click", function(event){
         fireEvent($("google_link"), "click");
      });
    </script>
  </body>
</html>