Richard Richard - 3 months ago 24
HTML Question

jquery Hide show multiple divs

I'm looking for a smarter way to hide and show multiple elements.
The solution I have now is to create a separate script for every element I want to show, with a click on a button.

<a class="pure-button pure-button-primary" type='button' id='hideshow1'
value='hide/show' >Show it1 !</a>
<div id='content1' style="display:none">
lorem ipsum
</div>

<a class="pure-button pure-button-primary" type='button' id='hideshow2'
value='hide/show' >Show 2 </a>
<div id='content2' style="display:none">
lorem ipsum
</div>


This is the script part:

<script>
jQuery(document).ready(function(){
jQuery('#hideshow1').on('click', function(event) {
jQuery('#content1').toggle('hide');
});
});
</script>
<script>
jQuery(document).ready(function(){
jQuery('#hideshow2').on('click', function(event) {
jQuery('#content2').toggle('hide');
});
});
</script>


This way works perfect, however I think there must be a smarter way. Anyone can give me a clue how to make it smarter?

Answer

you dont have to write JS code for each element. Either you can speicify the same class class="hide" on all a tag and data-content="" to toggle hide/show (as Mostafa said). But if you want to do it by ids. then you can follow this code.

https://jsfiddle.net/unnxnz71/

HTML

      <a class="pure-button pure-button-primary" type='button' id='hideshow1' value='hide/show' data-value="content1">Show it1 !</a>
      <div id='content1' style="display:none">
        lorem ipsum
      </div>

      <a class="pure-button pure-button-primary" type='button' id='hideshow2' value='hide/show' data-value="content2">Show 2 </a>
      <div id='content2' style="display:none">
        lorem ipsum
      </div>

JS

    $('[id^="hideshow"]').on('click', function(event) {
      var dataValue = $(this).attr('data-value');
      dataValue = $('#'+dataValue);
      $(dataValue).toggle('hide');
    });