Jquery - custom maxlength function

Hello experts.
I'm trying to add a maxlength function to a editable div.
There is a problem with my code. I want to prevent to be able to write more than the max characters.
In my code f.e. it is adding the new character at the beginning that is not i want.
also i want to delete all characters that are above the maxlength.
I have in mind this function: https://stjerneman.com/portfolio/maxlength-jquery
but for a div
Any help?
http://jsfiddle.net/panosms/xexzsuam/

css:
.error{ color:red;}
.valid{color:green}
.jqte_editor{width:200px;height:100px;border:  1px solid #aaaaaa;}
html:
<div class="jqte_editor" contenteditable="true">
</div>
<div id="counter"><span></span></div>
js:
$(".jqte_editor").keypress(function() {
      var max = 20;
	  var a = $(".jqte_editor");
	  var loadlength = a.text().length;
	  if (loadlength > max) {
		   a.text(a.text().substr(0, max))
		   var loadlength = a.text().length;
		   a.removeClass('valid').addClass('error');
      }else{
		  a.removeClass('error').addClass('valid');
		  }
		  
      var lengthleft =  parseFloat(max) -  parseFloat(loadlength);
      $('div#counter span').html(lengthleft + ' Characters left of ' + max);

});

Open in new window

LVL 2
PanosAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Rainer JeschorCommented:
Hi,
you have to use another Javascript function to place the caret/cursor at the end.

From this excellent GIT source:
https://gist.github.com/al3x-edge/1010364

function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    { 
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}

Open in new window

Usage:
setEndOfContenteditable(element);

Open in new window

If like in your case element is a jQuery object then please use this:
setEndOfContenteditable(a.get(0));

Open in new window


And here a live sample:
http://jsfiddle.net/EE_RainerJ/8o9d95o9/

HTH
Rainer

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
PanosAuthor Commented:
Hi Rainer Jeschor
Thank you very much. It is working perfect.
Testing the code i realized that i need a new function or edit this one if for example i'm copy a large text and want to paste it in the div. The script is working after pressing a key.
Have any idea how to solve this ?
PanosAuthor Commented:
Hi again
I did play a little with the jquery paste function
It needs a little setTimeout to work
The problem is that for a large text the pasted text is visible for a short of time
I will post a new question for this case.
Thank you very much for your help
$(".jqte_editor").on('paste', function () {
	  var max = 20;
	  var a = $(this);
	  setTimeout(function () {
	  var loadlength = a.text().length;
	  if (loadlength > max) {
		   a.text(a.text().substr(0, max));
           setEndOfContenteditable(a.get(0));
		   var loadlength = a.text().length;
		   a.removeClass('valid').addClass('error');
      }else{
		  a.removeClass('error').addClass('valid');
		  } 
      var lengthleft =  parseFloat(max) -  parseFloat(loadlength);
      $('div#counter span').html(lengthleft + ' Characters left of ' + max);
	  })
     }
	);

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.