Search code examples
javascripthtmlcsspagedown

How can I hide a <div> and have it show only when a <textarea> has focus?


I'm using the same editor as Stack Overflow and the HTML looks something like this with multiple editors on a page:

<pagedown-admin id="modal-data-solution-1">
   <div>
      <div>
         Menu
      </div>
   </div>
   <textarea>
         ABC
   </textarea>
</pagedown-admin>
<pagedown-admin id="modal-data-solution-2">
   <div>
      <div>
         Menu
      </div>
   </div>
   <textarea>
         ABC
   </textarea>
</pagedown-admin>

Is there a way that I could hide the <div> that contains the menu and have it show only when the <textarea> has focus. Note that I'm not using jQuery so it would need to be a vanilla JavaScript solution. I'm just not sure where to start trying to code something like that.


Solution

  • Here's an example of a generic solution, that will work with multiple menus based on your markup. The JavaScript could be improved, but it will give you an idea, how to solve it.

    HTML

    <pagedown-admin>
        <div>
            <div class="off">Menu</div>
       </div>
       <textarea>
             ABC
       </textarea>
    </pagedown-admin>
    

    CSS

    .off {
        display: none;
    }
    

    JavaScript

    var tas = document.getElementsByTagName('textarea');
    
    for (var i = 0, j = tas.length; i < j; ++i) {
        tas[i].onfocus = function() {
            var e = this.parentNode.firstElementChild.firstElementChild;
            e.classList.toggle('off');
        }
    
        tas[i].onblur = function() {
            var e = this.parentNode.firstElementChild.firstElementChild;
            e.classList.toggle('off');
        }
    }
    

    Demo

    Try before buy