Silver Light
Silver Light

Reputation: 45902

Jquery: run code when text is selected

I have a HTML document which llokes like this:

<div class="this_can_be_selected">Some text here</div>
<div>No text in the div above is selected</div>

<div class="this_can_be_selected">Some text here</div>
<div>No text in the div above is selected</div>

<div class="this_can_be_selected">Some text here</div>
<div>No text in the div above is selected</div>

I want text No text in the div above is selected to be changed to Some text in the div above is selected when, guess what, some of the text in the div above is selected :)

jQuery has a .select() event, that would make this rather easy to do, but seems, that it works when selected text is inside input or textarea.

Here is a code that I've tried:

$(document).ready(function()
    {

        //Some text inside div is selected
        $('DIV.this_can_be_selected').select
        (
            function()
            {
                alert('Something is selected!');
                $(this).next().html('Some text in the div above is selected');
            }
        );

    }
);

Nothing is happening.

Is there a way to solve this problem?

Upvotes: 1

Views: 210

Answers (1)

Nick Craver
Nick Craver

Reputation: 630369

jQuery core doesn't have anything for this, but there are some plugin options.

Your code would look like this:

$(function() {
  $(document).bind('textselect', function(e) {
    alert('Selected Text: ' + e.text);
  });    
});

You can test it out here.

Upvotes: 4

Related Questions