Change CSS automatically when typing

Asked

Viewed 68 times

-1

I need to change the CSS of a string that is inside keys automatically.

Follow an example:

Olá {{AMIGO}}.

Whenever I typed this {{AMIGO}}, I wanted it to be button-shaped and without the keys.

Someone knows how to do?

1 answer

3


This type of functionality is complex. Mainly because of the position of the marker/cursor... If you are writing in the middle of a sentence and change the content (by changing the {{AMIGO}} it is complex to put the cursor back in the expected place.

But leaving that problem aside, what you’re looking for in the question can be done like this:

(or using .replace)

const editor = document.getElementById('editor');
const tag = '{{AMIGO}}';
editor.addEventListener('keyup', () => {
  const html = editor.innerHTML;
  if (html.includes(tag)) {
    editor.innerHTML = html
      .split(tag)
      .join('<button>amigo</button>');
  }
});
#editor {
  border: solid 1px black;
}
<div contenteditable id="editor"></div>

  • An adjustment that can be interesting, move the pointer to the end after innerHTML, because otherwise the pointer goes back to the beginning and during a typing it becomes a nuisance.

  • Very good! But it can be something even more basic, insert only a CSS formatting instead of turning into a button and put the pointer pro end of the string, have to make this option there for me?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.