1

I'd like to display at short d3 animation and upon completion, have a form field become automatically selected/focused to take user input.

It seems like it is best accomplished through chaining functions. I tried to use the javascript function focus() that selects the form field ("signup","inputname") on load, but this isn't working.

How do I select a form field automatically after animation completion?

d3.js:

<script>
selectReady = d3.selectAll("#ready")
    .on("mouseover", function(){d3.select(this).style("color", "red");})
    .on("mouseout", function(){d3.select(this).style("color", "black");})           
    .on("mousedown", animateDisplay); //starts animation with a mousepress

function animateDisplay(){
    d3.selectAll("#Display")
        .transition()
        .delay(200)            
        .duration(1000)             
        .style("color","white") // changes Display to white
        .each("end",selectForm);
};

function selectForm(){
    d3.select("#inputname")
        .focus(); // remove() works here
};  

</script>

HTML:

<html>
<head>
<script type="text/javascript"src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
<p id="ready">Click when ready<p></th>
<p id='Display'>A</p>
<p id='Display'>B</p>
<p id='Display'>C</p>

<form name="signup" id="signup" method="post" action="#">   
    <table> 
        <tr>        
        <td colspan="2" class="labelcell"><label for="name">Name</label></td>   
        <td colspan="2" class="fieldcell">      
            <input type="text" name="inputname" id="inputname" tabindex="1" />  
        </td>   
        </tr>
    </table>
</form>
</body>
</html>
Amyunimus
  • 1,583
  • 4
  • 20
  • 43

2 Answers2

13

Use selection.node to access the underlying DOM element, and then element.focus:

d3.select("#inputname").node().focus()
mbostock
  • 51,423
  • 13
  • 175
  • 129
3

That was clear DEMO

d3.select("#inputname").focus is not a function
http://fiddle.jshell.net/mplungjan/JfvbD/show/
Line 41

Here you go

I changed to this

<p id='DisplayA' class="disp">A</p>
<p id='DisplayB' class="disp">B</p>
<p id='DisplayC' class="disp">C</p>

so I could use this:

d3.selectAll(".disp")

and have the code

function selectForm(){
  if (this.id!="DisplayC") return;
  document.getElementById('inputname').focus();  
}; 
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    Awesome thanks! The function `document.getElementById('inputname').focus()` was particularly helpful. – Amyunimus Mar 22 '12 at 14:58