1

is it possible to throw the jquery-select() event on a text which is inside a div element? here is my example but it doesnt work.

<div id='id1'>Hello text</div>
$("#id1").select( function () { 
  alert("something was selected");
});

My goal is to select a word in a text and to put this selected word in an URL and to open a new window with this url. For example i mark or rather i select the word hello, the word hello should apear in this url

window.open('http://dict.leo.org/ende?lp=ende&lang=de&searchLoc=0&cmpType=relaxed&sectHdr=on&spellToler=&search=Hello');

i am not sure if the select-event is the right way. please help. sorry for my bad english!

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Pero
  • 774
  • 3
  • 15
  • 34
  • Check this question out: http://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse – Gabe Jan 12 '12 at 22:02

2 Answers2

3

Translate a selected (highlighted) text portion

jsBin demo

function getSelRange() {
  var notIE8 = window.getSelection;
  var rng = notIE8 ? window.getSelection() : document.selection.createRange().htmlText;
  return $.trim(rng);
}

$('#id1').mouseup(function() {
  var selRange = getSelRange(); // THE HIGHLIGHTED TEXT PORTION
  if(selRange) window.open('https://translate.google.com/#en/de/'+ selRange); // TRANSLATE
});
<div id='id1'>
  Please highlight a text range you want to translate.
  Translating text is really cool. You should try it!
</div>

NB: notIE8 means lower than or equal to IE8 ;)

P.S: If you don't use jQuery and you need to support older browsers, than make sure to use onclick function and a Polyfill for .trim();
otherwise use JS's addEventListener() and String.prototype.trim() as usual.

Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
2

No, jQuery.select() is limited to text input fields and textareas.

javascript has some varied options:

if (window.getSelection) {
    txt = window.getSelection();
} else if (document.getSelection) {
    txt = document.getSelection();
} else if (document.selection) {
    txt = document.selection.createRange().text;
} else return;
alert(txt);

But you would have to bind that to some kind of listener event. Most applications use a right click menu or something.

Scottux
  • 1,577
  • 1
  • 11
  • 22