You do not need to create a function for each state, the fact of hiding and showing a particular element in the DOM is not inherent to the state the user has chosen, it is just a reaction to a user action. Think about this, if in the future add another Feature that needs to react to the choice of the state, how would you do? For example, display the state flag in the header that is a component with its own context.
In this case, not separating the responsibilities, all the components of the system begin to be strongly coupled, making maintenance and evolution difficult. If in the future the header is completely changed and there is a function that is strongly coupled to the header and at the same time to another part of the system, it is much more difficult to change the header.
A good example to maintain healthy application would be to implement the standard Observer , but it depends on the context and complexity of the application, I just left the reference so you know that there is this possible solution.
However, I leave a simpler solution. We can separate the responsibilities in the same using custom Events, that is, the responsibility to select a state should not be in the same role as that which reacts to that choice.
To define each state, I used the ISO_3166-2:EN:
<button type="button" onclick="selecionaEstado('br-mg')">Minas Gerais</button>
<button type="button" onclick="selecionaEstado('br-ba')">Bahia</button>
<div id="br-mg" class="wrapper">
Escolheu o estado MG
</div>
<div id="br-ba" class="wrapper">
Escolheu o estado BA
</div>
The function selecionaEstado
is responsible for informing the system that the user has selected its status:
function selecionaEstado(estado) {
const event = new CustomEvent("alteraEstado", {
detail: { estado }
});
document.dispatchEvent(event);
}
Any component of the system is now able to listen to and react to the changing state:
document.addEventListener("alteraEstado", (event) => {
const estado = event.detail.estado;
document.querySelectorAll('.wrapper').forEach(function(el) {
el.style.display = 'none';
});
document.getElementById(estado).style.display = 'block';
});
CSS:
.wrapper {
display: none;
}
Here you can find the code working.
It is important to note that Customevent has compatibility limitations with Internet Explorer.
Thank you very much I’ll give a study.
– João Silva
I wanted to put other buttons inside these to show the content but when I put more buttons and click on them the others disappear
– João Silva
You know what it can be?
– João Silva
I got it, but it doesn’t work in internet explorer
– João Silva
You know how to make it work in the explorer?
– João Silva