Add class with a span when there is @ / #

1

On Twitter or Facebook, when we type a hashtag the background of the text will turn blue, as in the image below

I'mtryingtodothisinjsusing.keyup()inadiv[contenteditable=true],I'mdoingwithPHPpassingthetextbyjQueryandreturningthetextifthereis@andaddingaclassandaspan.Itworks,butalwaysitreturnsthetexttothecursortextthatisindiv[contenteditable=true]italwaysreturnstothebeginning(leftside)oftheDIVandwhenIstartthetext(rightside)editbutreturnstothebeginningthecursor(leftside)again.

IknowtheremaybeanothermethodI'vealreadyfishedandIdonotfindanythinglikeit.

jQuerycode:

$(document).ready(function(){$("#text_publica").keyup(function(){
            var text = $("#text_publica").text();
            var dataString = 'nome='+text;
            $.ajax({
                type: 'post',
                url: 'pages/validate_nm.php',
                data: dataString,
                cache: false,
                success: function(data){
                    $("#text_publica").html(data);
                    $("#text_publica").focus();
                }
            });
        });
    });

PHP code:

<?php
    session_start();
    include('main_bd.php');
    include 'data.class.php';


    if(isset($_POST['nome'])){
        $txt = $_POST['nome'];
        $txt = preg_replace('/\B@([\d\w_]+)/i', '<span class="tag">$0</span>', $txt);
        echo $txt;
    }
?>

I came to an interest in doing so I had this idea in doing with jQuery + PHP I am not an expert in this area of js more I turn when it is necessary. In this case I need your help, if you know how to do otherwise or make the cursor text always stay ahead of the last character at the end of the text is already a start.

    
asked by anonymous 11.07.2016 / 13:32

1 answer

1

You will have to memorize the start position of the selection in the text, then modify the HTML and then move the text selection cart to the old position.

To get the position of the cart it will require the selectionStart property on the element (it does not exist in IE

11.07.2016 / 14:22