Yurii Rashkovskii
Yurii Rashkovskii

Reputation: 1152

SVG-based text input field

Has anyone seen any javascript implementation of a text input field besides http://www.carto.net/papers/svg/gui/textbox/ ?

Upvotes: 33

Views: 51222

Answers (3)

Ricardo Cruz
Ricardo Cruz

Reputation: 3583

There is an interesting SVG node called foreignObject, which allows you to place HTML, flash, etc within your SVG code. Try the following:

<svg width="100%" height="500" xmlns="http://www.w3.org/2000/svg">
  <foreignObject x="10" y="10" width="100" height="150">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <input>
    </div>
  </foreignObject>
</svg>

EDIT: added xmlns so it works for IE.

Upvotes: 43

Wolfgang Kuehn
Wolfgang Kuehn

Reputation: 12926

This is for MS Internet Explorer, not tested in any other browser.

As mentioned in another comment, up to IE11 does not support foreignObject. Instead, use the contentEditable attribute.

Plain SVG example

<svg width="100" height="100" >
    <g transform="translate(40,40)">
        <text contentEditable="true">foo</text>
    </g>
</svg>

D3.js example with data binding

Here we listen for key events to write the text back to the data.

selection.
  .append("text")
    .attr("contentEditable", true)
    .text(function(d) { return d.text })
    .on("keyup", function(d) { d.text = d3.select(this).text(); });

Note: If nodes are dynamically generated like with d3.js, you must capitalize contentEditablelike such (this took me some time)!

Note: Do not style your text with pointer-events: None, for then you cannot interact with the text anymore, regardless of the contentEditable setting.

Upvotes: 10

Erik Dahlstr&#246;m
Erik Dahlstr&#246;m

Reputation: 60966

I've seen another one, note that it requires support for the 'editable' attribute from SVG Tiny 1.2... it's definately more native in the sense that there's not a single line of javascript in that example. Try it out in Opera.

Upvotes: 3

Related Questions