search

Home  >  Q&A  >  body text

How to create a label with a disconnected input section?

I have a basic input and tags: https://codepen.io/agrawalishaan/pen/QWBxBdK

span {
  border: 1px solid red;
}
<label for="myInput">
  I am a label! <span>icon</span>
</label>
<input id="myInput"/>

When I click on the label, the cursor is set inside the input, which is ideal.

My tags also contain an information icon. When I hover over the icon, a popup appears (so I need hover for it to work).

On mobile devices, instead of hovering, a click is required. However, when I click on this icon, a popup appears and the input is selected, how can I specifically disable the input selection when only clicking on the icon?

P粉006540600P粉006540600334 days ago452

reply all(1)I'll reply

  • P粉147747637

    P粉1477476372024-02-26 17:09:32

    I added some JavaScript using the event.preventDefault() method to ensure that the input does not get focus when the icon is clicked.

    const infoIcon = document.querySelector('.info-icon');
    const popup = document.querySelector('#popup');
    
    infoIcon.addEventListener('click', function(event) {
      event.preventDefault(); // prevent default behavior of focusing on the input
      
    //toggles the popup on click/touch of the icon
    popup.style.display = popup.style.display === 'none' ? 'block' : 'none'
    });
    span {
      border: 1px solid red;
    }
    
    #popup {
       position:absolute;
       display:none;
       width:50px;
       height:50px;
       border-style:solid;
       background-color:yellow;
    }
    
    .info-icon:hover #popup { /*uses the ' ' adjacent child selector to display popup on hover*/
      display: block;
    }
    
    

    reply
    0
  • Cancelreply