Search code examples
javascriptjqueryhtmlclickshow-hide

Show/hide jquery click function


I have a problem with my code, I don't know why it doesn't work. My goal is to have my default:

EN div with only #en div visible, FR & DE id must be hidden by default. When we click on FR or DE, we have only #fr or #de visible and the rest hidden.

HERE IS MY JSFIDDLE

HERE IS MY CODE:

    $('#en').click(function(){
    $('fr[id^=fr], de[id^=de]').hide();
    $('#en1, #en2').show();
    });

    $('#fr').click(function(){
    $('en[id^=en], de[id^=de]').hide();
    $('#fr1, #fr2').show();
    });

    $('#de').click(function(){
    $('fr[id^=fr], en[id^=en]').hide();
    $('#de1, #de2').show();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="button" id="en">EN</a>
    <a class="button" id="fr">FR</a>
    <a class="button" id="de">DE</a>
    <div id="en1">1</div>
    <div id="fr1">2</div>
    <div id="de1">3</div>
    <div id="en2">4</div>
    <div id="fr2">5</div>
    <div id="de2">6</div>


Solution

  • Here is a jsfiddle of how I think should this code work: http://jsfiddle.net/MJambazov/tdeotges/1/

    Try to follow the DRY principle, it will make your code more readable for humans.

    $(document).ready(function() {
      $('.lan').hide();
      $('.en').show();
    });
    
    $('.button').click(function(event) {
      $('.lan').hide();
      var selectedLanguage = $(this).attr('id');
      var setActiveLanguage = "." + selectedLanguage;
      $(setActiveLanguage).show();
    });