Sameera Silva
Sameera Silva

Reputation: 453

Get textbox word on mouse pointer

I have textbox/textarea and I want get only one word with mouse pointed. then display that word in a another text box. Ex: When I over my mouse pointer on one word, it should display in another textbox/textarea (only that word).

I saw many posts with tag, but it is not possible to add in textbox/textarea Also I need to create function with mouse click,

I need mouse hover function and mouse click function both ways to get word.

See the 

Demo and update this

Upvotes: 1

Views: 423

Answers (1)

Grant Gibson
Grant Gibson

Reputation: 813

I'm not sure this will be possible with a plain textarea, but here's a way you could do it using a div with 'contenteditable' enabled.

Works quite nicely, see my jsfiddle demo (note: click outside of the editable area to re-enable highlighting after any edits).

HTML:

<div contenteditable="true" id="editor">
    <div>
        Content here.
    </div>
    <div>
        More content here.
    </div>
</div>
Current word: <span id="word"></span>

Javascript:

var wrapwords = function() {
    $('#editor > div').each(function() {
        $(this).html($(this).text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
    });

    $('#editor span').hover(
        function() { $('#word').text($(this).css('background-color','#ffff66').text()); },
        function() { $('#word').text(''); $(this).css('background-color',''); }
    );
};

$('#editor').on('focus', function() {
    $('#editor span').contents().unwrap();
});

$('#editor').on('blur', function() {
    wrapwords();
});

wrapwords();

Upvotes: 2

Related Questions