What is the best way to display identical dropdown menus for multiple div elements on a single page?

I am new to asp.net and programming in general (this is my first question so please be patient with me).

I have encountered an issue with my initial project. The page contains multiple tiles, each following the same style. I want to include a dropdown menu with CRUD options (View, Update, Delete) on each tile. However, the problem arises when clicking the menu button - the dropdown menu always shows up on the first tile, regardless of where I click. I am looking for a way to display the menu on the specific tile I clicked on, enabling actions only on that particular element.

HTML:

<div class="tile-menu-dropdown">
    <button onclick="tileMenu()" class="tile-menu-btn">
        <i class="fas fa-ellipsis-v fa-2x" style="pointer-events: none;"></i>
    </button>
    <div id="tile-menu" class="tile-menu-content">
        <button>View</button>
        <button>Edit</button>
        <button>Delete</button>
    </div>
</div>

CSS:

.tiles .tile .tile-menu-btn {
            position: absolute;
            z-index: 1;
            width: 50px;
            height: 50px;
            text-align: right;
            top: 0;
            right: 0;
            padding-top: 14px;
            padding-right: 14px;
            background: none;
            border: none;
            outline: none;
            font-size: 16px;
            color: #ffffff;
            transition: 0.3s;
            transition-property: color;
            cursor: pointer;
        }

            .tiles .tile .tile-menu-btn:hover {
                color: #cd42e9;
            }

.tile-menu-content {
    display: none;
    position: absolute;
    background: #2F323A;
    min-width: 80px;
    border: 2px solid #cd42e9;
    z-index: 1;
    border-radius: 5px;
    right: 0;
    top: 50px;
}

    .tile-menu-content button {
        background: none;
        border: none;
        outline: none;
        width: 100%;
        color: #ffffff;
        padding: 12px 16px;
        text-decoration: none;
        text-align: left;
        font-size: 17px;
        font-weight: 500;
        font-family: 'Lato', sans-serif;
        display: block;
    }

        .tile-menu-content button:hover {
            color: #cd42e9;
            background: #22242A;
        }

.show {
    display: block;
}

JavaScript:

function tileMenu() {
    document.getElementById("tile-menu").classList.toggle("show");
}

window.onclick = function (event) {
    if (!event.target.matches('.tile-menu-btn')) {
        var dropdowns = document.getElementsByClassName("tile-menu-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }
}

Answer №1

When selecting an element using the Id, if there are multiple elements with the same Id, it will always point to the first one.

To target a specific element, you can begin searching from the element that triggered the event.

<div class="tile-menu-dropdown">
    <button onclick="tileMenu(this)" class="tile-menu-btn">
        menu1
    </button>
    <div id="tile-menu" class="tile-menu-content">
        <button>View</button>
        <button>Edit</button>
        <button>Delete</button>
    </div>
</div>

<div class="tile-menu-dropdown">
    <button onclick="tileMenu(this)" class="tile-menu-btn">
        menu2
    </button>
    <div id="tile-menu" class="tile-menu-content">
        <button>View2</button>
        <button>Edit2</button>
        <button>Delete2</button>
    </div>
</div>

JavaScript:

<script>
    function tileMenu(element) {
        clearMenuStatus();
        element.nextElementSibling.classList.toggle("show");
    }

    window.onclick = function (event) {
        if (!event.target.matches('.tile-menu-btn')) {
            clearMenuStatus();
        }
    }

    function clearMenuStatus() {
        var dropdowns = document.getElementsByClassName("tile-menu-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }
</script>

Result:

https://i.sstatic.net/OtOca.gif

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

Using jQuery to create a dynamically moving div that forms an endless wall

In order to create a continuous wall that pulls text from a database and displays it, I've developed the following code: $(function() { var x = 0; var y = 100.0; var z=0; setInterval(function() { x -= 0.1; y -= 0.1; ...

Utilize Vus.js 2.0 in conjunction with Laravel 5.4 to pass an object to the application and allow for its global usage

How can I efficiently load the authenticated user and access it across all my Vue components without making unnecessary AJAX requests, as I can directly fetch it from the back-end? In my Laravel home.blade.php file, I have a reference to a Vue app and att ...

Vue text failed to display the variable. Any ideas on why?

While working with a library, I encountered the issue of having "Close {{myVar}}" displayed on the screen. Can anyone guide me on how to use template literals in Vue? I have experience with React JSX. <template> <a-alert message="Info Tex ...

Substitute using JQuery

Hello, I am attempting to update some html using Jquery, here is my current progress. $(".old").html($(".new").html()); It's almost working. The problem is that the .new content is being copied instead of replaced. I want to Cut/Paste instead of Co ...

Ways to showcase corresponding information for an item contained within an array?

I'm working with a function that is designed to retrieve specific descriptions for objects nested within an array. The purpose of the function (findSettings()) is to take in an array (systemSettings) and a key (tab12) as arguments, then use a switch s ...

Ways to eliminate the Vuetify append-icon from the sequential keyboard navigation

In my Vue.js application using Vuetify, I have implemented a series of password fields using v-text-field with an append-icon to toggle text visibility. Here is the code snippet: <v-text-field v-model="password" :append-icon="show1 ? 'mdi-eye& ...

Animating borders with jQuery

Attempting to add animation to a button click using borders and jQuery animate function. jQuery( '#sendForm' ).hover( function (){ jQuery( this ).animate({ borderTopWidth: "5px", borderBottomWidth: "0px" }, 'fast&apo ...

Execute a task prior to invoking a different task

I'm currently working on an image slider that has some interactive features. Here's how it functions: When a user clicks on an image, it slides and comes to the front. On the next click, the image is flipped and enlarged. Then, on another click ...

Obtain the contenteditable span's value

I'm facing an issue with a content editable span - I want to extract its value when the post button is clicked, but it's not working as expected. Please note that I am unable to convert the span to a textbox or div, I specifically need the value ...

Leveraging JavaScript for setting an ASP.net Dropdownlist

I have made several attempts to set the dropdownlist without success. Despite observing the selectedIndex changing appropriately in developer tools, and noticing the selected option node change from false to true, the dropdownlist still displays the first ...

Angular $watch not working as expected

I have a specific directive code: .directive('myDirective', function(){ 'use strict'; return { restrict: 'A' , link: function(scope, element, attrs) { var count = 0; function d ...

Show text using AJAX when the form is submitted

I'm in the process of creating a basic form with a submit button (see below). My objective is to allow users to enter text into the input box, click submit, and have the page refresh while displaying the entered text in a div element. The user's ...

Create a custom div by clicking a button

I have been working on a fun web project where users can click a button to add sticky notes to a page. Here is the HTML code for a single sticky note: <div class="sticky_note"> <div class="title"> <input type="text" name="title" ...

What steps can I take to troubleshoot the 'Uncaught DOMException: failed to execute add on DOMTokenList' error?

I am looking to create media icons <div class="contact"> <span> <i class="fa fa-phone"></i> </span> <span> <i class="fa fa-facebook"></i> </spa ...

Try incorporating a variety of colors to enhance the appearance of your paper-menu in Polymer 1

I'm currently working on creating a customized menu using Polymer 1.0. This is how my menu structure looks like: <paper-menu> <template is="dom-repeat" items="{{menu}}" as="item"> <paper-item> <div>{{item.title}}</div& ...

Transferring Shadertoy creations into Three.js

Embarking on my coding journey, I have completed some online courses and dabbled in three.js experiments. Now, I am eager to dive into the world of Shaders. Discovering Shadertoy.com has been eye-opening with its plethora of mesmerizing experiments and ef ...

Discover past stock prices on Yahoo Finance

I'm stuck on tweaking a functioning jfiddle example that I have. Can anyone help me with this two-part question regarding the jfiddle: http://jsfiddle.net/maxmillien/qPVSy/ Part 1) Is there a way to clear the search each time a new search is performe ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

AngularJS Firebase Login Scope Value Not Retained After Refresh

I have stored my unique username in the variable "$scope" and I am trying to access it from different views once the user logs in, using: However, when I refresh the page immediately after the user successfully signs in, the value of "$scope" goes bac ...

Using a Proxy in C# WebBrowserControl and Making Calls from Javascript to C#

In my project, I successfully merged the capabilities of webbrowsercontrol ObjectForScripting to invoke C# functions from JavaScript, as explained in this source. Additionally, I utilized a proxy for the webbrowser control, following the guidance provided ...