Search code examples
jquerytinymce

how to get the span created dynamically inside an iframe?


I am using TinyMCE editor.Everything I write inside the editor is placed in p tag. But when I click the equation tool from toolbars,a dynamically span having class AMedit is created inside the p tag.My question is how to do some stuff or more simple just alert something when I focus the newly created span.Remember that the this span is contenteditable and also the whole editor comes from an Iframe.

Please have a look at the following link.

http://www.imathas.com/editordemo/demo.html

I have written the following code but id does not work for me.What is the error in my code.

var span = $("#elm1_ifr").contents().find("span.AMedit");
var canPressEnter = true;
    span.on("focus", function(){
        canPressEnter = false;
    }).on("keypress", function(e){
        var code = (e.keyCode ? e.keyCode : e.which);
        if (canPressEnter === false && code === 13)
        {
            alert('welcome');
        }
    }).on("blur", function(){
        canPressEnter = true;
    });
   })

Please anyone can explain with a simple example.


Solution

  • I understand your problem better with the beyondthelogix.com link.

    TinyMCE editor changes the class of the span from AM to AMedit. The solution I think about is to have a setInterval listening for that class change. I wrapped my code in a .ready() function.

    Try this:

    Add a line here:
    
    tinyMCE.init({  
    theme : "advanced",
        mode: "exact",
        elements : "elm1",
    oninit: function() { loadlistener(); }, //add this line to run the next code under
    setup : function(ed) {
    

    and add this somewhere in the page:

    var amedit = false;
    
    function loadlistener() {
        console.log('load');
        $("#elm1_ifr").contents().keydown(function (e) {
            console.log('key');
            var code = (e.keyCode ? e.keyCode : e.which);
            console.log(code);
            if (code == 13 && amedit) {
                e.preventDefault();
                return false;
            }
        });
        var p_parent = $("#elm1_ifr").contents().find("p");
        setInterval(function () {
            if (p_parent.find('span').length && p_parent.find('span').hasClass('AMedit')) {
    
                amedit = true;
            } else {
                amedit = false;
            }
        }, 200)
    };