Macros in coordinates relative to textarea

1

I need to insert some macros into a text area, these macros can be inserted anywhere in the field, currently I only use a append that just puts the macro in the beginning.

I'm thinking of getting the coordinates of the click with clientX - ClientY and when inserting the macro to use these coordinates for insertion.

Example:

 $("#inserirMacro").click(function() {
   // Pega o macro selecionado.
   var macro = $("#macros :selected").text();
   // Inseri o macro no  começo do campo textarea
   $('#campo').append(macro);
 });

 // Pega as coordenadas do click no textArea.
 $("#campo").mousedown(function(e) {
   console.log(e.clientX + ' ClientX ' + e.clientY + ' ClientY');
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><selectid="macros">
  <option>[NOMECLIENTE]</option>
  <option>[CPF]</option>
  <option>[TELEFONE]</option>
  <option>[TELEFONE2]</option>
</select>
<button type="button" id="inserirMacro">Inserir</button>
<br>
<textarea rows="4" id="campo"></textarea>

How can I use these coordinates to insert the macros in the correct places?

    
asked by anonymous 04.11.2015 / 12:30

1 answer

1

Gabriel, I think it's best to get the cursor position in textarea .

var selection = {};
selection.Start = 0;
selection.End = 0;

var campo = $("#campo");
var inserirMacro = $("#inserirMacro");
var macros = $("#macros");

inserirMacro.click(function() {
  // Pega o macro selecionado.
  var macro = macros.children(":selected").text();
  var pre = campo.val().substring(0, selection.Start);
  var pos = campo.val().substring(selection.End);  
  campo.val(pre + macro + pos);  
  
  selection.End = selection.Start += macro.length;
  campo.prop("selectionStart", selection.Start);
  campo.prop("selectionEnd", selection.End);
  campo.focus();
});

campo.on("keyup keypress blur input", function () {
  selection.Start = campo.prop("selectionStart");
  selection.End = campo.prop("selectionEnd");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><selectid="macros">
  <option>[NOMECLIENTE]</option>
  <option>[CPF]</option>
  <option>[TELEFONE]</option>
  <option>[TELEFONE2]</option>
</select>
<button type="button" id="inserirMacro">Inserir</button>
<br>
<textarea rows="4" id="campo"></textarea>

In this case the macro will be inserted in the textarea region that the user was working on.

    
18.02.2016 / 20:04