How to get cursor coordinates in a textarea and display a div below the cursor

0

I have a code that I want to improve, currently writing an arroba in a textarea displays a list of registered people to add mentions. That list opens on a div below the textarea. Desire is to obtain the cursor coordinates within the textarea and display the floating list below the cursor. What options can you give me?

I want to show a small list of users within textarea to do something like @mentions in javascript or jquery without adding another plugin ... What do you recommend?

<html>
<textarea id="pcomment" ></textarea>
<div id="menciones"></div>


<script>
var ini_arrob=-1;
var fin_arrob=0;
$(document).ready(function() {
    $('#pcomment').on('keyup', function() { 
        var editor = $("#pcomment");
        var key = $(this).val();    
        var start = editor.get(0).selectionStart;

        if(key.substring(start, start-1)=="@"){
            ini_arrob=start-1;
        }
        if(key.substring(start, start-1)==" "){
            ini_arrob=-1;
        }
        $('#menciones').fadeOut(100);
if(ini_arrob>-1){

        var arroba = key.substring(ini_arrob, start);
        var cont1 = key.substring(0 , ini_arrob);
        var cont2 = key.substring(start , key.length);
        var dataString = 'key='+ arroba;

    $.ajax({
            type: "POST",
            url: "/getmentions.php",
            data: dataString,
            success: function(data) {

                $('#menciones').fadeIn(100).html(data);

                $('.suggest-element').on('click', function(){

                        var id = $(this).attr('id');

                        var comentario = $("#pcomment").val();
                        var mention = $('#'+id).attr('data')
                        $("#pcomment").val(cont1 + mention +" "+ cont2);
                        $("#pcomment").focus();

                        $('#menciones').fadeOut(100);
                        return false;
                });
            }
        });
}
    });
}); 

</script>

</html>
    
asked by CRUZ VARGAS 27.12.2018 в 15:14
source

0 answers