Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Paste Event in jQuery fires on pre-paste?

I am trying to make textbox similar to the Twitter, for this I have written code for:

  • Word Count
  • Used Events Change, Keyup and Paste

Keyup and Change Events are working fine but paste event is little bit strange, when I paste something in textarea the word count doesn't change at that moment, after some debugging I found that paste event fires up before pasting something on textbox. I don't know how they handle this in Twitter.

Here is my code:
events:

'click #textboxId'  : 'submitQuestion'
'keyup #textboxId'  : 'wordCounter'
'change #textboxId' : 'wordCounter'
'paste #textboxId'  : 'wordCounter'

wordCounter: ->  
  #Code for Word Count#  

Due to pre-paste nature of paste event the work count doesn't changes on that instance.

Your suggestion and help will be appreciated.

like image 582
Arpit Rawat Avatar asked Dec 19 '11 06:12

Arpit Rawat


2 Answers

See this example.

http://jsfiddle.net/urEhK/1

$('textarea').bind('input propertychange', function() {
    $('#output').html($(this).val().length + ' characters');
});

That behavior was very weird. You would think that one of those events would catch this properly? I was surprised there weren't more answers to this via Google.

like image 129
mrtsherman Avatar answered Oct 10 '22 09:10

mrtsherman


   function update()    
   {
       alert($textbox.val().length);
   }


    var $textbox = $('input');
    $textbox.bind('keyup change cut paste', function(){
        update(); //code to count or do something else
    });
    // And this line is to catch the browser paste event
    $textbox.bind('input paste',function(e){ setTimeout( update, 250); });  
like image 31
aWebDeveloper Avatar answered Oct 10 '22 10:10

aWebDeveloper