Search code examples
javascriptjqueryhtmlcsslive-preview

Selecting a particular location inside a Text Input Box with jQuery


I am experimenting with live preview of text inputs.

At the moment, users can preview their text as they type and can also select the input field by clicking on the live preview text. What I would like to do is allow users to click on the live preview text and have the cursor in the text field appear in the exact same location in the text as where they clicked on in the preview. (Any solution must work with multiple input fields.)

Previous posts show how to highlight a range or a particular word (see below), but I couldn't find any Javascript/JQuery for what I am trying to do. Any advice would be helpful!

Related Stack Overflow Question: Selecting Part of String inside an Input Box with jQuery

$( document ).ready(function() {
  $('.liveInput').keyup(function(){
    var $this = $(this);
    $('.'+$this.attr('id')+'').html($this.val());
  });

  $('.description').click(function(){
    $('#description').focus();
  });

  $(".description").hover(function () {
    $(this).toggleClass("preview-hover");
  });
});
.preview-hover {
  cursor:pointer;
  opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="description" class="liveInput" name="description" cols="80" rows="8" style="width:100%; resize:vertical;" placeholder="POST CONTENT"></textarea>				

<div>
  <p class="description"></p>                   
</div>


Solution

  • I think this is what you are looking for.

    $('.liveInput').keyup(function(){
         var $this = $(this);
         $('.'+$this.attr('id')+'').html($this.val());
    });
     
    $('.description').click(function(){
        s = window.getSelection();
             var range = s.getRangeAt(0);
             var node = s.anchorNode;
    
             $('.liveInput')[0].setSelectionRange(range.startOffset, range.startOffset);
    
     });
     
    $(".description").hover(function () {
         $(this).toggleClass("preview-hover");
    });
    .preview-hover {
         cursor:text;
         opacity: 0.5;
     }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <textarea id="description" class="liveInput" name="description" cols="80" rows="8" style="width:100%; resize:vertical;" placeholder="POST CONTENT"></textarea>				
    
    <div>
       <p class="description"></p>                   
    </div>