0

I want an HTML <input type="text"> element that has to be clicked on before it can be edited. Kind of along the same lines of how, in Windows or Mac OS Finder, you need to click on a filename before it turns editable.

I at first tried setting the <input> to disabled, and having JavaScript that "enables" it when clicked. This did exactly what I wanted in Chrome, but didn't work in Firefox, because in Firefox apparently making it disabled removes its ability to react to clicks as well.

How do I get this behavior in a way that works well across modern browsers?

Ascendant
  • 944
  • 1
  • 10
  • 28

2 Answers2

2

You can listen on the parent div and check if input is clicked and then enable it.

Updated answer is working in firefox too.

function enableInput() {
  if(event.target.id == 'text-input-overlay') {
   event.target.style.display = "none";
   document.getElementById("text-input").disabled = false;
  }
 }
<html>
<body>
<div style="position:relative;" id="container" onclick="enableInput()">
  <label for="text-input">Input: </label>
  <input id="text-input" type="text" disabled />
  <div id="text-input-overlay" style="position:absolute; left:0; right:0; top:0; bottom:0; cursor: pointer;" ></div>
</div>
</body>
</html>
Hamza Arshad
  • 856
  • 5
  • 8
1

You can reset the default input styles with CSS making it look like a normal text/element. Then use focus and blur events to toggle.

const input = document.querySelector('input[type="text"]');

input.addEventListener('focus', (event) => {
  event.target.classList.remove('disabled');    
});

input.addEventListener('blur', (event) => {
  event.target.classList.add('disabled');     
});
.disabled {
  border: none;
  background: #ccc;
}
<input id="text-input" type="text" class="disabled" value="Click Me" />
Sai Krishna
  • 597
  • 4
  • 16