Search code examples
javascripthtmlinputiconsmarkup

How can I add more icon in input tag when I key down comma


I'm wondering how can I add more icon, when I keydown comma inside input tag

before input comma
after input comma

is there any plugins or reference code? please let me know


Solution

  • You can add an EventListener for the keyup event, that is fired, if a key was pressed and is released. The event interface proviedes a code property, that contains the code of the key that was pressed. If this code is "Comma", you add a 🏠 (or any other character or icon) to the input's value:

    const input = document.querySelector("input");
    
    input.addEventListener("keyup", (event) => {
      if (event.code === "Comma")
        input.value += "🏠";
    })
    <input type="text" value="🏠">

    If you want to insert material icons, you can use a div with contenteditable and insert a <span class="material-icons">[icon-name]</span> after the user typed a comma:

    const icon = `<span class="material-icons">house</span>`
    
    const input = document.querySelector("div[contenteditable]");
    
    input.addEventListener("keyup", (event) => {
      if (event.code === "Comma")
        input.innerHTML += icon;
    })
    div[contenteditable] {
      border: 1px solid black;
    }
    <html lang="en">
    
    <head>
      <!-- ... -->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    </head>
    
    <body>
      <div contenteditable><span class="material-icons">house</span></div>
    </body>
    
    </html>

    The bad thing about this is, that for example every house icon is five characters long, because we use house in the span and that is a house icon in the google material icons font, but it still remains five characters long. But this could be solved using another icon font, that works with classes.