Click Event for Basic CSS Dropdown Menu

My goal is to develop a straightforward feature where a dropdown menu appears below a specific text field once it is 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>

The issue arises with the click function not triggering as expected... (Perhaps due to CSS taking precedence with focus first and preventing the click event from registering on the hidden element?)

Despite having an "alert" in place, my intention is to utilize the click event to populate the value back into the .lab field resembling a dropdown functionality.

Answer №1

When you interact with the <div> element that has the class .lab, it triggers the first event listener and reveals the dropdown list. Clicking on any of the <div> elements inside the dropdown list with the class .clickable will then activate the second event listener. This action closes the dropdown list and logs the ID value of the selected <div> element onto the console.

/* Action upon clicking the <div> with ".lab" class */
$(document).on('click', '.lab', function(event) {
  event.stopPropagation();
  console.clear();
  console.log("The dropdown list is now visible.");
  
  /* Display Dropdown List */
  $('.val').attr('style', 'display: inline-block');
  
  /* Event when clicking the <div> with ".clickable" class */
  $(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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Inquiries prior to projecting rays

As I delve into the world of Interaction with Three.js, several questions arise in my mind. 1) Can you shed some light on what exactly Viewport Coordinates are? 2) In what ways do they differ from client Coordinates? 3) How did we come up with this form ...

Ensuring that Bootstrap rows fill the entire height within a column

While working on a template with nested rows and columns in Bootstrap, the layout ended up looking like this: <div class="col-5"> <div class="row"> <div class="col-3 border border-secondary">Truck Number</div> ...

Issues with message display validation in jQuery

Validation has been applied to the form, and there are div elements within the input fields with corresponding IDs. The goal is to display error messages within those divs. Specifically, if an input field is missing, the errorMessage should be set in the ...

What are the differences between using attachShadow with the "mode" set to open compared to closed

I've recently delved into the world of Shadow DOM through some casual video watching. It seems like many people are quick to dismiss this feature, with comments like "Just keep it open" and "It's less flexible when closed." attachShadow( { mode ...

Having trouble displaying toasts on my website using Angular Material design and $mdToast

Hello there, I am very new to AngularJS, and I have just started using the basic function Show() from $mdToast. Below is the complete code that I have written for this issue, and I would greatly appreciate any help you can provide. 'use strict&apos ...

Spin a sphere by clicking on a link using three.js

I've designed a spherical object and have a group of links. I'm looking for a way to manipulate the position or rotation of the sphere by simply clicking on one of the links. Despite extensive searching, I haven't been able to find an exampl ...

Lower the placement of Glyphicons

I have recently implemented a custom font on my website. Unfortunately, this font is not standard and its alignment is off. As a result, when I use this font with Twitter Bootstrap glyphicon, they do not appear in the same line. Is there a way to adjust t ...

Updating the table in real time with new data from the MySQL database without the need to

I'm struggling with dynamically adding new lines to my table without refreshing the page. Most of the guides I've found suggest using Ajax, but that resets my table. My table displays a name, status, and message fetched from the database. The use ...

Ways to extract a specific value from a geojson object using the key name

After making a call to the back-end, I retrieved the below geojson data in the 'data' object. However, when trying to access the values of the 'type' and 'features' keys within the geojson, I encountered difficulties. data["g ...

The JavaScript function is returning a value of undefined

I encountered an issue where my Javascript function is returning undefined even though it alerts the correct value within the function itself. I have a setup where I call the function in my 1st controller like this: CustomerService.setName(data.name); A ...

Sinon - observing the constructor function

While I've come across a few related inquiries, none seem to address what I am specifically looking to achieve. My goal is to monitor a constructor method in such a way that when an object created with the constructor calls this method from a differe ...

Unable to group the array based on the key value using Jquery or Javascript

I am looking to group my array values based on specific key values using Jquery/Javascript, but I am facing issues with my current code. Let me explain the code below. var dataArr=[ { "login_id":"9937229853", "alloc ...

After the state loads in Ui-router, how can I execute a function?

Transitioning from jQuery to Angular, I am struggling with ui-router and states. In jQuery, I can make an AJAX call and then run another function on success. How can this be achieved in Angular? For instance, consider the code snippet below: var ivApp = ...

Easier JavaScript for numerous HTML elements

I am an aspiring JavaScript learner seeking advice. Currently, I am working on a website that features numerous items with multiple images for each. I am utilizing JQuery to display a larger image when the user hovers over a thumbnail image. My query is ...

Tips for positioning the popup ul in relation to its parent li

How can the pop-up ul be positioned in the center of the parent li using CSS? * { margin: 0; padding: 0; } #track-nav { margin-left: 50px; margin-top: 50px; float: left; width: 100%; list-style: none; font-weight: bold; margin-bottom: ...

What is the best place to define data that remains constant?

In a Vue component, I am looking to utilize data that remains constant. The issue arises when attempting to implement the following code: const numbers = [1, 2, 3] new Vue({ el: "#app" }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2 ...

Error with REST service and browser history in ReactJS

I am currently developing my first Java application, which is a REST service built with Spring Boot. It utilizes technologies such as WEB, REST, JPA, Thymeleaf, and MySQL. The API is fully functional, but I wanted to enhance it with a user interface. After ...

Updating the selected value in TomSelect based on an ajax response

I am facing an issue setting a value on TomSelect using ajax response. Normally, I would use the following code on a general dropdown: $('#homebasepeg').val(data.hmb_id).change(); However, when I try to apply this on TomSelect, it doesn't s ...

Is it possible to ensure that a newly created element functions in the same way as an existing element?

I am currently in the process of developing an application that empowers users to generate new items, modify existing items, or delete items by utilizing corresponding icons located adjacent to each item. When it comes to existing items, the action icon d ...

Steps to conceal a <select> element and reveal it by clicking a button

I'm currently working with Bootstrap 3 and I am attempting to replicate jQueryMobile's select option feature. This would involve replacing the standard select textbar and arrows with a single button that can toggle the opening of the select. Ins ...