-2

I am trying to alert some message when every I select text (::selection) in a div. Can someone please give me some pointers

Also can I change the css of ::selection ? This doesn't seem to work.

$('::selection').css({.....

VMN
  • 181
  • 1
  • 2
  • 14
  • 1
    This should help you out. http://stackoverflow.com/questions/3545018/selected-text-event-trigger-in-javascript – Shriike Oct 17 '14 at 19:39

1 Answers1

0

Here's a JSFiddle example of doing just that with jQuery: http://jsfiddle.net/Lvx6bvth/1/

(function (window, document, $) {
    var getSelectedText = function () {
        var text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        return text;
    };

    $(document.body).on("mouseup", function () {
        var selectedText = getSelectedText();
        if (selectedText.length !== 0) {
            alert("You selected: " + selectedText);   
        }
    });
})(window, document, jQuery);

Of course, you can delegate this to specific selectors so it only works on your targeted divs.

Function referenced from Get the Highlighted/Selected text

Community
  • 1
  • 1
Tristan Lee
  • 1,210
  • 10
  • 17
  • Please mark if this has answered your question, or if you need more clarification before it's answered. – Tristan Lee Oct 17 '14 at 20:08
  • Will using the `selection` rule in your style not suffice? `div::selection { background: red; }` http://www.w3schools.com/cssref/sel_selection.asp – Tristan Lee Oct 17 '14 at 20:15
  • $('div::selection').alert('hi'); I was hoping for something like this to work. It would have been much simpler. – VMN Oct 17 '14 at 20:27
  • Unfortunately, there is no DOM event to trigger a selection like that which is why I provided the example of detecting `mouseup` events on the body, and checking to see if any text is selected. – Tristan Lee Oct 18 '14 at 22:18