Implementing JavaScript to assign unique IDs to several elements - a step-by-step guide

I've been struggling to find a solution to my problem despite days of research. After stumbling upon a similar Stack Overflow question (GetElementByID - Multiple IDs), I still can't seem to implement the solution into my code even after numerous attempts and variations. [DEMO]. Despite asking for help multiple times, I keep receiving vague responses that don't provide any real assistance. The main issue at hand is: How do I create multiple IDs in the script to carry out different open-transitions?

 /*!
  * classie - class helper functions
  * classie.has( elem, 'my-class' ) -> true/false
  * classie.add( elem, 'my-new-class' )
  * classie.remove( elem, 'my-unwanted-class' )
  * classie.toggle( elem, 'my-class' )
  */

 /*jshint browser: true, strict: true, undef: true */
 /*global define: false */

 (function (window) {

     'use strict';

     // class helper functions from bonzo https://github.com/ded/bonzo

     function classReg(className) {
         return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
     }

     // classList support for class management
     // although it sucks because it only accepts one class at a time
     var hasClass, addClass, removeClass;

     if ('classList' in document.documentElement) {
         hasClass = function (elem, c) {
             return elem.classList.contains(c);
         };
         addClass = function (elem, c) {
             elem.classList.add(c);
         };
         removeClass = function (elem, c) {
             elem.classList.remove(c);
         };
     } else {
         hasClass = function (elem, c) {
             return classReg(c).test(elem.className);
         };
         addClass = function (elem, c) {
             if (!hasClass(elem, c)) {
                 elem.className = elem.className + ' ' + c;
             }
         };
         removeClass = function (elem, c) {
             elem.className = elem.className.replace(classReg(c), ' ');
         };
     }

     function toggleClass(elem, c) {
         var fn = hasClass(elem, c) ? removeClass : addClass;
         fn(elem, c);
     }

     var classie = {
         // full names
         hasClass: hasClass,
         addClass: addClass,
         removeClass: removeClass,
         toggleClass: toggleClass,
         // short names
         has: hasClass,
         add: addClass,
         remove: removeClass,
         toggle: toggleClass
     };

     // transport
     if (typeof define === 'function' && define.amd) {
         // AMD
         define(classie);
     } else {
         // browser global
         window.classie = classie;
     }

 })(window);


 /**
  * main.js
  * http://www.codrops.com
  *
  * Licensed under the MIT license.
  * http://www.opensource.org/licenses/mit-license.php
  * 
  * Copyright 2014, Codrops
  * http://www.codrops.com
  */ (function () {

     var bodyEl = document.body,
         content = document.querySelector('.content-wrap'),
         openbtn = document.getElementById('open-button'),
         closebtn = document.getElementById('close-button'),
         isOpen = false;

     function init() {
         initEvents();
     }

     function initEvents() {
         openbtn.addEventListener('click', toggleMenu);
         if (closebtn) {
             closebtn.addEventListener('click', toggleMenu);
         }

         // close the menu element if the target isn't the menu element or one of its descendants..
         content.addEventListener('click', function (ev) {
             var target = ev.target;
             if (isOpen && target !== openbtn) {
                 toggleMenu();
             }
         });
     }

     function toggleMenu() {
         if (isOpen) {
             classie.remove(bodyEl, 'show-menu');
         } else {
             classie.add(bodyEl, 'show-menu');
         }
         isOpen = !isOpen;
     }

     init();

 })();

Despite having some insights,

 var bodyEl = document.body,
         content = document.querySelector('.content-wrap'),
         openbtn = document.getElementById('open-button'),
         closebtn = document.getElementById('close-button'),
         isOpen = false;

You will notice two sets of gray dots on the page, with each set opening different boxes when clicked. Instead of this behavior, I want the first set of dots to only open the first box and the second set to open the second box, without any overlap. It seems like modifying the JavaScript portion mentioned above could solve this issue, but I'm unable to make it work. Can someone with expertise guide me through this process? Please provide a straightforward solution without unnecessary explanations.

I am in desperate need of assistance as I've encountered lengthy responses with no clear resolution. This task should be simple for those experienced in the field, and I believe there is a proven solution!

Answer №1

It's important to note that this platform is for asking and answering questions, not for requesting others to write code for you. Using all caps to demand assistance will not be effective in getting the help you need.

That being said, there are a few issues in your code that need addressing. Firstly, having buttons with the same ID trying to open different elements without IDs can cause conflicts. Make sure each button has a unique ID and assign different click functions to them. Alternatively, you can pass the ID of the element to toggle using the same method. The click function should modify the class of the specific menu-wrap element identified by its own unique ID.

Another problem lies in your CSS code, which modifies the body's class to show/hide the menu. It would be better to adjust the class of the individual element you want to display or hide.

If you'd like to see an improved version of your code, check out this link. While it may not be perfect, it can give you some guidance on what needs to be done. Additionally, consider cleaning up your code and exploring the use of jQuery, as it can be more user-friendly for beginners.

Answer №2

Utilizing .show-menu .menu-wrap{...} to reveal the divs, clicking on the gray dots applies the class .show-menu to the body causing both divs to be affected by the style .show-menu .menu-wrap since they are within the body.

To rectify this issue, wrap them in a parent element and toggle the class .show-menu on the parent of the gray dot element that is clicked as shown below:

$(".menu-button").click(function () {
    $(this).parents(".wrapper").toggleClass("show-menu");
});
// CSS code here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div class="wrapper">
        <button class="menu-button">Open Menu</button>
        <div class="menu-wrap"></div>
    </div>
    <div class="wrapper">
        <button class="menu-button" style="
    top: 560px;
">Open Menu</button>
        <div class="menu-wrap" style="
    top: 700px;
"></div>
    </div>
</body>

If you prefer not to modify your markup, simply toggle the class .show-menu directly on .menu-wrap, adjusting the selector accordingly as demonstrated below:

$(".menu-button").click(function () {
    $(this).next(".menu-wrap").toggleClass("show-menu");
});
// CSS code here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <button class="menu-button">Open Menu</button>
    <div class="menu-wrap"></div>
    <button class="menu-button" style="
    top: 560px;
">Open Menu</button>
    <div class="menu-wrap" style="
    top: 700px;
"></div>
</body>

The examples provided above serve as a guide, where the implementation can be done in pure JavaScript but using jQuery is recommended for easier handling.

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

Retrieve the folder and file name selected by the user in the browser

Can the client's directory path be obtained for a file uploaded to a server? ...

Analyzing the structure according to the month/week/year

My array consists of count and date values: day = [ { count: 1, date: '2022-07-07' }, { count: 1, date: '2022-08-14' }, { count: 2, date: '2022-07-19' }, { count: 4, date: '2022-07-19' }, { count: 2, date: ...

Condition for button functionality

I have a Submit button that, when pressed, triggers the onSubmit function. <b-form @submit.stop.prevent="handleSubmit(onSubmit)"> ... <b-button type="submit" >Submit</b-button> <script lang="ts ...

"Clicking on one item in the Bootstrap submenu doesn't close the other items,

I have this Javascript code snippet that deals with expanding and collapsing submenu items: <script type="text/javascript> jQuery(function(){ jQuery(".dropdown-menu > li > a.trigger").on("click",function(e){ var current ...

"Exploring the realms of AngularJS through callback functions and variable scopes

I am currently experiencing an issue with JavaScript in general. Specifically, I am trying to update a list after invoking a callback from two separate files. Here is the description of the callback : this.modify = function(){ var self = this; v ...

Incorporate a new item into a JSON file using Node.js

I need assistance with adding new objects to a JSON file in Node.js, but only if the id does not match an existing object. Below is my current code: sample JSON file: [ { id:123, text: "some text" }, { id:223, text: "som ...

Import the JSON data into the designated storage unit

$(".btn-primary").click(function(){ runSuccessFunction(jsonObj); }); If I need to update the JSON data in the JSFiddle Code example, how can I reload only the container by clicking a button? I want to run the code every time I make a change to the J ...

Modify the color of the menu in OpenCart 1.5.6.4 to give it a fresh

In the default theme of OpenCart 1.5.6.4, I am looking to change the background color of the dropdown menu which is currently defined by the background image 'menu.png' to a custom hex value. The CSS code for this section is shown below: #menu & ...

Getting duplicate tokens for multiple users while utilizing Firebase messaging

When attempting to acquire a token from firebase, I employ the code snippet provided below: const messaging = firebase.messaging(); messaging.requestPermission() .then(() =>{ return firebase.messaging().getToken(); }).then(token => { s ...

Updating the label on a Highcharts speedometer gauge

I need to customize the number sequence of a speedometer displaying internet bandwidth speed. I have done extensive research but haven't found a solution yet. Below is the code snippet for the highchart gauge. The current label sequence is 0,10,20,30 ...

Is it possible to include padding within a textarea element?

Is it possible to add some left margin inside a textarea? I would like there to be some extra space because I am using an image icon as my button within the textarea, and when I type, the words end up covering the image. <div id="inputBox"> < ...

Three.js - Display a model with material that can be visible without the need for a light source

I am currently utilizing Three.js, specifically version 71. My workflow involves creating models in Blender, exporting them as JSON files, and then using THREE.JSONLoader to incorporate these models into my scene as shown below: this.jsonLoader.load(path ...

Google Maps JavaScript API Version 2 - jQuery plugin for converting numbers to words

I am encountering an issue with my Google Maps project where I am using jQuery. I am fetching a number from a PHP array and looping through it to translate the number into a word. For instance, if I receive the number 1 from the array, I would like to disp ...

Retrieve the parent document information even when the subdocument array is filtered out

I have implemented the solution provided in this post How to filter array in subdocument with MongoDB The method works correctly, except for cases where none of the elements in the array pass the test. In such situations, I end up with an empty array with ...

How about using a JQuery variable?

I'm a beginner in jQuery and I have this code snippet that displays a div when a specific link on a map is hovered over: <div id="locationmap"> <a class="linkhide" id="link1" href="#">Occupier 1</a> <a class="linkhide" id ...

Placing a table within a div causes the div to expand in width beyond 100%

A situation has arisen where a table with a large number of columns (30 columns) is being affected by the white-space:nowrap style set on each th tag, causing the parent div to stretch unnaturally. How can this issue be resolved and allow for a horizonta ...

What exactly is the significance of the </< in THREE.Camera.prototype.lookAt</<()?

After experimenting with THREE.js for a while, I came across something peculiar: When using Firefox and opening the developer console to type camera.lookAt (assuming your camera is named camera), it displays function THREE.Camera.prototype.lookAt</< ...

Adjusting the gaps between each item in a list

Currently, I am working on developing a minimalist single-page website. However, I am facing challenges with spacing in the navbar section (as demonstrated below). When using an unordered list, everything looks good until the list overlaps with the centra ...

Can you point me in the right direction to find the Configure function within the EasyRTC module for

As a newcomer to NodeJS, I may be getting ahead of myself, but I'm diving into running the EasyRTC demo with NodeJS. On the EasyRTC download page, there are "easy install instructions" that outline the steps required to get EasyRTC up and running smo ...

Generate random DOM element exchange (without using jQuery)

My JavaScript code is designed to randomly swap HTML elements like images or paragraphs. The swapping of positions is working, but I've encountered a strange bug that I can't seem to explain. In the example HTML provided, there are only 2 paragra ...