0

I'm trying to replicate this 'onclickout simulator' script as seen here:

http://jsfiddle.net/C9CL3/

As you can see, it works fine (in all of the browsers I've tested it in - so this isn't a browser compatibility issue as far as I'm aware).

The code in my solution reads as follows:

document.getElementById('bigBtn').onclick = function(event) {
        alert('button clicked');
        if (event.cancelBubble) //THIS LINE GIVES 'EVENT IS UNDEFINED' ERROR
            event.cancelBubble = true;
        else
            event.stopPropagation();
    }

This is found in pageLoad().

As you can see, I'm getting an unexpected error from the event.cancelBubble line as event is undefined. I can't for the life of me work out why.

NOTE: I am testing cancelBubble in this way differently from the fiddle demo for browser compatibility reasons.

Thanks a lot for any help, really stuck on this.

  • 1
    Well you say it's not a browser issue, but, event will be undefined in earlier version of IE (as they use window.event) instead. So you can always try adding this at the top of the handler. if (!event) event = window.event; – GillesC Apr 27 '12 at 11:10
  • In your fiddle link, `event.cancelBubble` is `false` which means that `event` is not `undefined` – Anji Apr 27 '12 at 11:12
  • @Anji - yes, that is expected - like I said - the fiddle link works, but in my solution it doesn't. –  Apr 27 '12 at 12:12
  • @gillesc - "Microsoft JScript runtime error: Object doesn't support property or method 'stopPropagation'" –  Apr 27 '12 at 12:20
  • In IE you need to use window.event.cancelBubble = false; instead of stopPropagation. here is a good source for event issue cross browser http://www.quirksmode.org/js/events_order.html – GillesC Apr 27 '12 at 12:36
  • @gillesc - the problem is that it didn't recognise cancelBubble - see error I posted above. –  Apr 27 '12 at 12:45

2 Answers2

2

Try using the DOM2 events model. Instead, use the following approach to registering the handler:

document.getElementById('bigBtn').addEventListener("click", yourFunction, false);
Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
  • Microsoft JScript runtime error: Object doesn't support property or method 'addEventListener' –  Apr 27 '12 at 12:17
  • This is a JavaScript-related question, not a JScript one... :) Which IE version? Prior to IE 9, you have to use [attachEvent](https://developer.mozilla.org/en/DOM/element.addEventListener#Legacy_Internet_Explorer_and_attachEvent). – Alexander Pavlov Apr 27 '12 at 12:24
  • Thanks for your reply mate. IE9. This really has stumped me, not a clue why this isn't working. –  Apr 27 '12 at 12:30
0

Problem solved. Instead of 'simulating' an onclickout event in this way, I simply set focus (using window.hash) to the menu that was to appear in place of that 'button clicked' alert and then handled the onblur event to close it.