Tips for maintaining an exposed dropdown menu in the following page?

I'm working with a dropdown that contains <a> tags and is initially set to be hidden. There's also a caret next to the dropdown that rotates down when the dropdown is open. What I'm trying to achieve is keeping the dropdown open (caret down) even after clicking an element inside it, and ideally have the selected element stay highlighted on the next page without using any form of storage like localStorage or Sessions. Can anyone provide some guidance or an example of how this could be accomplished?

<div class="client dropdownSideBar" id="cl">
    <button class="dropdown-btn font_24 font_white">
        CLIENT
    </button>
    <div class="dropdown-container" id="dropdown-menu">
        <a>Element1</a><br>
        <a>Element2</a><br>
    </div>
</div>

/* keep the caret aligned */
#cl .dropdown-btn::before {
    margin-left: 115px;
}
.dropdown-btn::before {
    display: inline-block;
    content: "\25BC"; /* caret content */
    transition: transform 0.3s;
    transform: rotate(270deg);
    float: right;
}
.dropdownSideBar.is-open .dropdown-btn:before {
    transform: rotate(-360deg);
    color: white;
}

.dropdownSideBar.is-open .font_white {
    background-color: #575757;
    width: 100%;
    color: white;
}
.dropdownSideBar.is-open .dropdown-container {
    display: block;
}
/* hidden by default, make the content shifts under the title */
.dropdown-container {
    display: none;
    font-size: 18px;
    padding-top: 10px;
    background-color: #575757;
}
.dropdown-container a {color: white; padding-left: 30px;}
.dropdown-container a:hover {background-color: #414141;}

Javascript code snippet for displaying the dropdown menu upon client click and ensuring only one dropdown is open at a time

var dropdown = document.getElementsByClassName("dropdown-btn");
var i;
var indexOfSelectedElement = window.location.pathname;

for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
    var dropdownContent = this.nextElementSibling;
    
    Array.from(document.querySelectorAll('.dropdown-container')).forEach(el => {
        //hide the nonclicked 
        if (el !== dropdownContent) {
            el.style.display = 'none';
        }
    });
    if (dropdownContent.style.display === "block") 
        dropdownContent.style.display = "none";
    else
        dropdownContent.style.display = "block";
  });
}
//get the three Dropdowns

const dropdowns = document.querySelectorAll(".dropdownSideBar");
dropdowns.forEach(el => {
    const button = el.querySelector(".dropdown-btn");
    button.addEventListener("click", () => {
        const caret = document.getElementById('caret');
        // Close all
        [...dropdowns].filter(x => x != el).forEach(el => el.classList.remove("is-open"));
        // Toggle one
        el.classList.toggle("is-open");
  });
});

Demo: https://jsfiddle.net/dgLfjxn2/ Update: I attempted to address this using the URL. The issue I'm encountering is that the caret rotation isn't happening, and when I click on the client, the after selector is being applied. However, I'm still not able to get the element selected once redirected to the new page.

var menu = document.getElementById('dropdown-menu');
var client = document.getElementById('clientButton');
var id = indexOfSelectedElement.substr(14, indexOfSelectedElement.lastIndexOf('/') - 14);
if(indexOfSelectedElement.substr(0, 14) === "/fleet/client/") {
    menu.style.display = 'block';
    menu.style.backgroundColor = '#575757';
    client.style.backgroundColor = '#575757';
    client.style.color = 'white';

    //TODO: keep the clicked client selected on the redirected page?, rotate the caret, when client is clicked again backgroundColor and caret are in the after selector.
}

Answer №1

It is recommended to include both href and id attributes in your anchor tag, like so:

<div class="client dropdownSideBar" id="cl">
    <button class="dropdown-btn font_24 font_white">
        CLIENT
    </button>
    <div class="dropdown-container" id="dropdown-menu">
        <a href="/destination/?item=element1" id="element1">Element1</a><br>
        <a href="/destination/?item=element2" id="element2">Element2</a><br>
    </div>
</div>

When on the /destination/ page, make sure to incorporate your CSS and JavaScript code along with the following steps:

var url_string = window.location.href;   // obtain the URL
var url = new URL(url_string);
var menuItem = url.searchParams.get("item"); // fetch the item parameter value

// retrieve the anchor element that was clicked on the previous page
var a = document.querySelector('#' + menuItem);
// locate and click the associated button to open the dropdown menu and rotate caret
a.closest('dropdownsidebar').querySelector('button').click();
// Lastly, apply a class for styling the selected menu item
a.className += " item-selected";

As an example:

.item-selected {
   background-color: '#575757',
   color: 'white'
}

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 could be causing the col-md class to not work within a Bootstrap 4 card element?

Please be aware that I specialize in development, not design. My goal is to split a card div into two columns for desktop view. The text "This should be in Left Side" should be positioned on the left side, while "This should be on right side" should be on ...

What is the best way to show the response data in an input text field within an HTML form?

I'm new to working with node.js and I've encountered an issue. I need to display the data of the currently logged in user in input fields. With the following code, I can access the data of the logged-in user and display it on the console: See O ...

Transfer a GET parameter from the URL to a .js file, then pass it from the .js file to a

Hey there, I'm currently using a JavaScript file to populate my HTML page with dynamic data. The JS file makes a call to a PHP file, which then fetches information from my SQL database and echoes it as json_encode to populate the HTML page. The issue ...

Attempting to configure a webhook eventsub through the Twitch API by utilizing ngrok as the intermediary

After triggering a test event using the Twitch CLI, an error response was received indicating: Post "https://1562-5-182-32-19.ngrok.io/api/twitch/eventsub/": context deadline exceeded (Client.Timeout exceeded while awaiting headers). The notification even ...

It appears that React is not successfully transferring props to another component

Recently, I decided to follow a tutorial on creating a React application. However, I encountered a peculiar issue that has left me scratching my head. The problem arises when I attempt to pass data from one component to another. Despite successfully passi ...

Tips for aligning a `img` element with absolute positioning within a `div` element while preserving its original aspect ratio

Here is an image along with its corresponding CSS: .containerImg { height: 420px; margin-top: 0; position: relative; width: 100%; } .img { margin: 0 auto; position: absolute; /*I cannot remove the position:absolute unfort ...

Rows nested within the Bootstrap grid system

Looking to implement a nested grid within a parent grid in Bootstrap 3.3.7. Check out the HTML below: Parent component <div> <div class="row"> <div class="col-md-3 border">.col-md-3</div> // <div class="col-md-9 ...

Utilizing Typescript Generics in Arrow Function to Combine Two Arguments

For instance, I am working with this code in a .tsx file extension const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1; const A = Add(1, 2); const B = Add('1', '2') However, I am encountering an issue, as there is an error m ...

Is it possible to incorporate shadows on a pie chart using recharts?

Does anyone know how to enhance a pie chart with shadows using the recharts library? https://i.sstatic.net/JLGVF.png https://i.sstatic.net/f5qv4.png If you have any solutions, please share. Thank you! ...

Which Angular2 npm packages should I be installing?

When I'm trying to create an empty app without using angular-cli, it's really difficult for me to figure out which packages or libraries to include. Searching for angular2 on npmjs yields unwanted results, forcing me to click through multiple li ...

Universal CSS styling for scrollbar design across platforms

I'm feeling extremely frustrated right now because I can't seem to create a basic scroll bar with a specific color and thickness that will display properly on various web browsers and smartphones. Are there any resources available to help me fig ...

Invoke the onClick function within a setInterval loop

My onClick function is functioning correctly. However, I want to run it periodically using setInterval after it's been triggered by a click event. Here's my attempt at modifying the code: var clickData; var isClicked=0; function onCl ...

I'm a bit torn between using images for text or utilizing Google Fonts

I am looking to use a unique font that is not commonly used. This font is available in Google Fonts as well as in Photoshop. I am unsure about which method to choose because both options involve some loading time. Although using images for text is not idea ...

Eliminate the AM and PM options from the input time selection dropdown menu in HTML

https://i.sstatic.net/wKeQk.png Is it possible to eliminate the AM / PM option from the input time format dropdown? The form builder currently uses a 24-hour format that includes the AM / PM field. ...

Difficulty encountered when utilizing an if statement within a function

I have encountered a simple issue while using an if statement within a function. The following code is working as intended: <!DOCTYPE html> <html> <body> <h1>Typewriter</h1> <button onclick="typeWriter()">Click me& ...

What is the process for altering the image on a jQuery mobile a href button?

Is it possible to use a custom image instead of a normal rectangular shape for a jquery mobile button? I'm looking for references on how to do this. The code below is an example of what I want. Here is an example of a normal button: <a data-role= ...

Guide to fetching and displaying a complex array API using JavaScript's fetch method

Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API: fetch('https://datausa.io/api/data?d ...

The child divs are not adjusting to the height of the parent container

My goal is to have the height of the children div .cell fill up 100% of the parent's height, but it doesn't seem to be working. This is the HTML code: <div class="header"> header </div> <div class="wrapper"> <di ...

Eliminating gaps between elements

I recently delved into the world of web design, and although I have a basic understanding of HTML and CSS, I am determined to enhance my skills and knowledge by creating a standard home page. So far, I managed to create a standard navigation bar, and now ...

Using Angular 2: Exploring the power of observables for broadcasting events during a forEach loop

Upon testing the service within a forEach loop, I noticed that the parameter I passed to the service ended up being the last one in the iteration. I initially suspected that the issue was due to closures, so I attempted using an anonymous function to add ...