Search code examples
javascriptfocusprepend

Set focus between prepend and value


Scenario: A button should prepend dynamic text to a text area that contains value already, then set focus after the text that is added. I cannot succeed in adding focus after between prepended text and previous value..

$('#workLogBtn').click(function(){
    // $('textarea[id^="Oppgaver_"]').prepend(timeSignature).focus();

    $('textarea[id^="Oppgaver_"]').val(function(i, text) {
        return timeSignature + text;
    });

    $('#workLogBtn').hide().fadeOut( 1000 );
    $('textarea[id^="Oppgaver_"]').css('margin-top', '63px');
    return false;
  });

I have tried both prepend and val(), but it only places focus at the end of the textarea, not after the text is added.

$('#workLogBtn').click(function(){
    $('textarea[id^="Oppgaver_"]').prepend(currenttimeStamp + ', ' +  timeStamp.getHoursTwoDigits() + ':' + timeStamp.getMinutesTwoDigits() + ' - '  + signedByUser + ':' + '\r\r\r');
    $('#workLogBtn').hide();
    $('textarea[id^="Oppgaver_"]').css('margin-top', '36px');
    return false;
  });

Fiddle

The solution below works. But when i add it to the SharePoint site it acts a bit unnatural as to where it places the caret. I cant understand where the count starts. The -3 matters, but if i write -0 it still ends up in the middle of the text.

Illustration


Solution

  • Add these two functions:

    function setSelectionRange(input, selectionStart, selectionEnd) {
      if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
      } else if (input.createTextRange) {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', selectionEnd);
            range.moveStart('character', selectionStart);
            range.select();
      }
    }
    
    function setCaretToPos(input, pos) {
      setSelectionRange(input, pos, pos);
    }
    

    and modify your click handler as follows:

    $('#workLogBtn').click(function(){
        var newString=currenttimeStamp + ', ' +  timeStamp.getHoursTwoDigits() + ':' + timeStamp.getMinutesTwoDigits() + ' - '  + signedByUser + ':' + '\r\r\r';  $('textarea[id^="Oppgaver_"]').prepend(newString);
        $('#workLogBtn').hide();
        $('textarea[id^="Oppgaver_"]').css('margin-top', '36px');
        setCaretToPos($('textarea[id^="Oppgaver_"]')[0], newString.length-1)
        return false;
      });
    

    Here is a snippet:

    $(document).ready(function(){
    
    // CSS:ADD
    $('textarea[id^="Oppgaver_"]').css("width", "800px");
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    // USER:GET
         var signedInUser = document.getElementById('zz5_Menu').innerHTML;   
         var end = signedInUser.indexOf('<'); 
         var signedByUser = signedInUser.substring();
    
    // DATE:FORMAT
        Date.prototype.getHoursTwoDigits = function(){var retval = this.getHours();if (retval < 10){return ("0" + retval.toString());}else{return retval.toString();}}
        Date.prototype.getMinutesTwoDigits = function(){var retval = this.getMinutes();if (retval < 10){return ("0" + retval.toString());}else{return retval.toString();}}
        var timeStamp = new Date();
        function pad(n) {return n < 10 ? "0"+n : n;}
        var currenttimeStamp = [pad(timeStamp.getDate()), pad(timeStamp.getMonth()+1), timeStamp.getFullYear()].join('.'); 
        var timeSignature = currenttimeStamp + ', ' +  timeStamp.getHoursTwoDigits() + ':' + timeStamp.getMinutesTwoDigits() + ' - '  + signedByUser + ':' + '\r\r\r';
    
    // BUTTON:PREPEND
        $('textarea[id^="Oppgaver_"]').before( '<p><button id="workLogBtn">Signer</button></p>' );
    
    // BUTTON:ACTION
        function setSelectionRange(input, selectionStart, selectionEnd) {
          if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(selectionStart, selectionEnd);
          } else if (input.createTextRange) {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', selectionEnd);
            range.moveStart('character', selectionStart);
            range.select();
          }
        }
        
        function setCaretToPos(input, pos) {
          setSelectionRange(input, pos, pos);
        }
    
        $('#workLogBtn').click(function(){
          var newString=currenttimeStamp + ', ' +  timeStamp.getHoursTwoDigits() + ':' + timeStamp.getMinutesTwoDigits() + ' - '  + signedByUser + ':' + '\r\r\r';  $('textarea[id^="Oppgaver_"]').prepend(newString);
            $('#workLogBtn').hide();
            $('textarea[id^="Oppgaver_"]').css('margin-top', '36px');
            setCaretToPos($('textarea[id^="Oppgaver_"]')[0], newString.length-3)
            return false;
          });
    
    });
    textarea {width:600px;height:600px;border:0px;border-radius:4px;padding:20px;margin:0 0 0 20px;color:#444;}
    
    #workLogBtn, #workLogBtn:visited {padding:4px 10px;text-decoration:none;margin:10px 20px; background:green;color:#fff;border-radius:4px;display:inline-block;border:0px;}
    #workLogBtn:hover {color:#444;background:#fff;}
    #zz5_Menu {display:none;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
    <a id="zz5_Menu">Eliassen, John-Eilif</a>
    
    <textarea id="Oppgaver_f3cf5190-9ce6-459b-808c-4a832ee9a559_$TextField">
    17.03.2017, 10:37 - Eliassen, John-Eilif:
    Oppgradering fra v 6.20.3185 til 6.20.3215
    
    17.03.2017, 10:37 - Eliassen, John-Eilif:
    Oppgradering fra v 6.20.3185 til 6.20.3215
    </textarea>