. focus () Not focusing on a new item

I have a function to rename specific divs. The way I'm trying to get it to work is as follows:

  • User right click div
  • User clicks "Rename" in the context menu
  • Div gets an input element and automatically focuses
  • The input comes after pressing the enter key or pressing the screen.

I have most of the steps, but the input element does not focus after clicking rename. Here is the code:

function Rename( ){ ClickedFile.innerHTML = "<input class='Rename' type='text' value='" + ClickedFile.innerHTML + "'>"; ClickedFile.childNodes[0].focus(); } 

ClickedFile is a node that has been right-clicked. Changing innerHTML works fine, but .focus () does not, and I'm not sure why. I also do not get any errors on the console.

I also tried using:

 ClickedFile.childNodes[0].select(); ClickedFile.childNodes[1].focus(); ClickedFile.focus(); 

None of them worked.

Edit:

  • I know that using jQuery can help, but I'm more interested in knowing why this is not working.

  • I fixed the problem. This has something to do with event handlers. My answer is posted below.

+4
source share
3 answers

You must add an element as part of the DOM

 var input = document.createElement("input"); input.className = "Rename"; input.type = "text"; document.getElementById("somenode").appendChild(input); input.focus(); // should work now 

see violin

+3
source

The reason is that since you immediately call the selection and focus methods. The browser was not able to insert an element so that it was not part of the DOM.

A quick and dirty solution is to use the setTimeout function with a value of 0 milliseconds:

 function Rename( ){ ClickedFile.innerHTML = "<input class='Rename' type='text' value='" + ClickedFile.innerHTML + "'>"; setTimeout(function(){ClickedFile.childNodes[0].focus();}, 0); } 

This forces the browser to do everything it needs to do, and then run the function that you passed to setTimeout

The following script shows your example operational: http://jsfiddle.net/Kennethtruyers/fX8h6/

+1
source

I fixed the problem by changing a function that renames a div that will run on "mouseup" instead of "mousedown".

I think the reason is that it caused the problem because the rename () function was run on mousedown, as a result of which the focus was set during "mousedown", but the context menu was not hidden until "mouseup".

I cannot confirm that the reason, but I know that the code works after "mousedown" has been changed to "mouseup" for the Rename () trigger.

+1
source

Source: https://habr.com/ru/post/1480592/


All Articles