Leia_Organa
Leia_Organa

Reputation: 2094

jQuery: Hide function not working properly?

I'm working on a one-page application in jQuery where different buttons and options will display based on which buttons are clicked.

I can't figure out why my hide() functions aren't working. I wrapped it in a $(document).ready function, but I feel like there's either something I'm not including, or something else that is interfering.

Also yes, I did check and see that the jQuery library is loading before my JS file.

$(document).ready(function() {
    showCategories() {
      ("#dog").hide();
      ("#cat").hide();
      ("#eagle").hide():
      ("#sparrow").hide();
    }
      
    showCategories();
});
    #purple {
      color: purple;
    }
    
    #pink {
      color: pink;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <button id="purple">Mammals </button>
    <button id="pink">Birds</button>
    
    <div class="mammalButtons"> 
      <button id="dog">Dog</button>
      <button id="cat">Cat</button>
    </div>
    
    <div class="birdButtons">
      <button id="eagle">Eagle</button>
      <button id="sparrow">Sparrow</button>
    </div>

Can anyone give any pointers or suggestions?

Upvotes: 0

Views: 534

Answers (1)

Taplar
Taplar

Reputation: 24965

$(document).ready(function() {
    showCategories() {
        ("#dog").hide();
        ("#cat").hide();
        ("#eagle").hide():
        ("#sparrow").hide();
    }
});

1) Malformed function definition

showCategories(){} is not formatted correctly. Function definitions require function at the start of them. So to correct that issue it would need to look like

$(document).ready(function() {
    function showCategories() {
        ("#dog").hide();
        ("#cat").hide();
        ("#eagle").hide():
        ("#sparrow").hide();
    }
});

However, that leads to another issue. That just declares a function. It's not executing it. So you would have to change it to...

$(document).ready(function() {
    function showCategories() {
        ("#dog").hide();
        ("#cat").hide();
        ("#eagle").hide():
        ("#sparrow").hide();
    }

    showCategories();
});

for the function to execute, but really at that point you should just remove it.

$(document).ready(function() {
    ("#dog").hide();
    ("#cat").hide();
    ("#eagle").hide():
    ("#sparrow").hide();
});

2) Typo calling jQuery

("#dog").hide(); and the other calls, are just trying to call hide() on a string, because you left off the $ for the lookup. All those should be corrected.

$(document).ready(function() {
    $("#dog").hide();
    $("#cat").hide();
    $("#eagle").hide():
    $("#sparrow").hide();
});

At that point, it should work, however, you can reduce this since you are performing the same operation on multiple things.

$(document).ready(function() {
    $("#dog, #cat, #eagle, #sparrow").hide();
});

Upvotes: 3

Related Questions