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

放肆的年华 提交于 2019-12-06 06:10:33
Ricardo Castañeda

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.

I found this to be much simpler:

    $('#editor_textarea').wysiwyg('document').keypress(function(e) {
        e.preventDefault(); //This will cancel the keypress
        alert('Keypress in jwysiwyg editor detected!');
    });

You can set autoSave to the true and do like these:

$(element).wysiwyg('getContent').afterSave(function () { /magic/ }

if you want you can trigger 'change' of an element in this handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!