Егор Кротенко Егор Кротенко - 10 days ago 5
CSS Question

Close menu by clicking on any screen place

Have a script thats open menu and closes after clicking on 'li' element, how to close it by clicking on any place on screen ?

$(function() {
$('.drop-down-input').click(function() {
$('.drop-down-input.selected').removeClass('selected'); // Forget the previous selection
$(this).addClass('selected');
$(this).find(".dropdown-list").show();
});

$(document).on("click", ".drop-down-input.selected li",
function(e) {
e.stopPropagation();
$('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html());
});
});


Thats my HTML:

<div class="styled-input-container drop-down-input">
<input id="simple_2" class="drop-down-select" placeholder="input text" type="text">
<ul class="dropdown-list">
<li>eeee</li>
<li>xxxx</li>
<li>xxxx</li>
<li>xsssxxx</li>
</ul>
</div>

Answer

Here's a working solution. Hope it helps :)

$( document ).ready(function() {
    
    // change from grey to blue color input
    
    
  $(".styled-input-container input").focus(function () {
     $id = this.id;
     $idgen = '#' + $id;
     //console.log($idgen);
     
     $($idgen).closest( "div" ).addClass('focused');
    });
    
    $(".styled-input-container input").blur(function() {
        $('.styled-input-container').removeClass('focused');
        
    });
  
  
    
    //open % close ul list input
    
   $(function() {
  $('.drop-down-input').click(function() {
  $('.drop-down-input.selected').removeClass('selected'); // Forget the previous selection
  $(this).addClass('selected');
  $(this).find(".dropdown-list").show();
});

$(document).on("click", ".drop-down-input.selected li",
  function(e) {
    e.stopPropagation();
    $('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html());
  });
});

$(document).mouseup(function (e){
    var container = $(".dropdown-list");

    if (!container.is(e.target)
        && container.has(e.target).length === 0)
    {
        container.hide();
    }
});
   

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="styled-input-container">
                       <input id="simple_1" placeholder="input text" type="text">
                   
                   </div>
                   <div class="separator"></div>
                   <div class="styled-input-container drop-down-input">
                       <input id="simple_2" class="drop-down-select" placeholder="input text" type="text">
                       <ul class="dropdown-list">
                           <li>eeee</li>
                           <li>xxxx</li>
                           <li>xxxx</li>
                           <li>xsssxxx</li>
                       </ul>
                   </div>

Comments