Search code examples
javascriptjqueryhideshow

Show Div by clicking on button, hide others


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>


Solution

  • 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>