Reputation: 45
I want the content of the div container with the ID = '1' to be displayed when I click on the "Europe" button. When clicking on the button "USA" the content of the DIV with id 2 should be displayed.
I have the following problems with my code: I can't manage to select that no DIV or only a specific one is displayed when the page is loaded. After the first click on the button the function does not work anymore.
Translated with www.DeepL.com/Translator (free version)
function showOne(id) {
$('.hide').not('#' + id).hide();
}
<button type="button" onclick="showOne('1')">Europe</button>
<br>
<button type="button" onclick="showOne('2')">USA</button>
<div class='hide' id='2'>About USA</div>
<div class='hide' id='1'>About Europe</div>
Upvotes: 4
Views: 1598
Reputation: 2134
This is honestly a really simple problem, I'm sure that there's already an answer to such problems, in any case, you could do something like this:
Might I add that this solution includes only web native technologies, no jQuery has been included, I'm not sure if this is a pro or a con in your eyes. In any case, if you'd like to learn more about the native JavaScript I've used, perhaps MDN would be a good starting point.
function showOne(id) {
document.querySelectorAll(".hide").forEach(function (el) {
el.style = "display: block;";
});
document.querySelector(".hide[id='" + id + "']").style = "display: none;";
};
.hide {
display: none;
}
<button type="button" onclick="showOne('1')">Europe</button>
<br>
<button type="button" onclick="showOne('2')">USA</button>
<div class='hide' id='1'>About USA</div>
<div class='hide' id='2'>About Europe</div>
Upvotes: 0
Reputation: 1
You can try to add .show()
method to show all of that elements before hiding:
function showOne(id) {
$('.hide').show().not('#' + id).hide();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" onclick="showOne('1')">Europe</button>
<br>
<button type="button" onclick="showOne('2')">USA</button>
<div class='hide' id='2'>About USA</div>
<div class='hide' id='1'>About Europe</div>
Upvotes: 0
Reputation: 73896
You just need to show the current div first on button click like:
function showOne(id) {
$('#' + id).show();
$('.hide').not('#' + id).hide();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" onclick="showOne('1')">Europe</button>
<br>
<button type="button" onclick="showOne('2')">USA</button>
<div class='hide' id='2'>About USA</div>
<div class='hide' id='1'>About Europe</div>
Upvotes: 1