Search code examples
jqueryeventstextareajwysiwyg

How to detect a change with jQuery to the contents of a textarea that's using jWYSIWYG plugin?


I'm using the jwysiwyg plugin on textareas in my form (jwysiwyg: https://github.com/akzhan/jwysiwyg )

I want to detect changes to any of the textareas that are in my form.

Normally, with a standard non-wysiwyg textarea, I do:

$('textarea').change(function(e){
    alert('Something changed!');
 });

This proves ineffective when jwysiwyg is being used due to jwysiwyg's DOM manipulation.

Anyone have any pointers?


Solution

  • Use this code, I've tested it with the help/example/01.basic.html and 02.full.html, I guess it will work with the others too:

    $(document).ready(function(){
    var current = $("#wysiwyg-wysiwyg-iframe").contents().find('html');
    
         function detectFn(){
              alert('Detected');
           } 
    
           var timer;
    
        current.bind({    
                    keyup: function(){
                        clearTimeout(timer);
              timer = setTimeout(detectFn, 2000)
    
                    }
        });
    
    });
    

    The sources:
    Yasir Laghari and Ghommey have the real credit of this solution.

    jQuery/JavaScript: accessing contents of an iframe

    On keypress, when stop after X seconds call function

    Explanation:

    1) The 'jwysiwyg plugin' what it does is to replace the textarea for an iframe. The text is inside a 'p' tag, another thing to consider is that this tag can not be clicked, if you click the text, what you are actually clicking is the 'iframed html' tag.

    2) For jQuery to access and select an iframed element, the 'contents()' method must be used. That way we can start triggering some functions with the iframe.

    3) Create the detectFn() that will execute the code you want to use after detecting the change in the fake textarea.

    4) Declare the variable 'timer'.

    5) The bind() method must be used with the 'iframed html' tag for using the keyup event. That way the typing action of a textarea will be simulated.

    6) Each keyup will execute the detect function multiple times, to prevent that, we use the setTimeout method and store the detectFn in the variable 'timer'. Finally the variable must be passed to the clearTimeout as an argument, that way each keyup, will cancel the previous execution of the detect function.