3

I'm trying to get an event to fire whenever a contenteditable div is changed using keyup. Unfortunately it's also catching things like moving the caret with the arrow keys. I only want it to spot actual changes though.

I read this question, which seems similar, but the solution on there doesn't work for things like linebreaks. Ideas?

Community
  • 1
  • 1
Stephen Belanger
  • 6,251
  • 11
  • 45
  • 49

1 Answers1

2

One way would be to cache the length outside the handler then compare the current length of the textarea against your cached length. If they differ then you can assume the key that was pressed added content to the textarea. Hope this helps.

var textarea = $('textarea').get(0),
    length = $(textarea).val().length;

$(textarea).keyup(function() {
   if($(this).val().length != length) {

     //do something


     //cache new length
     length = $(this).val().length();
   }
});
John Strickler
  • 25,151
  • 4
  • 52
  • 68