pavneet tiwana pavneet tiwana - 1 year ago 58
jQuery Question

Find out if a selected text is inside a input field or textarea

I am creating a chrome extension.

Whenever you select a text I add two buttons to the webpage adjacent to the selection.

In case the selection is inside a textarea or Input box, i don't want any action to take place.

Here is the code i am using currently

$(document).on("mouseup", function(e) {
if(class1=="INPUT" || class1=="TEXTAREA"){
var selectedtext=window.getSelection().toString();
var chars=selectedtext.length;
var posx=e.clientX;
var posy=e.clientY;
var scrollDepth=$(window).scrollTop();
var location=findSelectionCoords(posx,posy);

Create button function is used to create the buttons.

If the user selects some text inside the text area/input box this function works, the console shows input/textarea.
But sometimes the textarea or input box gets selected also and then this function fails. In the class1, I get DiV in this case.

Can some one suggest a function that will work in all cases and detect if a text selection is inside a input or text area

Thanks in advance

Answer Source

Here is the sample code, in which the alert message is shown only if the mouseup event came from element that is not textarea or input of type text.


$(function() {
    var isInputOrTextarea = false;
	$(document).on("mousedown", function(e) {
        // On mousedown flag whether it was clicked in input or textarea
        if($("textarea,input[type=text]")) {
            isInputOrTextarea = true;
	$(document).on("mouseup", function(e) {
        if($("textarea,input[type=text]") || isInputOrTextarea) {
            isInputOrTextarea = false;
        isInputOrTextarea = false;
        alert("Not in text area or input");
<script src=""></script>
<input type="text" value="Lorem ipsum"/>
    Lorem ipsum
    Lorem ipsum