Ishita Ray
Ishita Ray

Reputation: 666

Used .select jquery but not getting any selected text

I want make one Editor. I have a content editable div. But I want to get the text which I select. But I am not getting any text. Can anyone help me..??

$(document).ready(function() {
  $(".editor").select(function() {
    console.log("dd");
  });
});
.editor {
  display: block;
  width: 100%;
  padding: 10px;
  background: #fff;
  height: 150px;
  box-sizing: border-box;
  border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="editor" contenteditable="true">Type text here...</div>

Upvotes: 0

Views: 37

Answers (2)

sbgib
sbgib

Reputation: 5838

Try like this (<textarea>):

$(document).ready(function() {
  $(".editor").select(function() {
    console.log("dd");
  });
});
.editor {
  display: block;
  width: 100%;
  padding: 10px;
  background: #fff;
  height: 150px;
  box-sizing: border-box;
  border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="editor" contenteditable="true">Type text here...</textarea>

The <div> must be changed to <textarea> for this to work:

The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes.


EDIT: If your editor needs to be a <div> (as you may wish to add formatting, for example), then you can achieve it like this:

$(document).ready(function() {
  $(".editor").on("click", function() {
    var text = getSelectionText();

    if (text) {
      console.log(text);
    };
  });
});

function getSelectionText() {
  var text = "";
  if (window.getSelection) {
    text = window.getSelection().toString();
  } else if (document.selection && document.selection.type != "Control") {
    text = document.selection.createRange().text;
  }
  return text;
}
.editor {
  display: block;
  width: 100%;
  padding: 10px;
  background: #fff;
  height: 150px;
  box-sizing: border-box;
  border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="editor" contenteditable="true">Type text here...</div>

In this version, a click event attached to the div is used to get user-selected text. If the text returned is not empty, then the user has selected that text.

Upvotes: 2

Mara Black
Mara Black

Reputation: 1751

Try to use onKeyUp event, like ContentEditable's example

$(document).ready(function() {
  $('.editor').on('keyup', function() {
    console.log("dd" + $(".editor").text());
  });
});
.editor {
  display: block;
  width: 100%;
  padding: 10px;
  background: #fff;
  height: 150px;
  box-sizing: border-box;
  border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="editor" contenteditable="true">Type text here...</div>

Upvotes: 0

Related Questions