Utilizing jQuery for a dropdown menu

After clicking the "..." button, I want to display the edit and delete buttons. However, when I implement this code, it applies to all three buttons instead of just the one I clicked on.

I need guidance on how to modify the jQuery code so that it only affects the button I have clicked, not all of them.

The Code :-

HTML :

<div class="commentdropdown pr-3">
    <button class="dropbtn btn p-0 m-0 bg-white">...</button>
    <div class="dropdown-content">
        <a href="#">Edit</a>
        <a href="#">Delete</a>
    </div>

    <button class="dropbtn btn p-0 m-0 bg-white">...</button>
    <div class="dropdown-content">
        <a href="#">Edit</a>
        <a href="#">Delete</a>
    </div>

    <button class="dropbtn btn p-0 m-0 bg-white">...</button>
    <div class="dropdown-content">
        <a href="#">Edit</a>
        <a href="#">Delete</a>
    </div>
</div>

CSS :

.commentdropdown{
    float: right;
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
}

.apear{
    display: block;
}

.commentbtn{
    width: 30vw;
}

JavaScript :

$(".commentdropdown").on("click", function(){
 $(this).find(".dropdown-content").toggleClass("apear");
});

Thanks

Answer №1

$(document).ready( function() {
    $(".commentdropdown .dropbtn").on("click", function(e){
      $(this).next('.dropdown-content').toggleClass("apear");
    });
});
.commentdropdown{
    float: right;
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
}

.apear{
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="commentdropdown pr-3">
    <button class="dropbtn btn p-0 m-0 bg-white">btn 1</button>
    <div class="dropdown-content">
        <a href="#">Edit 1</a>
        <a href="#">Delete 1</a>
    </div>

    <button class="dropbtn btn p-0 m-0 bg-white">btn 2</button>
    <div class="dropdown-content">
        <a href="#">Edit 2</a>
        <a href="#">Delete 2</a>
    </div>

   <button class="dropbtn btn p-0 m-0 bg-white">btn 3</button>
    <div class="dropdown-content">
        <a href="#">Edit 3</a>
        <a href="#">Delete 3</a>
    </div>
</div>

Give this a shot.

Answer №2

When the 'dropbtn' element is clicked, a function will toggle the 'appear' class on the nearest '.dropdown-content'.

Answer №3

When you mention the commentdropdown in the event handler, it enables clicking on the whole object along with all its children.

To simplify things, you can simply attach the event listener to the buttons themselves.

$(".dropbtn").click(function(){
    $(this).closest(".dropdown-content").toggleClass("apear");
});

Answer №4

Your code, $(".dropdown-content").toggleClass("apear"), toggles the class for all elements with the dropdown-content class. To fix this, target the closest element containing dropdown-content when clicked.

Try the following approach:

$(".commentdropdown").on("click", function(evt){
    $( event.target ).closest('.dropdown-content').toggleClass("apear");
});

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

What is the most efficient method for clearing the innerHTML when dealing with dynamic content?

Is there a more efficient method for cleaning the innerHTML of an element that is constantly changing? I created a function to clean the containers, but I'm not sure if it's the most efficient approach. While it works with the specified containe ...

In the world of React in Meteor, the command event.preventDefault() doesn't seem

I have encountered an issue with my application development. I am utilizing a submit form in Meteor with React, and although I am using event.preventDefault(), the page continues to reload every time the submit button is clicked. Following a brief delay, i ...

Is there a way to transform a stream fetched from an S3 bucket into a JPEG image for display on my React frontend?

I've been grappling with a frustrating issue that seems to have solutions scattered all over the internet. Despite spending two full days trying to crack it, I just can't seem to find the right answer. Here's the crux of my problem: I hav ...

What could be causing me to receive these PHP alerts: simplexml_load_string?

Currently in the process of developing a jQuery Translation Plugin, I encountered some performance issues with the initial array-based translation method. To optimize speed, I switched to translating one word at a time. Both approaches utilize ajax calls t ...

Tips for downloading a file using a Django function triggered by JavaScript instead of redirecting to the URL

Managing a page with multiple buttons that trigger various functions, such as sending an SMS (via API), emailing a file, or downloading a PDF. The button actions are powered by Ajax requests through JavaScript instead of using forms. I initially used Java ...

Guide to accessing child prop reference in Vue 3 using Element Plus UI library

I am encountering an issue with a dropdown component labeled 'dropdown' When selecting an item, I need to retrieve the selected label (not just the value) Currently, when using dropdown.value, I receive an object containing a key and its corres ...

Craft a hierarchical JSON structure out of a different nested JSON object [PAUSE]

Looking to transform an existing JSON object into a new object structure. Here is the current JSON object: { "name": "Parent", "children": [ { "name": "Child1", "children": [ { "name": "GrandC ...

Using Jquery Autocomplete? It functions seamlessly with Firefox 3.6 but encounters issues with Firefox 5 and Chrome

Upon running a test server, I noticed that the jQuery autocomplete feature works perfectly on Firefox 3.6 but not on Chrome or Firefox 5. Below is the HTML code being used: <html> <head> <title>Test Page</title> <script s ...

Retrieving information from two MySQL tables using jQuery EasyUI

Hello, I am new to using jquery easyui. I have created 3 files: project.php, projectdetail.php, and get_project_detail.php. Here is the code from project.php: ... ... <table id="dg" title="Next Target" class="easyui-datagrid" style="width:700px;heig ...

The PayPal JavaScript SDK button triggers a blank window with a #blocked URL when used in a Django template, but does not have the same issue

I've been grappling with an issue while trying to incorporate PayPal buttons into my Django website. Every time I attempt to do so, the PayPal popup window shows up as about:blank#blocked. In the console, I can see the following error: popup_open_erro ...

Animate as you scroll down and as you scroll back up

Trying to animate a set of buttons from a relative position to a fixed position on each scroll by. HTML <div class="menu"> <button class="button"></button> <button class="button"></button> </div> CSS .button ...

"electron-builder - initially designated for building app for Mac only, but now configured to build for both Mac

This is my first attempt at creating an electronjs app, so I may not have a full grasp on what I'm doing. I've been following the instructions on GitHub and also this guide from Medium. Here's a snippet of my package.json: { (package.jso ...

Polyfill failing to function properly

I'm currently in the process of developing my own starter framework. Check it out here Before anything else, I'd like to apologize for the extensive list of CDN plugins. Right now, my focus is on creating some custom CSS overrides for commonly u ...

Understanding the functionality of imports within modules imported into Angular

I have been scouring through the documentation trying to understand the functionality of the import statement in JavaScript, specifically within the Angular framework. While I grasp the basic concept that it imports modules from other files containing expo ...

The inconsistency between updating data in the model and its corresponding binding in the controller

I've been attempting to implement this specific approach in my application, but I'm encountering difficulties. CountriesModel.js app.service('CountriesModel', ['$http', function($http) { $http.get(baseUrl + 'api/co ...

There is a bug that I have encountered specifically on RN version 0.74

Everything was running smoothly in RN 0.73.7, but encountered an issue on Android when upgrading to RN 74 with the following error message: Error: Failed to create a new MMKV instance: React Native is not running on-device. MMKV can only be used when syn ...

Encountered CSRF validation error while working with a Python Django backend in conjunction with React frontend using Axios for making POST requests

I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function ...

What is the HTML code for a circumflex over a number in Unicode?

For adding a circumflex accent, also known as a "hat" (^) over the character before it, we can utilize Unicode U+0302, COMBINING CIRCUMFLEX ACCENT, or ̂ in HTML. For example, s&#x302; gives us ŝ ("s hat"). In the realm of music theory, this accent ...

Switch the alignment of Bootstrap checkboxes from vertical to horizontal

I'm looking to have my checkbox elements aligned horizontally instead of the default vertical alignment in bootstrap. To achieve this, I've added the following CSS code: .checkboxinsameline{ display:inline; } Here's the HTML structure ...

"An issue occurred with AJAX and jQuery resulting in a

Can someone take a look at this code with fresh eyes? The variable formPaymentData contains a JSON string of objects extracted from a form. I then created a partial list called _newData using some of the data from formPaymentData. This _newData was used f ...