Is there a javascript function that marks a selected random text with the mouse?

Asked

Viewed 841 times

0

Hello, do you know if it is possible to create a text marker, similar to those used in pdf, but in an html? Not necessarily would he need to save the markings, but saving would be better.

Thanks!

  • would be that?

  • How do you mark the text? It would be something like this: https://www.w3schools.com/html/tryit.asp?filename=tryhtml_formatting_mark ?

  • Hello! This way I can too. It’s just that I thought it would be a lot of work if I had to mark all words with tags and then do a javascript function to mark them as selected. So I was wondering if it was possible to select an excerpt from a "p" tag, for example.

3 answers

3

From what I understand, it would be something related to that?

var textMark = null;
var textStart = 0;
var textStop = 0;

function getSelectionText() {
    var text = "";
    var select = null;
    if (window.getSelection){
        select = window.getSelection();
        text = select.toString();
        textMark = select.anchorNode.textContent;
        textStart = select.anchorOffset;
        textStop = select.focusOffset;
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

function mark(elements){
    var textSelected = getSelectionText();
    if(textSelected.length > 0){
        for(var i in elements){
            var element     = elements[i];
            var html        = element.innerHTML;
            var htmlParts   = html.split(/(?=(?:<\/?mark>))/);
            var htmlPartsClear  = [];
            var divClear = document.createElement('div');
            for(var i in htmlParts){
                divClear.innerHTML = htmlParts[i];
                htmlPartsClear.push(divClear.textContent);
            }
            var index       = htmlPartsClear.indexOf(textMark);
            var change      = htmlParts[index];
            if(change.length >= textStop){

                var lenMarks = 0;
                var matchs = change.match(/<\/?mark>/g);
                for (var i in matchs){
                    lenMarks += matchs[i].length;
                }

                var r = new RegExp('(.{'+(textStart+lenMarks)+'})(.{'+(textStop-textStart)+'})(.*)');
                change = change.replace(r, '$1<mark>$2</mark>$3');

                htmlParts[index] = change;
            }
            element.innerHTML = htmlParts.join('');
        }
    }
}

$(document).ready(function(){

    var elementsCheck = [];

    var allowMark = 0;
    var timerToMark = 0.5;
    var timer = null;

    $('p').on('mouseover', function(){
        allowMark = 1;
        elementsCheck.push(this);
    });
    $('p').on('mouseout', function(){
        allowMark = 0;
        var i = elementsCheck.indexOf(this);
        if (i > -1) {
            elementsCheck.splice(i, 1);
        }
    });

    $(document).on('mousemove', function(){
        if(allowMark){
            clearInterval(timer);
            var current = [];
            for(var i = 0; i < elementsCheck.length; i++){
                current.push(elementsCheck[i]);
            }
            timer = setTimeout(function(){
                mark(current);
            }, timerToMark*1000);
        }
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h3>Selecionar parte do texto (abaixo) e aguardar 500ms</h3>
<p>Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos. Lorem Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.</p>

Note

  • That’s the introduction, there’s a lot to do yet.
  • I did not test on all browsers, only on FF 50.
  • tested in Chrome and is Ok! + 1

  • Very cool that. There was some way to delete selections?

  • I just noticed that he Buga depending on the appointment. It seems that it will always mark the first occurrence of the letter or sequence of marked letters and can interfere even in the <mark>. Exemplo: If you score just one m in the middle of the paragraph and then a a in the middle of the paragraph, you will see that it will mark the a of <mark> and bugle.

  • @Leonfreire I’m seeing this already edited

  • Dude, perfect. I’m developing some interactive books for the public education network. I was racking my brain with this. Thank you very much.

  • @Leonfreire Now yes, this ok :D

  • @Marciodossantos, anything, make good use :D. I recommend seeing the update.

Show 2 more comments

0


Hello, I found this Javascript library searching on the web. I will now search for a way to save tags. Texthighlighter

0

By Imran Bughio Selecting text with mouse and Highlighting the same text with Multiple occurences in that div

//<![CDATA[
$(window).load(function(){


thisRespondHightlightText(".select--highlight--active");


function thisRespondHightlightText(thisDiv){
    $(thisDiv).on("mouseup", function () {
        var selectedText = getSelectionText();
        var selectedTextRegExp = new RegExp(selectedText,"g");
        var text = $(this).text().replace(selectedTextRegExp, "<span class='red'>" + selectedText + "</span>");
        $(this).html(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;
}
});//]]> 
    .red {
    color: red;
}
  
<!DOCTYPE html>

  <script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>

    
  <script type="text/javascript" src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    
    
  <link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
  
    <div class="select--highlight--active">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>

  • Interesting and fast. However, it seems that it marks all occurrences of the selected text.

  • That’s what I thought he wanted but I don’t think.

  • Understood. Even so it is a very interesting information and worth keeping. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.