Search code examples
javascripthtmlinputplaceholder

Write text next to text in a input if contient "//"JS


I would like to display a placeholder (or grey text) in JavaScript next to a text in an entry if it contains "//".

(The idea did not come from me, I put it in credit here) https://dribbble.com/shots/14433695-Task-composer-interactions

Do you have any idea how to display text in an entry that already contains text?

Thank you in advance for your help.


Solution

  • Here's one solution. It uses 2 inputs and jQuery to manipulate the DOM (but vanilla would work fine as well). It's not incredibly robust but accomplishes what your question asked. Because the input gets auto-sized, I am importing and using a monospace font, and using the ch unit to measure the length of the input.

    $('.faux-element .main-input').on('input', function(e) {
      let l = $(this).val().length;
      $(this).css({
        width: l + "ch"
      });
      if ($(this).val().includes('//')) {
        let second = $(this).parent().find('.secondary-input').attr('readonly', false);
        second.attr('placeholder', 'Another place to type').focus();
    
      }
    }).focus()
    .faux-element {
      padding: 10px;
      background: #f0f0f0;
      border-radius: 4px;
    }
    
    .faux-element input,
    .faux-element input:focus {
      border: none;
      outline: none;
      background: none;
      font-family: 'Roboto Mono', monospace;
    }
    
    .secondary-input {
      display: inline-block;
      margin-left: 2px;
      color: #f00;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400&display=swap" rel="stylesheet">
    <div class='faux-element'>
      <input class='main-input' /><input class='secondary-input' readonly />
    </div>