What is the best way to create a collapsible div element?

I was trying to create a collapsible div that functions like a <select> element. However, I encountered an issue because you cannot insert an <img> into an <option>.

My goal was to mimic a "language selection" box similar to this example: https://i.sstatic.net/TpUSP.png

Unfortunately, when I click on the dropdown box in my replica, the different languages do not pop up as expected. The div does not expand or collapse.

This is the code I have been working with:

var coll = document.getElementsByClassName("languageSelect");
var i;

for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function () {
        this.classList.toggle("active");
        var content = document.getElementsByClassName("languageContainer");
        if (content.style.display === "block") {
            content.style.display = "none";
        } else {
            content.style.display = "block";
        }
    });
}
.languageSelect {
    overflow: hidden;
    background-color: #6bca56;
    height: 100px;
    width: 100px;
    position: absolute;
    left: 0 !important;
    top: 0 !important;
    border: none;
}

.languageSelect:hover {
    background-color: #5cae4a;
}

.selectedLanguageFlag {
    overflow: hidden;
    width: 45%;
    height: 30%;
    position: relative;
    left: 10px;
    top: 0%;
    display: block;
}

.languageContainer {
    z-index: 2;
    position: absolute;
    background-color: #5cae4a;
    left: 0!important;
    top: 100px !important;
    width: 100px;
    display: none;
}
<button class="languageSelect"><img class="selectedLanguageFlag" src="images/language_sk_flag.png" /></button>
<div id="languageContainer" class="languageContainer">
    <button><img src="images/language_cz_flag.png"/></button>
</div>

Answer №1

Here is a simple method for toggling the visibility of an element:

const elem1 = document.querySelector('.elem1')
const elem2 = document.querySelector('.elem2')

elem1.addEventListener('click', () => {
  elem2.classList.toggle('hidden')
})
.elem1, .elem2 {
  width: 100px;
  height: 80px;
}

.elem1 {
  background: green;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  -webkit-user-select: none;
  user-select: none;
}

.elem2 {
  background: orange;
}

.hidden {
  display: none;
}
<div class="elem1">click me</div>
<div class="elem2 hidden"></div>

For creating a language selector, you can simply use a standard <select> element. While you can't insert images into the options, you are able to include Unicode characters such as emojis.

body, select {
  color: #666;
}

body {
  background: #f0f0f0;
}

select {
  appearance: none;
  font-size: 1.2em;
  border: 1px solid rgb(0 0 0 / 0.5);
  padding: 8px 2rem 8px 1rem;
  background: url('data:image/svg+xml;utf8,<svg viewBox="0 0 10 7" xmlns="http://www.w3.org/2000/svg"><path style="fill: black" d="M 0 0 L 10 0 L 5 7 L 0 0 Z"/></svg>') no-repeat;
  background-size: 15px;
  background-position: right 12px top 50%;
  outline: none;
}
<select>
  <option>🇺🇸 English</option>
  <option>🇫🇷 Français</option>
  <option>🇩🇪 Deutsch</option>
  <option>🇪🇸 Español</option>
  <option>🇮🇹 Italiano</option>
</select>

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 is the best way to import a local image into THREE.js?

I'm struggling to apply an image onto an object using the following code: var texture = new THREE.TextureLoader().load( 'crate.gif' ); var geometry = new THREE.BoxBufferGeometry( 200, 200, 200 ); var material = new THREE.MeshBasicMaterial( ...

Determining the true width of a span element using jQuery

I am trying to determine the actual width of a span element within a div, but when I attempt to do so, it gives me the width of the entire div instead. Here is the code I am working with: <div class="content"> <span class="type-text" id="ta ...

Navigate to the middle of a DIV container in Angular 7

Is there a way to programmatically scroll to the center of my element on both the Y and X axes when a specific function is executed? My HTML structure includes the following (I am aiming to scroll to the middle of #viewport): </div> <div # ...

Dragging additional events into FullCalendar is disabled after applying a filter to external events

I am encountering an issue while attempting to drag events from the external events box to the fullcalendar. To replicate the problem, you can visit this CodePen: Initially, dragging an external event into the calendar works smoothly. However, after appl ...

Issue with incorporating Material UI HtmlTooltip within Material UI Select MenuItem and handling synthetic events in the select onChange method

---OBJECTIVE--- The goal is to integrate a Material UI select component with MenuItems wrapped in HtmlTooltips, providing hover information for each option in the list. For now, I'm keeping it simple as a proof of concept and plan to implement dynam ...

Put Jest to the test by testing the appendFileSync function

I am currently working on creating a test for appendfilesync function. When using a logger, I noticed that one line of code is not covered in my tests. Below is the code snippet I am referring to (please note that I am using tslog for logging purposes): ex ...

Next/image is encountering an error due to an invalid Element type being generated

Trying to utilize the next/image feature to display an SVG image is causing me some trouble. Every time I attempt this, an error message pops up: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

"The login page failed to redirect to a different page due to issues with the header function

Hello PHP gurus, I need some assistance from all of you. I'm facing an issue where my Log-in button is not directing to Home (Student_Home.php) even though the Student ID and password are already registered in the database. *Below is the code snippe ...

Tips for preventing text from shifting once a border has been applied

Is there a way to create a navigation bar that adds a border upon hovering without the text shifting every time the border is added or removed? function navigateToHomePage(){ window.location.replace("..."); }; $(document).ready(function(){ $(".n ...

A function that can retrieve distinct values for a specific property within an array of objects while maintaining their original order

Here is some information I have: $scope.Reports = [ { Id: 1, Name: 'Report One', Year: 2016, Month: 5 }, { Id: 2, Name: 'Report Core', Year: 2016, Month: 5 }, { Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 }, { I ...

Modify the anchor text when a malfunction occurs upon clicking

Whenever I click on the link, I am able to retrieve the correct id, but the status changes for all posts instead of just the selected item. Below is the HTML code: <div th:each="p : ${posts}"> <div id="para"> <a style="float: right;" href= ...

Creating a fixed list with top-sticking elements on a webpage using HTML

Creating a single page webapp using Vue/Vuetify, I am facing an issue with building a list (v-list) of items on the right side that requires scrolling. Even though the list is longer than the page height, I want to prevent the rest of the page from scrolli ...

Why is my jQuery + JSONP request not returning any data?

I'm having a strange issue with my script that is not returning any data from a JSON file sourced from a third-party site. Here's the code: $(document).ready(function() { var url = "http://konachan.net/post/index.json?limit=20&tags=hat ...

Discovering the culprit causing a freeze on your page: Uncovering the tool or technique to identify the problematic

What is the best tool to identify resource-heavy or infinite loop JavaScript/jQuery scripts? I am currently experiencing issues with a specific template: When I open this page on Firefox 46.0.1, it freezes after a few minutes. I am having trouble pinpoin ...

Anticipated a JavaScript module script, but the server returned a MIME type of text/html as well as text/css. No frameworks used, just pure JavaScript

I have been attempting to implement the color-calendar plugin by following their tutorial closely. I have replicated the code from both the DEMO and documentation, shown below: // js/calendar.js import Calendar from '../node_modules/color-calendar&ap ...

Using ASP.NET to cleverly include script files based on certain conditions

We are currently developing a CMS project in ASP.NET, utilizing jQuery for our client-side scripting needs. At the moment, our project includes the jquery-1.2.6.js file as a mandatory script file. Additional script files are loaded as needed, based on the ...

The vertical tabs in JQueryUI lost their functionality when a few seemingly unrelated CSS styles were added

Check out the JsFiddle demo here I embarked on a mission to craft JQueryUI Vertical tabs by following the guidance provided in this example. The source code within the aforementioned link contains specific CSS styles: .ui-tabs-vertical { width: 55em; } ...

Node.js - Transform a string in the form of '{a:1}' (produced by the `util.format()`) into an object

When using util.format(), it creates strings like '{a:1}' that are not valid JSON format because the keys are not enclosed in double quotes. What is the best way to change these types of strings back into objects? ...

Identifying a user's unique identity through a POST request using Node.js

Currently, I am developing a browser game that integrates voice communication. To capture audio within the browser, I have chosen to use wami-recorder. This tool relies on Flash technology to make a POST request to the server containing the recorded audio. ...

The changes made in Express are not reflecting in the MongoDB database as expected

I'm having trouble with my update function. It's not a database issue because delete works fine. Here is the code for my Update route: Can someone please assist me? I've been using console.log to display values in the console, and they all ...