Search code examples
javascripttextareanicedit

Placeholder doesn't work in NicEdit


I'm using NicEdit Inline WYSIWYG and try to understand how to make placeholder work with it.

I created a div with attribute placeholder, but when NicEdit activate it, show blank textarea without placeholder.

Maybe there is some way to make it work. As I understood it writes text directly into div.

In code it looks like. (I comment display non for textarea) https://i.sstatic.net/hRvqA.png


Solution

  • You could manually add/remove the placeholder, by using nicEditor Events.
    focus Send when an editor gains focus (IE someone clicks inside it).
    blur Sent when an editor instance loses focus.

    var editor = new nicEditor();
    var $placeholder = '<p>Click here to add content...</p>';
    
    $('[id^="textArea"]').each(function() {
        var textAreaId =  $(this).attr("id");
    
        editor.addInstance( textAreaId );
        var editorInstance = editor.instanceById(textAreaId)
    
        // Add the initial Placeholder
        var content = editorInstance.getContent();
        if(content == "" || content == "<br>"){
            editor.instanceById(textAreaId).setContent($placeholder);
        }
    
        // onFocus - Remove the placeholder
        editor.addEvent('focus', function() 
        {
            if (editorInstance.getContent() == $placeholder){
                editor.instanceById(textAreaId).setContent("<br>");
            }
        });
    
        // onBlur - Re-add the placeholder
        editor.addEvent('blur', function() 
        {
            var newText = editorInstance.getContent();
            if(newText == "" || newText == "<br>") {
                editor.instanceById(textAreaId).setContent($placeholder);
            }
        });
    });
    

    Initially, check to see if there is no content or if there is a single <br> (this is nicEditor's placeholder). If so, replace with your placeholder.
    Then on focus check for the placeholder and change the content back to "<br>".
    Then on blur check if the content is still empty and replace it with the placeholder again