ValJor Posted March 19, 2022 Share Posted March 19, 2022 Hi! Note: first time posting here. In my code (example below) the input on div2 works as expected, but the one in div1 does not, it doesn't maintain focus after I click on it. The function does change the content of the div, but it does not allow me to enter a value. What do I have to do to make the input in div1 behave the same way as the input in div2? Is there another event that works like onclick but keeps the focus after we "unclick"? <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Changing the content of a div by clicking on it</title> <script> function div1_was_clicked() { document.getElementById("div1").innerHTML = '<input type="text">'; } </script> </head> <body> <div id = "div1" onclick="div1_was_clicked();"> <p>1 2 3</p> </div> <div id = "div2"> <input type="text"> </div> </body> </html> Link to comment Share on other sites More sharing options...
Ingolme Posted March 19, 2022 Share Posted March 19, 2022 Every time you click on the div, it deletes what's inside the div and replaces it with an empty text field. Since the text field is inside the div, a click on the text field is also a click on the div, which makes the text field get deleted and replaced with another text field. If you put the click event on the <p> element instead the event listener will be gone when the <p> element gets removed. That's one possible solution, there are others, but what solution is best depends on what your end goal is with the whole page. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Changing the content of a div by clicking on it</title> <script> function div1_was_clicked() { document.getElementById("div1").innerHTML = '<input type="text">'; } </script> </head> <body> <div id="div1"> <p onclick="div1_was_clicked();">1 2 3</p> </div> <div id = "div2"> <input type="text"> </div> </body> </html> Link to comment Share on other sites More sharing options...
ValJor Posted March 19, 2022 Author Share Posted March 19, 2022 That is fantastic @Ingolme! Such a simple and elegant solution. I'll apply this to my program. Thank you very much! Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now