Apr 15, 2010 3
Update to the Google & Safari Double Firing mouseup Issue
Yesterday, I wrote about an issue I was having with Google & Safari’s way of handling text selection & the “mouseup” event versus Firefox & IE. I installed Opera 10.51 as well to ensure I tested this on the major browsers and Opera behaved just like Firefox & IE. So this was definitely specific to Chrome & Safari (and I assume Webkit as well).
It was an odd scenario but using a closure I found a workaround. This morning I was happy to see a comment from my friend Diego Perini with an explanation of what he feels is the cause and also an alternative fix.
you have setup an on “mouseup” event so it is normal it fires each time you release the mouse button. You are filtering “mouseup” to act only if a selection exists, that’s ok. Unfortunately the difference between the browsers you mention is that in Firefox the selection is cleared as soon as the next “mousedown” while in Safari/Chrome it is cleared on “mouseup” so when fired your filtering will still find a selection active on Safari/Chrome, thus the second alert you see.
This is how you can alternatively fix that problem, just add these lines:
function clearSelectedText() { if (window.getSelection) { window.getSelection().removeAllRanges(); } else if (document.getSelection) { document.getSelection().empty(); } else { var selection = document.selection && document.selection.createRange(); if (selection.text) { selection.collapse(true); selection.select(); } } } addEvent(document, “mousedown”, clearSelectedText);Hope this help fix it and explain what happens in Safari/Chrome, I wouldn’t mark this as a bug. Have fun.
This did in fact fix it and I like it much better because it avoids the need to attach a closure to an event, which could lead to a memory leak. Thanks Diego!
While this does provide a great workaround, it still leaves unanswered the reason that Chrome & Safari (and Webkit??) behave differently than IE, Firefox & Safari. I’m not sure if the expected behavior for “mouseup” & “mousedown” when selected text is present is clearly defined in a specification but this is just another example of how lack of consensus causes web developers to jump through hurdles for no clear reason.

AIM: iamreybango
