d3 text

original - create div on click 1 - two different ways (div, fo) 2 - foreignObject

by dirtyd77

HTML

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<button id='text'>Text</button>

CSS

svg {
    border: solid 1px;
    height: 500px;
}

JavaScript

var svg = d3.select("body").append("svg").attr('xmlns', "http://www.w3.org/2000/svg");

d3.select('#text').on('click', function () {
    new Text();
});

function Text() {
    var self = this, m, click = true, fo, ta;
    svg.on("mousedown", function () {
        m = d3.mouse(this);
        //console.log(m);
        if (click) {
            fo = svg.append('foreignObject').attr('contentEditable', 'true')
                .style('border', 'solid 1px blue');
            ta = fo.append("xhtml:textarea").html('text').attr('class', 'text-area');
            ta.style({
                position: 'relative',
                top: m[1] - 10 + 'px',
                left: m[0] - 5 + 'px',
                border: 'solid 2px',
                'font-family': 'Arial',
                'font-size': '12pt',
                'background-color': 'transparent',
                color: '#000',                
                zIndex: '1',
                padding: '5px',
                width: '50px',
                height: '25px'
            }).attr('contentEditable', 'true').attr('autofocus', 'autofocus');
        }
        click = false;
        var taBox = $('.text-area');
        taBox.focus(function () {
            ta.style('border', 'solid 2px').style('resize', 'both');
        });
        taBox.blur(function () {
            ta.style('border', 'none').style('resize', 'none');            
        });
    });
}