Search code examples
javascripthtmlcsstypeahead

Drop-down list closes at unwanted time


I want to create search-input with drop-down list. The list must close when i have focused or clicked anywhere except search-input.

I added listClose() to "blur"-Listener. But now I can`t catch click-event from drop-down elements. Which is the event-listener I really need? Or I need the another realization?

Please, run snippet below. I tried to write it the most clear.

document.addEventListener("DOMContentLoaded", function() {
  var inputElement = document.getElementById("input_word-search");
  var listElement = document.getElementById("dd-menu_search-input");

  // Input will focused when document is ready.
  inputElement.focus();

  listOpen = function() {
    listElement.classList.add('dd-open');
  };

  listClose = function() {
    listElement.classList.remove('dd-open');
  };

  inputElement.addEventListener("focus", function(e) {
    listOpen();
  });

  inputElement.addEventListener("blur", function(e) {
    listClose();
  });
})
.dd-menu {
  padding: 8px 0;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
  position: absolute;
  display: none;
}

.dd-suggestion {
  cursor: pointer;
  text-align: left;
  padding: 3px 20px;
  line-height: 24px;
}

.dd-suggestion:hover {
  color: #fff;
  background-color: #697981;
}

.dd-open {
  display: block;
}

.dd-empty {
  display: none;
}

#dd-menu_search-input {
  width: 74%;
}
<body>

  <div id="input-group">
    <input id="input_word-search" class="input_search suggest__field" type="search" autocomplete="off" name="q" placeholder="Seach">
    <div id="dd-menu_search-input" class="dd-menu dd-open">
      <div class="dd-dataset">
        <div class="dd-suggestion" onclick="alert('Click!')">
          suggestion-1
        </div>
        <div class="dd-suggestion" onclick="alert('Click!')">
          suggestion-2
        </div>
        <div class="dd-suggestion" onclick="alert('Click!')">
          suggestion-3
        </div>
        <div class="dd-suggestion" onclick="alert('Click!')">
          suggestion-4
        </div>
        <div class="dd-suggestion" onclick="alert('Click!')">
          suggestion-5
        </div>
      </div>
    </div>
  </div>

</body>


Solution

  • I added boolean-variable that indicates mousedown-event on drop-down list

        var mousedownOnNodeCalee = false;
    
        listElement.addEventListener("mousedown", function (e) {
            mousedownOnNodeCalee = true;
        });
    
        inputElement.addEventListener("blur", function (e) {
            if(!mousedownOnNodeCalee) {
                listClose();
                return;
            }
            inputElement.focus();
            mousedownOnNodeCalee = false;
        });