Step-by-step guide on activating dropdown using a distinct button in a Stack Overflow code snippet

When attempting to run a code snippet by using the "Run code snippet" button and then clicking the "Open menu" button, nothing happens. However, it should open the menu as expected.

The menu is defined elsewhere in the DOM, and its display property is set to none.

Is there a way to execute this code snippet from this current page?

function xonclick() {
  const dropdownButton = document.getElementById('settingsDropDown');
  const dropdownMenu = document.getElementById('seadedMenyy');
  const clickedButton = document.getElementById('grid_muu');

  // Get current dropdown instance
  const existingDropdown = bootstrap.Dropdown.getInstance(dropdownButton);

  // Toggle behavior
  if (existingDropdown) {
    existingDropdown.dispose();
    dropdownMenu.classList.remove('show');
    return;
  }

  // Get precise button position
  const rect = clickedButton.getBoundingClientRect();
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;

  // Set position with scroll offset
  dropdownMenu.style.position = 'absolute';
  dropdownMenu.style.left = `${rect.left}px`;
  dropdownMenu.style.top = `${rect.bottom + scrollTop}px`;

  // Create and show new dropdown instance
  const dropdown = new bootstrap.Dropdown(dropdownButton);
  dropdown.show();
}
.dropdown-menu {
  margin: 0 !important;
  padding: 0.5rem 0;
  transform: none !important;
}

#settingsDropDown {
  position: fixed;
  visibility: hidden;
  pointer-events: none;
}
<head>
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e0c01011a1d1a1c0f1e2e5b405d405d">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87e5e8e8f3f4f3f5e6f7c7b2a9b4a9b4">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body>
  <div class="dropdown">
    <button id="settingsDropDown" class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
  Dropdown button
</button>
    <ul class="dropdown-menu" id="seadedMenyy">
      <li><a class="dropdown-item" href="#">Action</a></li>
      <li><a class="dropdown-item" href="#">Another action</a></li>
      <li><a class="dropdown-item" href="#">Something else here</a></li>
    </ul>
  </div>

  <table>
    <tr>
      <td>Some text</td>
      <td><button id="grid_muu" onclick="xonclick()">Open menu</button></td>
    </tr>
  </table>
</body>

Answer №1

Minimize the navigation menu and enable toggling it with a button

const dropdownButton = document.getElementById('settingsDropDown');
const dropdownMenu = document.getElementById('seadedMenyy');
const clickedButton = document.getElementById('grid_muu');

clickedButton.addEventListener('click', () => {

  // Check if the menu is already open, close it
  const isMenuOpen = dropdownMenu.style.display === 'block';
  if (isMenuOpen) {
    dropdownMenu.style.display = 'none';
    dropdownMenu.classList.remove('show');
    return;
  }

  // Determine precise position of the button
  const rect = clickedButton.getBoundingClientRect();
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;

  // Set position considering scroll offset
  dropdownMenu.style.position = 'absolute';
  dropdownMenu.style.left = `${rect.left}px`;
  dropdownMenu.style.top = `${rect.bottom + scrollTop}px`;

  // Display the dropdown menu
  dropdownMenu.style.display = 'block';
  dropdownMenu.classList.add('show');
});
document.addEventListener('click', (event) => {
  // Close menu if click occurs outside menu or button
  if (!dropdownMenu.contains(event.target) && !clickedButton.contains(event.target)) {
    dropdownMenu.style.display = 'none';
    dropdownMenu.classList.remove('show');
  }
});
// Handle click event on dropdown menu items
dropdownMenu.addEventListener('click', (event) => {
  if (event.target.matches('.dropdown-item')) {
    dropdownMenu.style.display = 'none';
    dropdownMenu.classList.remove('show');
  }
});
.dropdown-menu {
  margin: 0 !important;
  padding: 0.5rem 0;
  transform: none !important;
  display: none;
  /* Default hide state */
}

#settingsDropDown {
  position: fixed;
  visibility: hidden;
  pointer-events: none;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="27454848535453554657671209140914">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e88a87879c9b9c9a8998a8ddc6dbc6db">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>


<div class="dropdown">
  <button id="settingsDropDown" class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
      Toggle Dropdown
    </button>
  <ul class="dropdown-menu" id="seadedMenyy">
    <li><a class="dropdown-item" href="#">Action</a></li>
    <li><a class="dropdown-item" href="#">Another action</a></li>
    <li><a class="dropdown-item" href="#">Something else here</a></li>
  </ul>
</div>

<table>
  <tr>
    <td>Additional text to showcase</td>
    <td><button id="grid_muu">Access Menu Items</button></td>
  </tr>
</table>

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

unable to use redirect feature for specific URLs with nodejs module

I have been using the request nodejs module to retrieve HTML content from websites. However, I have encountered issues with certain redirection websites, as shown below: var request = require('request'); var options = { url: "http://www.amw ...

The functionality of a JQuery post within a PHP loop is not functioning optimally

I am encountering an issue with my list.php file, which generates a list with items and a button (Erledigt!) that triggers a jQuery Post to wishdelete2.php. The problem is that the jQuery post sometimes requires multiple clicks (3x or 5x) before it process ...

Trouble arises when dynamic parameters fail to function post building in Nuxt

In my Nuxt project set to "spa" mode, I am facing an issue with a URL containing a dynamic parameter /shop/:product, which could have various values such as: /shop/ipad-128gb-rose-gold /shop/subway-gift-card /shop/any-string and so on. This ...

The code is functioning properly, however it is returning the following error: Anticipated either

Can you explain why this code is resulting in an unused expression error? <input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e =>{(e.key ==='En ...

Leveraging Multiple MongoDB Databases in Meteor.js

Can 2 Meteor.Collections fetch data from separate MongoDB database servers? Dogs = Meteor.Collection('dogs') // mongodb://192.168.1.123:27017/dogs Cats = Meteor.Collection('cats') // mongodb://192.168.1.124:27017/cats ...

Using Google App Script for Slides to center-align text within a text box

Currently, I am tackling a project that demands the center alignment of text within a textbox on a google slide using a google app script. The primary objective is to fetch text from a google worksheet and an image from google drive. Subsequently, combine ...

What is causing my Angularjs View to not update upon clicking, even though I am successfully retrieving the content?

<div class="example" ng-controller="Ctrl"> <div ng-repeat="item in items"> <button ng-click="removeItem(item.id);">remove</button> <div class="element" id="{{itemId}}"></div> </div> <div> var a ...

Utilizing Vue to Embed Multiple Hubspot Forms on one Page

While working on a Vue page, I encountered an issue with loading multiple Hubspot forms simultaneously. Only one form would load at a time. Here is the code snippet I used to append a single Hubspot form: mounted() { const script = document.createElem ...

JQUERY inArray failing to find a match

I'm at my wit's end working with inArray and I'm really hoping for some help. I am using AJAX to fetch userIDs from my database, which come through as a JSON-encoded array. However, no matter what I try, I always get a -1 when trying to mat ...

Identifying particular text patterns in JavaScript using regular expressions

disclaimer - brand new to regular expressions.... I'm facing a challenge with a string that looks like this: subject=something||x-access-token=something The task at hand is to extract two specific values: Subject and x-access-token. To get starte ...

What is the best way to make my navbar banner stretch below the navbar row?

I am in the midst of rebuilding a website and making the switch from Bootstrap 3.3 to Bootstrap 5. During this transition, I am trying to replicate the navbar design found on this page. While I have made progress in aligning the look and feel, I am facing ...

The operation has stopped with error code 1 due to an unhandled error. The error message states: "Unauthorized access for user ''@'localhost' (without password) in express js."

After numerous attempts at debugging, the error persists. However, when I don't debug, everything seems to work fine. I've tried all the solutions I could find, but nothing seems to be working. Any suggestions would be greatly appreciated. The ...

Exploring a dynamic approach to cycling through a list of JSON objects within React

When I make an API call, I receive an array of JSON objects as a response. An example of the data structure is: [ {"id": 1, "name": "Pete", "age": 22}, {"id": 2, "name": "Sarah", "age": 32}, {"id": 3, "name": "Marshall", "age": 33} ] I am attemptin ...

Tips for creating nested child routes in AngularJS 2 with ID:

Here is a Demo of what I'm working on. Just getting started with angularjs 2 and trying to figure things out. I want to display Twitter names that correspond to certain names using routes on the same page, specifically utilizing a second <router- ...

Tips for accessing array or JSON data with ReactJS

As a novice with the MERN stack, I have set up my express app to run on port 3001 with a dbconn route. When I access "localhost:3001/dbconn," it displays the docs array successfully. const mongoose = require('mongoose') const MongoClient = req ...

Login should only be tried when the error code is 403

I have encountered an issue with checking if the API token is expired. The process involves making a GET call, and if a 403 error is received from the API, then re-login is required. This is what I tried: app.get = async (body) => { return new Pro ...

What is the best way to insert an Image or DIV while playing an HTML 5 Video, similar to a Youtube Advertisement?

I'm currently using the MediaElement.js HTML 5 Video Player and I am interested in incorporating advertisements similar to those seen on Youtube. Specifically, I would like the advertisement to appear over my videos during specific intervals (for exam ...

Investigating Javascript compatibility problems with Firefox 4

In FF3.X and IE7 to 9, the code below is functioning correctly, but in FF4, there seems to be an issue. The following code is used in two different locations within my file: var args = "method=getoptions"; args += "&dr ...

Hinting the type for the puppeteer page

I am trying to type hint a page variable as a function parameter, but I encountered a compilation error. sync function than_func(page:Page) ^ SyntaxError: Unexpected token: ...

The React component fails to update even after altering the state in the componentDidMount lifecycle method

I've been working on a React component that displays a table with data retrieved from an API on the server. Here's the code snippet: var ModulesTable = React.createClass({ getInitialState: function () { return { module ...