Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I shorten this javascript code? show hide multiple divs

How can I shorten this code? Each css selector increases +1. All Bio's divs are hidden unless the .mug(x) is selected.

Thanks

        <script type='text/javascript'>
                $(document).ready(function () {
                    $(".mug1").click(function() {
                        $("#bios div").hide();
                        $(".bio1").show();                      
                    });                     
                    $(".mug2").click(function() {
                        $("#bios div").hide();
                        $(".bio2").show();                      
                    });                     
                    $(".mug3").click(function() {
                        $("#bios div").hide();
                        $(".bio3").show();                      
                    });                     

            });
        </script>   

        <h2>Meet the team</h2>

        <div id="mugshots">
            <img src="images/img-mugshot.jpg" alt="mug" class="mug1"/>
            <img src="images/img-mugshot.jpg" alt="mug" class="mug2"/>
            <img src="images/img-mugshot.jpg" alt="mug" class="mug3"/>
        </div>

        <div id="bios">
            <div class="bio1"></div>
                            <div class="bio2"></div>
                            <div class="bio3"></div>
                    </div>
like image 766
Mark Avatar asked Jan 23 '26 06:01

Mark


1 Answers

Something along these lines?

Change the html to this:

    <div id="bios">
        <div class="bio"  data-id="1"></div>
                        <div class="bio" data-id="2"></div>
                        <div class="bio" data-id="3"></div>
                </div>

Then your js to this:

$(".mug").click(function() {
                    $("#bios div").hide();
                    $(".bio[data-id='" + $(this).data("id") + "'", $("#bios")).show();                      
                }); 

This way you could add as many mugs and bios as you like without having to add any more js.

like image 155
DavidGouge Avatar answered Jan 25 '26 21:01

DavidGouge