Search code examples
javascripthtmljquerytagscolor-picker

Get Color Picker value in tags


I'm creating a text editor and so far everything is great, except for a little mess I don't know how to fix.

I need to get the value of the color selected by the user into the tag that is inserted into the textarea.

I don't reeally know how to use JSFiddle, but I think I can share it: https://jsfiddle.net/ElenaMcDowell/mh9rfwct/

<script>//Color picker

//color picker

var theInput = document.getElementById("colorChoice");
var theColor = theInput.value;
theInput.addEventListener("input", function() {

document.getElementById("hex").innerHTML = theInput.value;
}, false);

//Tags

function btnEditor(h, a, i) { // helloacm.com
    var g = document.getElementById(h);
    g.focus();
    if (g.setSelectionRange) {
        var c = g.scrollTop;
        var e = g.selectionStart;
        var f = g.selectionEnd;
        g.value = g.value.substring(0, g.selectionStart) + a + g.value.substring(g.selectionStart, g.selectionEnd) + i + g.value.substring(g.selectionEnd, g.value.length);
        g.selectionStart = e;
        g.selectionEnd = f + a.length + i.length;
        g.scrollTop = c;
    } else {
        if (document.selection && document.selection.createRange) {
            g.focus();
            var b = document.selection.createRange();
            if (b.text != "") {
                b.text = a + b.text + i;
            } else {
                b.text = a + "REPLACE" + i;
            }
            g.focus();
        }
    }// helloacm.com
}

</script>

And the HTML

<div class="fonts-box fonts-color" style="text-align: center;">
            <form>
                <input type="color" value="" id="colorChoice">
            </form> 
            <p id="hex" style="padding-bottom: 3px;"></p>
            <button id="colorSelect" onclick="btnEditor('ECEditor', '[color=#VALUEHERE]', '[/color]');">Select</button>
</div>
<textarea id="ECEditor" class="editor-textarea" name="editor-text"></textarea>

Solution

  • function btnEditor() { 
    
    var but = document.getElementById('wrapper')
    var color = document.getElementById('colorChoice').value
    console.log(color)
    
    but.innerHTML = '<button id=\"colorSelect\" onclick=\"btnEditor(\'ECEditor\', \'[color=' + color + ']\',\'[/color]\');">Select</button>'
       
    }
    
    /*
    this answer
    <button id="colorSelect" onclick="btnEditor('ECEditor', '[color=#000000]','[/color]');">Select</button>
    
    your request
    <button id="colorSelect" onclick="btnEditor('ECEditor','[color=#VALUEHERE]','[/color]');">Select</button>
    */
    <div class="fonts-box fonts-color" style="text-align: center;">
                <form>
                    <input type="color" value="" id="colorChoice">
                </form> 
                <p id="hex" style="padding-bottom: 3px;"></p>
                <span id = 'wrapper'>
                <button id="colorSelect" onclick="btnEditor();">Select</button></span>
    </div>