Search code examples
javascriptjqueryhtmltogglebutton

Show/Hide divs not working as expected


I need some buttons which on click shows the related divs and hide the rest.

I googled the below code. It is working as expected on jsfiddle.net, but it's not on my server. I get something like this, and of course the 'buttons' aren't working as well:

button1 button2 button3 button4 button5
part1
part2
part3
part4
part5

Code:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('.showSingle').on('click', function () {
    $(this).addClass('selected').siblings().removeClass('selected');
    $('.targetDiv').hide();
    $('#div' + $(this).data('target')).show();
});
$('.showSingle').first().click();
</script>

<div class="buttons">
    <a  class="showSingle" data-target="1">button1</a>
    <a  class="showSingle" data-target="2">button2</a>
    <a  class="showSingle" data-target="3">button3</a>
    <a  class="showSingle" data-target="4">button4</a>
    <a  class="showSingle" data-target="5">button5</a>
</div>

<div id="div1" class="targetDiv">part1</div>
<div id="div2" class="targetDiv">part2</div>
<div id="div3" class="targetDiv">part3</div>
<div id="div4" class="targetDiv">part4</div>
<div id="div5" class="targetDiv">part5</div>

Solution

  • Use the following at the beginning of your script:

    $(document).ready(function(){
       //Your logic
    });