Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery user screen selection

I am working on a script that takes a users on screen selection (when they physically highlight text in the browser) and is supposed to manipulate that text.

This is what I am trying to do.

Take the selected text, search for the selected text in an original string and then wrap the text that is found in the original string with a certain HTML tag (<b>, <span>, <a>)

I am using the jQuery.textselect plugin.

The part I can't figure out is how to manipulate the original text once the user selection has been found.

Example: If this text is shown on the screen: "HELLO WORLD"

The original text is HELLO WORLD, the user selects HELLO, then the script searches through the original text for the user selection and will wrap HELLO with <b> tags and then output the new original text... make sense?

Sorry for the confusion and thanks for the help!

like image 276
dennismonsewicz Avatar asked Nov 06 '22 07:11

dennismonsewicz


1 Answers

This is the closest I could get. It's not ideal for a few reasons (if you highlight Hello, it will highlight ALL the hellos). The text select plugin isn't particularly standardized, and I couldn't identify a way to know WHERE in the text, besides pixel positioning, the event was taking place, since the e variable is an event object, rather than a $(this)-style DOM element.

$(function() {
  $(document).bind('textselect', function(e) {
        $('body').html($('body').html().replace(e.text,"<b>"+e.text+"</b>"));
    });
});

jQuery isn't quite ideally suited for this, as it tends to cater to manipulation of DOM elements, rather than text manipulation.

EDIT: A more precise option, but that limits you to having this effect for a single DOM element:

$(function() {
  $(document).bind('textselect', function(e) {
      var $this = $(e.target);
      $this.html($this.html().replace(e.text,"<b>"+e.text+"</b>"));
    });
});

This is an excellent question.

like image 193
Yahel Avatar answered Nov 09 '22 03:11

Yahel