1

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>.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
slacy
  • 11,397
  • 8
  • 56
  • 61

2 Answers2

0

If you got here from google this is probably what you want: handle onmousedown instead of onclick. It's written in the post but if you're a lazy reader like me, you skimmed and missed it.

amwinter
  • 3,121
  • 2
  • 27
  • 25
0

The quick and dirty solution is to use wrap() -

$('span.paste').wrap('<a class="paste" />');

and then you can try to attach your click event to an <a> tag, which works (as you mentioned)

Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
  • Yeah, but the element I'm trying to attach this behavior to doesn't have a nice selector I can use. (and I don't really want to be mucking with my DOM via jQuery like this with every page load) – slacy Jan 03 '12 at 20:52