JavaScript content count is unreliable with attachEvent for keypress/onclick

  •  03-09-2006, 1:31 AM

    JavaScript content count is unreliable with attachEvent for keypress/onclick

    I have a user control that contains 3 editors for which I need to update a count of the chars (including the tags), but the events only sometimes bubble.  On load 7/8's of the time the characters remaining will be 0 even though there is text in the CE control.  Clicking or typing in the CE does not cause updates.  Refresh the page a few times and the count will show correctly and be updated via responses to the events.  Refresh again at they are back to 0.
     
    Adam, I've viewed the samples and I think you need to try testing it with the event attachment occuring onload vs. the button.  It appears the onload code is running before the CE control is fully rendered and setup.
     
    <script language="javascript">
          // get the cute editor instance
          var editor1 = document.getElementById('<%=RemarksEditor.ClientID%>');
       function CE_attachEvent()
       {
        // get the cute editor instance
        if(editor1.attachEvent)
         editor1.attachEvent('onclick',CountWords);
        else if(editdoc.addEventListener)
         editor1.addEventListener('onclick',CountWords,true);
       
        //Get the editor content 
        var editdoc=editor1.GetDocument();
        // attach Event
        if(editdoc.attachEvent)
         editdoc.attachEvent('onkeypress',CountWords);
        else if(editdoc.addEventListener)
         editdoc.addEventListener('keypress',CountWords,true);
        
         CountWords();
       }  
      
       function CE_detachEvent()
       {
        // get the cute editor instance
        //var editor1 = document.getElementById('<%=RemarksEditor.ClientID%>');
       
        //Get the editor content 
        var editdoc=editor1.GetDocument();
        // detach Event
        if(editdoc.detachEvent)
         editdoc.detachEvent('onkeypress',CountWords);
        else if(editdoc.removeEventListener)
         editdoc.removeEventListener('keypress',CountWords,true);
       }
         
        //as page loads, attach it:
        //tried to do this with Page.RegisterStartupScript, but it also, only sometimes works
        //with this inline version, it works 1 of 8 times.
       CE_attachEvent();
       
       
          function CountWords()
          {
                // get the cute editor instance
                document.getElementById('RemarksEditorCount').innerHTML = 'Character Count = ' + editor1.getHTML().length;
          }
    </script>
View Complete Thread