I want to attach an event handler to a <span>
node that processes the current selection, but before the click event fires, it appears as though the selection is cleared by the browser (Chrome 16.0.912.63).
I can work around this in a slightly messy way by attaching a handler to onmousedown
, but I'd rather not have to do it that way.
Here's a brief HTML example that illustrates the problem (requires jQuery):
<span class="paste">PASTE</span>
<textarea id="selected"></textarea>
<script type="text/javascript">
$('.paste').click(function(e) {
var txt = window.getSelection(); // works only in Chrome, Safari, FF
$('#selected').val(txt);
e.stopPropagation();
});
</script>
The desired behavior is that I'm able to select some text using the mouse, then click on the word "PASTE" to have the contents of the selected area inserted into the textarea. It appears as though the selection is cleared before the click handler fires. This code works just fine if I use:
<a class="paste" href="#">PASTE</a>
instead of a span element, or if I bind onmousedown
, but I'm not in control over the elements, so I can't just use an <a>
instead of a <span>
.