javascript - Set focus to end of string in div -


i have div attribute contenteditable , want cut content that's input , longer e.g. 5 chars. focus set start of input time...

var maxlength = 5;  $(".test").attr("contenteditable", function(){      $(this).on('keyup', function( e ){          if( $(this).html().length > (maxlength)){              var content = $(this).html();                  content = content.substring(0,(maxlength));              $(this).html(content).focus();          }      });      return true;  });
div{      width: 100px;      height: 20px;      background: red;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div class="test"></div>

how can set cursor end of div content?

i found samples here in did not work construct.

i have tried .focus() , .blur() before , cleared content... no results...

of course don't want install plugin...

my solution:

$('.test').attr('contenteditable', function() {    $(this).on('keypress', function(e) {      var len = $(this).attr('maxlength');      if ($(this).html().length >= len) {        e.preventdefault();      }    });    return true;  });
div {    background: red;  }  .small {    width: 42px;  }  .medium {    width: 82px;  }  .large {    width: 122px;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  maxlength 5:  <div class="test small" maxlength="5"></div>  maxlength 10:  <div class="test medium" maxlength="10"></div>  maxlength 15:  <div class="test large" maxlength="15"></div>

thx @cmbuckley. brought me new thinking :d

no focus needed because focus never lost , chars can deleted easy.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -