It's possible to focus on an input field using D3, without even the need to go through setTimeout
(I don't know why, but I'm not complaining).
But this only works the first time. After the second press on Set
(i.e.: Set
, Reset
, Set
), the input field does not receive focus. Why?
Setting a callback to focus after the transition is complete gives me an error.
<!DOCTYPE HTML>
<head>
<style>
div { width: 300px; }
div#outerdiv { height: 500px; background-color: #ccc; }
div#topdiv { height: 400px; background-color: #dff; }
div#bottomdiv { height: 0px; background-color: #ffd; display: 'none' }
input:focus { background-color: pink; }
</style>
</head>
<body>
<div id="outerdiv">
<div id="topdiv">
<button onclick=open_form();>Set</button>
<button onclick=close_form();>Reset</button>
</div>
<div id="bottomdiv">
<form action="javascript:close_form()">
Name:
<input type="text" id="myTextField" name="name">
<input type="submit" name="submit" value="Submit">
</form>
</div>
</div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
<script>
function open_form() {
d3.select('#topdiv').transition().duration(500)
.style('height', '100px');
d3.select('#bottomdiv').transition().duration(500)
.style('height', '300px').style('display', 'inline-block');
d3.select("#myTextField").node().focus();
}
function close_form() {
d3.select('#topdiv').transition().duration(500)
.style('height', '390px');
d3.select('#bottomdiv').transition().duration(500)
.style('height', '10px').style('display', 'none');
}
</script>
</body>