0

I'd like everytime the user click over the #box div to focus within the #innerbox contenteditable.

I'm using the following code, but it only works once:

document.getElementById('box').addEventListener('click', function(){
  setTimeout(function() {
    document.getElementById('innerbox').focus();
  }, 0);
});
#innerbox{
  border: 1px solid;
}

#box{
  border: 1px blue solid;
  padding:20px;
}
<div id="box">
  <div id="innerbox" contenteditable="true" style="min-height:26px;" onkeyup="myFunction()"></div>
</div>

there are no other 'click' listeners on the #box

EDIT: A difference i have with the snippet above is that the #innerbox div gets removed and recreated in the DOM, and it's after it gets recreated the first time that click eventlistener doesn't work anymore, can this be the issue?

EDIT 2: I tried using

$('#box').on('click', '#innerbox', function(){
  $('#innerbox').focus();
});

for dynamically created elements but also doesn't work.

  • 3
    Please create a [mcve]. (works fine for me: https://jsfiddle.net/p3Lfczsx/) –  Sep 04 '18 at 13:22
  • seems like you would want to prevent the default action and also check to make sure the click is not inside of the child. – epascarello Sep 04 '18 at 13:24
  • The code looks fine except there are few errors which actually should not hamper from executing the function you are trying to. Could you provide more detail on your issue? – Jay Sep 04 '18 at 13:27
  • So what do you mean it only runs once. Is there other code on the page that replaces the content? – epascarello Sep 04 '18 at 13:40
  • @Pete label is not going to focus a contenteditable. – epascarello Sep 04 '18 at 13:50
  • code would be too long, are more js pages, but a difference that may be the culprit i'm thinking of, can be the fact that the #innerbox div gets removed and recreated in the DOM, and it's then that click eventlistener doesn't work anymore –  Sep 04 '18 at 14:28
  • @ChrisG i edited with update –  Sep 05 '18 at 10:12
  • @notsure removing and recreating the div is the issue, yes. The event handler will not survive that. As you found out, jQuery's `.on()` can be used to solve this. –  Sep 05 '18 at 11:32

0 Answers0