Search code examples
javascriptjqueryjqte

How to create dynamic instances of JQueryTE text editor


I am attempting to create a small program that incorporates dynamically created instances of this editor.

I have it working except for the ability to create a button that opens/closes the editor. jsFiddle of what I've got so far.

"use strict";
$(document).ready(function() {

var createPad = $("#createPad").click(function () {
var body = document.getElementById("body");

var editorNumberCounter = 1;
var toggleOnOffCounter= 1;
var editorName = '.'+ (editorNumberCounter++);


var status = document.createElement('div');
status.className = "status";
status.id = "status";

var editorName= document.createElement('span');
editorName.className = "status";
editorName.id = "status";

$(body.appendChild(status));
$(body.appendChild(editorName));

var toggle = status.id + toggleOnOffCounter++;

    $(editorName).jqte();

    // settings of status
    var jqteStatus = true;
    $(toggle).click(function()
    {
        jqteStatus = jqteStatus ? false : true;
        $(editorName).jqte({toggle : jqteStatus})
    });

     });

    });

Solution

  • I made up some changes to your code an now seems to work.

    I try to explain them point by point:

    1. variabiles editorNumberCounter and toggleOnOffCounter must be globally scoped or you lose the incremented value
    2. ID of elements (dynamically created or not) MUST be unique, so I create the div and span element considering the counter
    3. for dynamically created elements you must use the bind method or the event will not be bind
    4. the toggle property not exist! You must use the status property
    5. the element onto JQTE is binded is get as next element after the clicked element

    Code:

    var editorNumberCounter = 0;
    var toggleOnOffCounter = 0;
    $(document).ready(function () {
    
        var createPad = $("#createPad").click(function () {
            var body = document.getElementById("body");
    
            var editorName = '.' + editorNumberCounter++;
            toggleOnOffCounter++;
    
    
            var status = document.createElement('div');
            status.className = "status";
            status.id = "div_status" + editorNumberCounter;
    
            var editorName = document.createElement('span');
            editorName.className = "status";
            editorName.id = "span_status" + editorNumberCounter;
    
            $(body.appendChild(status));
            $(body.appendChild(editorName));
    
            $(editorName).jqte();
    
            // settings of status
            var jqteStatus = true;
            $("#div_status" + editorNumberCounter).bind("click",function () {
                jqteStatus = jqteStatus ? false : true;
                $(this).next().jqte({
                    status: jqteStatus
                })
            });
    
        });
    
    });
    

    Here is a working fiddle: http://jsfiddle.net/IrvinDominin/UfhNQ/14/