Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add background color to text inside textbox?

I do not know how to ask this question correctly and I do not know how to find solutions in google because it leads me to how to add entire background color to a textbox which I am not looking for. I am trying to achieve such results like image below:

enter image description here

I want to add background to each text(of course characters) inside a input tag except spaces. User will start typing stuff inside input tag and will apply background color but spaced text won’t color.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I do not have any code because I do not know how to do it using css or JS if neccesary. I just have a

<input type="text">

I think it might use only JS but I do not know how to(of course I know JS). How do I achieve that?

>Solution :

You can use div with contentEditable and use little js to append text as span

<div contentEditable></div>

CSS

span {
  background-color: red;
  margin-right: 2px;
}
div {
  border: 1px solid black;
}
var el = document.querySelector("div");

el.addEventListener("blur", () => {
  var content = el.textContent;
  var contents = content.split(" ");
  el.innerHTML = "";

  contents.forEach((item) => {
    el.innerHTML += `<span>${item}</span>`;
  });
});

Something like this

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading