Tips for switching a group of buttons within a userscript by clicking a single button?

Apologies if my wording is not clear, allow me to clarify.

I am in the process of developing a userscript that will display a set of buttons below a main button when clicked. These additional buttons will serve different functions and should disappear when the main button is clicked again, essentially creating a toggleable dropdown menu.

Here is a snippet of the current userscript:

// ==/UserScript==

var menuButton       = document.createElement ('div');
menuButton.innerHTML = '<button id="mainButton" type="button">'
                + 'Glass</button>'
                ;
menuButton.setAttribute ('id', 'myContainer');
document.body.appendChild (menuButton);

//Click listener
document.getElementById ("mainButton").addEventListener (
    "click", openStuff, false
);

function openStuff (zEvent) {
    /*--- Dummy action, just adds a line of text to the top
        of the screen.
    */
    var menuButton       = document.createElement ('p');
    menuButton.innerHTML = 'Clicked.';
    document.getElementById ("myContainer").appendChild (menuButton);
}
// Style
GM_addStyle ( `
    #myContainer {
        position:               absolute;
        top:                    0;
        left:                   0;
        font-size:              20px;
        z-index:                1100;
    }
    #mainButton {
        cursor:                 pointer;
    }
    #myContainer p {
        color:                  black;
    }
` );

At the moment, clicking the main button simply adds a transparent line of dummy text below it. I have limited experience with CSS and my JavaScript knowledge is mainly focused on Node.js, leaving me feeling quite lost. Any guidance or assistance would be greatly appreciated.

Answer №1

New update:

  1. You are now able to easily copy and paste the solution. We have included both the css and js code directly into the html file. The style tags are placed within the head section, while the script tag is positioned at the bottom just before the closing body tag.

  2. Let's take a closer look at the css and js.
    a) The height of the container is set to view height to demonstrate alignment.
    b) The display property is set to flex, which helps in easy element positioning and solving layout problems.
    c) Setting flex direction to column ensures that direct children flow down the column instead of across a row.
    d) justify-content:center aligns elements along the major axis, while align-items:center aligns them along the minor axis defined by flex-direction.
    e) Initially, #buttons display is set to none to hide it.
    f) #buttons.showme targets the element #button when it has the class .showme

The javascript code is fairly straightforward. The key point is buttons.classList.toggle("showme"); which toggles the class on click.

Feel free to reach out if you need further clarification or we can schedule a zoom call for a detailed walkthrough.

<!DOCTYPE html>
<html>
<head>
   <title>help</title>
   <style>
      #container {
         height: 100vh;
         display: flex;
         flex-direction: column;
         justify-content: center;
         align-items: center;
         border: solid 1px black;
         flex-direction: column;
      }

      #buttons {
         display: none;
      }

      #buttons.showme {
         display: block;
      }
    </style>
</head>
<body>

<div id='container'>
  <div>
    <button onclick='toggleMe()'>click me</button>
  </div>
  <div id='buttons'>

    <button onclick='dostuff(0)'>button 1</button>
    <button onclick='dostuff(1)'>button 2</button>

  </div>

</div>

<script>
function toggleMe() {

  var buttons = document.getElementById('buttons')
  buttons.classList.toggle("showme");
}

function dostuff(idx) {

  if (idx == 0) alert("button 1 action")
  else alert("button 2 action")
}
</script>
</body>
</html>

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

Calculating the number of days between two given dates, including both the start and end dates

I need to calculate the number of days between two dates, including both of the dates. My current method for this task is as follows: numDaysBetweenDates(startDate, endDate) { let millisecondsPerDay = 24 * 60 * 60 * 1000; return (endDate - startDate) ...

Display a hidden division when a radio button is selected using Javascript and Jquery

Currently, I am in the process of constructing a form that triggers a series of additional questions based on the selected answer. Below is my current working code snippet: $(".appliedWorked").click(function(){ if($(this).val()==="appliedWorkedYes") ...

Is full support for CSS 3D transforms (preserve-3d) provided by IE11?

Creating a web app utilizing css 3d transforms, my goal is to have IE11 support if feasible. I am aware that IE10 does not endorse the preserve-3d value for the transform-style css attribute, however, there seems to be conflicting information regarding I ...

What is the process of sending a file to a server and storing it in a MySQL database?

Currently, I am exploring the process of enabling users to upload images of specific dimensions (468px by 60px) to a designated directory on my server, such as example.com/banners. Subsequently, the URL link to these uploaded banners will be stored in a ...

What is the best way to maintain the toggleClass event state once an ajax call has been made?

If I have the HTML code below <div class="row"> <div class="link grey"> <a href="#">Link</a> </div> </div> <div class="row"> <div class="link"> <a href="#">Link</a> </div> & ...

Is it necessary to execute 26 individual mysql queries in order to group items alphabetically in a directory listing page?

I am looking to create a directory listing page for my website that displays all of my articles grouped by the first letter of their titles. Do I have to execute 26 MySQL queries like: mysql query like "SELECT * FROM articles Where title like 'a%&ap ...

Bring in JS into Vue from the node_modules directory

Apologies for my limited knowledge in this area, but I am currently working on integrating and importing This Grid System into my Vue project. However, I am facing some challenges. Typically, I import plugins like this: import VuePlugin from 'vue-plu ...

How to Convert Irregular Timestamps in Node.js?

Currently, I am utilizing an API to retrieve information from Google News and proceed to save the data in Firestore. The challenge lies in the fact that the API delivers timestamps in various formats which are not uniform. For example: "1 Day Ago", "June ...

Cut an image using CSS while maintaining its original quality

I am currently working on an upload page where users can upload images. Here is the link to the page: MyPage. However, I would like to implement image cropping functionality that displays more of the image rather than just a small portion as it does now. A ...

Strategies for detecting changes in multiple HTML select elements with jQuery

I currently have three select HTML tags and I would like to filter my table using the selected values (group of selected tags) with an AJAX request. For example, filtering by Gender, Location, and Season. My question is how can I achieve this without dup ...

Exploring the Vertical Metrics of Various Typeface Styles

I'm encountering a problem and struggling to find a solution. I'm in the process of creating a website and incorporating various fonts. My goal is to ensure that every font appears visually similar to the others and align perfectly at the base. ...

Show or conceal input fields depending on the selection of radio buttons

Hello everyone, I am new to JavaScript and currently learning. Can someone please assist me in fixing this code? The required inputs are: radio-button-1; radio-button-2; input-fields-set-1; input-fields-set-2; input-field-submit. My objective is: Upon ...

Running Jquery after the DOM has loaded in an Angular Js environment can be achieved by utilizing specific

When developing a single page application with Angular, I have implemented multiple views that load various page content. My goal is to set the initial focus on the first input element for all screens using an Angular script, instead of manually adding the ...

Add a sound file to the server and configure the images based on the server's response

I am a newcomer to JavaScript and AJAX, and I am facing an issue while trying to upload an audio file to the server and display the image from the server response. When attempting to pass the audio file from the input tag to an AJAX call, I encounter an il ...

Exploring the power of QueryTask in ArcGIS JS API 3 for running multiple queries

When using QueryTask in ArcGIS JS Api 3, I encountered a challenge where I needed to execute multiple queries in one call. After referencing the documentation, I realized that this functionality was not directly supported. This is my current implementatio ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

The application is resetting when the "$http" method accesses the initial ADAL "protected" URL for the first time

I have created a page inspired by the Angular SPA ADAL sample which can be found here Upon returning from the Microsoft login page and accessing my API secured with AAD, the angular .config() function is called multiple times. This causes issues with upda ...

When using jQuery, the script will execute successfully only when running it chunk by chunk in the console, rather than running the

As I tidy up an html page, my main task is to remove anchor tags and keep the text nodes. To achieve this, I am enclosing all text nodes (without any surrounding elements) within the <asdf> tag. Additionally, I am deleting empty elements such as < ...

Learn how to retrieve data prior to rendering with Vue 3 and the composition api

Is there a way to fetch data from an API and populate my store (such as user info) before the entire page and components load? I have been struggling to find a solution. I recently came across the beforeRouteEnter method that can be used with the options ...

The function $(this).addClass() seems to be malfunctioning

While trying to follow a tutorial, I noticed that the style sheet isn't being applied to the clicked element in the list. What could be causing this issue? In the example provided, when a string is added to the text box and the button is clicked, a n ...