Home > Mobile >  How to have different buttons open different pieces of content
How to have different buttons open different pieces of content

Time:11-09

I am trying to build a part of my website where 2 different buttons open up 2 different messages. However, when I run the code, the content doesn't change when I press the second button.

I'm not extremely skilled in JQuery so I am not sure exactly what is going wrong.

Here is my code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="btnClick">Section one</button>
<button id="btnClick2">Section two</button>

<div id="1">
    <p>Section one. Message one.</p>
</div>

<div id="2" style="display:none;">
    <p>Section one. Message two.</p>
</div>

<div id="3" style="display:none;">
    <p>Section two. Message one.</p>
</div>

<div id="4" style="display:none;">
    <p>Section two. Message two.</p>
</div>

$('#btnClick').on('click', function () {
    if ($('#1').css('display') != 'none') {
        $('#2').show().siblings('div').hide();
    } else if ($('#2').css('display') != 'none') {
        $('#1').show().siblings('div').hide();
    } else {
        $('#1').show().siblings('div').hide();
    }
});

$('#btnClick2').on('click', function () {
    if ($('#3').css('display') != 'none') {
        $('#4').show().siblings('div').hide();
    } else if ($('#4').css('display') != 'none') {
        $('#3').show().siblings('div').hide();
    } else {
        $('#3').show().siblings('div').hide();;
    }
});

CodePudding user response:

Instead of use multiple functions like you tried, i edited your code with one master function. That function read data-attribute for show or hide div like:

const sections = $('.container-section');
$('.btnClick').on('click', function() {
  $(sections).find('[data-target]').hide();
  $(sections).find('[data-target="'   $(this).data('section')   '"]').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button  data-section="1">Section one</button>
<button  data-section="2">Section two</button>

<div >
  <div data-target="1">
    <p>Section one. Message one.</p>
  </div>

  <div data-target="2" style="display:none;">
    <p>Section one. Message two.</p>
  </div>
</div>

Reference:

  • Related