So I have been working on a dropdown menu to select a language. Thats the code:
HTML
<div class="language_section">
<span id="select-lang-btn"><img class="language_flag" src="en.svg"><a id="selected-lang">English</a></span>
<ul class="language_dropdown" id="language_dropdown">
<li onclick="show('English')"><a href="#" class="language_text"><img class="language_flag" src="en.svg">English</a></li>
<li onclick="show('Germany')"><a href="#" class="language_text"><img class="language_flag" src="de.svg">German</a></li>
<li onclick="show('Spanish')"><a href="#" class="language_text"><img class="language_flag" src="es.svg">Spanish</a></li>
</ul>
</div>
CSS
<style>
body {
background-color: #339699;
}
#select-lang-btn {
outline: none;
cursor: pointer;
}
.language_dropdown {
display: none;
align-items: center;
background-color: white;
width: 300px;
}
li {
cursor: pointer;
list-style: none;
}
.language_text {
color: black;
text-decoration: none;
}
.language_flag {
width: 32px;
}
</style>
JS
<script>
var button = document.getElementById('select-lang-btn');
button.onclick = function() {
var div = document.getElementById('language_dropdown');
if (div.style.display === 'block') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
function show(anything) {
document.getElementById("selected-lang").innerHTML = anything
document.getElementById('language_dropdown').style.display = 'none';
}
</script>
However there is one problem with my code. When I select a new language, the selected language appears as a text, but the image does not change. That is because I created a function called show which only manages to change the text. Now I have been researching and thinking a lot but still didnt find a solution. Then I had an Idea if i could change the image by the innertext -> For Example if Germany is visible then the image automatically changes to Germanys Flag. But it seems like there is nothing about that methode online. Is that possible or is there a cleaner way to solve this issue?