Search code examples
javascriptphpjquerytoggleclass

Using toggleClass in jQuery to shrink a div


I have a div and I'm trying to shrink it when I click a button. And when I click it again, I want it back to the original size. I'm using toggleClass for this, but I did something wrong with my code, and I'm not sure where. Please take a look. Thanks.

//*********************************************************************
<style>

    div {
    border: 1px solid black;    
    width: 500px;
    height: 500px;  
    }
    .shrink {
    width: 250px;
    height: 250px;
    }   

</style>

//*********************************************************************  

<button type = "button"> click me </button>
<div> Can you tell me a secret? </div>

//*********************************************************************

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type = "text/javascript">   

$(document).ready($function {

$("button").click(function(){
    $("div").toggleClass("shrink");
});               

});

</script>
//*********************************************************************

Solution

  • It's kind of a typo. You wrote "$function {" but you probably mean this:

    $(document).ready(function() {
    

    The rest is fine. Also, document ready can be expressed in a shorter form:

    $(function() {
        ...
        ...
    });
    

    Maybe you just confused those two. I did a few times too, back in my beginner days :)