-3

I have a DIV field which contains some lyrics. I want to know when user is dragged & selected some part of the lyrics. How is this can be done? Example is shown below:

image

In this example user is dragged & selected the part which has a blue background. I want JavaScript to select "I can't believe that my sanity lies in abandoning you" part of the text. Is this possible to do?

Community
  • 1
  • 1
Emre Aydin
  • 569
  • 2
  • 16

3 Answers3

4

I think this one is what you want:

if (!window.x) {
  x = {};
}

x.Selector = {};
x.Selector.getSelected = function() {
  var t = '';
  if (window.getSelection) {
    t = window.getSelection();
  } else if (document.getSelection) {
    t = document.getSelection();
  } else if (document.selection) {
    t = document.selection.createRange().text;
  }
  return t;
}

$('#html1').ready(function() {
  $(document).bind("mouseup", function() {
    var mytext = x.Selector.getSelected();
    alert(mytext);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="html1">They kill me for waiting you. I can't recall a more bla bla bla bla

</div>

http://jsfiddle.net/0mqo0zhk/

Giannis Grivas
  • 3,374
  • 1
  • 18
  • 38
2

Reference: How to get selected text with JavaScript

This is already answered and it has worked for me as well. I've shared the answer as well as the link. Hope it helps you as well.

function GetSelectedText () {
if (window.getSelection) {  // all browsers, except IE before version 9
    var range = window.getSelection ();
    alert (range.toString ());
} 
else {
    if (document.selection.createRange) { // Internet Explorer
        var range = document.selection.createRange ();
        alert (range.text);
    }
}
}

var butn = document.getElementById("soda");
butn.onclick = function(){
    GetSelectedText();
}
Community
  • 1
  • 1
Rupam Datta
  • 1,849
  • 1
  • 21
  • 36
  • 1
    I don't care about the older versions of IE. Actually I don't care about IE itself. I want my website to work on real browsers like Chrome, Safari and other browsers that use Chromium core. – Emre Aydin Nov 25 '14 at 17:59
0
window.getSelection().toString()