byle.05
byle.05

Reputation: 196

CSS Simple Dropdown click event

I am trying to build a very simple functionality to create a drop down under a certain text field when its clicked.

$(".val").children("div").on("click", function() {
  alert("CLICK");
});
.container {
  display: inline-block;
}

.val {
  display: none;
  position: absolute;
  z-index: 1;
}

.container:focus-within .val {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="lab" contenteditable>LABEL</div>
  <div class="val">
    <div>VAL1</div>
    <div>VAL2</div>
  </div>
</div>

Main problem comes with the click function which it never gets triggered... (I guess it runs first the lost focus in CSS and then no click is done in that element as its hidden?)

Even though there is an "alert" there, I want to use the click event to set the value back in the .lab field like a dropdown.

Upvotes: 1

Views: 83

Answers (1)

Sercan
Sercan

Reputation: 5101

In the solution below, clicking the <div> element with the .lab class style applied will fire the first event listener and the dropdown list will be visible. Clicking on any of the <div> elements in the dropdown list that implements the .clickable class style fires the second event listener. In this case, the dropdown list is closed and the id value of the clicked <div> element is printed to the console.

/* Fires when clicking the <div> element with the ".lab" class style applied. */
$(document).on('click', '.lab', function(event) {
  event.stopPropagation();
  console.clear();
  console.log("The dropdown list opens.");
  
  /* Open Dropdown List */
  $('.val').attr('style', 'display: inline-block');
  
  /* Fires when clicking the <div> element with the ".clickable" class style applied. */
  $(document).on('click', '.clickable', function(event) {
    event.stopPropagation();
    console.clear();
    console.log(`Clicked Container ID: ${$(this).attr('id')}`);
    
    /* Close Dropdown List */
    $('.val').attr('style', 'display: none');
  });
  
  $(document).on('click',function(event){
    event.stopPropagation();
    $('.val').attr('style', 'display: none');
  });
});
div {
  padding: 5px;
}
.container {
  display: inline-block;
}
.lab {
  border: 1px solid blue;
  margin-bottom: 5px;
  cursor: pointer;
}
.val {
  display: none;
  position: absolute;
  z-index: 1;
}
.container:focus-within .val {
  display: block;
}
.clickable {
  cursor: pointer;
  border: 1px solid red;
  margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div class="container">
    <div class="lab" contenteditable>Open Dropdown</div>

    <div class="val">
      <div id="first" class="clickable">First</div>
      <div id="second" class="clickable">Second</div>
    </div>
  </div>
</body>

Upvotes: 1

Related Questions