Issue
I tried to make a collapsible div the same way that a <select>
acts like. Since you can't add an <img>
into an <option>
.
I tried to replicate a "language selection" box. Like this:
When you click on the dropdown box a bunch of different languages pop up. Which isn't happening on my replica. It won't expand or collapse.
Here is my code:
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>
Solution
This is the basic logic to toggle the visibility of an element:
const d1 = document.querySelector('.d1')
const d2 = document.querySelector('.d2')
d1.addEventListener('click', () => {
d2.classList.toggle('hidden')
})
.d1, .d2 {
width: 100px;
height: 80px;
}
.d1 {
background: red;
color: white;
display: flex;
justify-content: center;
align-items: center;
-webkit-user-select: none;
user-select: none;
}
.d2 {
background: blue;
}
.hidden {
display: none;
}
<div class="d1">tap me</div>
<div class="d2 hidden"></div>
But to achieve your goal of building a language selector, there is an easier way: just use a standard <select>
. Although you can’t add images into the options, you can add Unicode characters including emoji.
body,select {
color: #ddd;
}
body {
background: #052b49;
}
select {
appearance: none;
font-size: 1.5em;
border: 1px solid rgb(255 255 255 / 0.5);
padding: 7px 2rem 7px 1rem;
background: url('data:image/svg+xml;utf8,<svg viewBox="0 0 10 7" xmlns="http://www.w3.org/2000/svg"><path style="fill: white" d="M 0 0 L 10 0 L 5 7 L 0 0 Z"/></svg>') no-repeat;
background-size: 12px;
background-position: right 10px top 50%;
outline: none;
}
<select>
<option>🇬🇧 English</option>
<option>🇫🇷 Français</option>
<option>🇩🇪 Deutsch</option>
<option>🇪🇸 Español</option>
<option>🇮🇹 Italiano</option>
</select>
Answered By - Brett Donald
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.