Timothy Fisher Timothy Fisher - 7 months ago 17
Javascript Question

Can't get this basic toggleClass to work in JQuery

So I'm not sure what I'm doing wrong. I am trying to make a button appear as if it is pressed down by toggling a class when it is clicked.

I did a quick JavaScript if statement to make sure jQuery was loaded.

Here is the code:

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.12.3.min.js"></script>
<script>
$("button").click(function(){
$("button").toggleClass("active-class");
});
</script>
<style type="text/css">
.active-class {
background-color:red;
}

/* Non-important styles */
button {
font-size:15px;
padding:10px;
background-color:#E8E8E8;
border:1px solid rgba(0,0,0,0.3);
border-radius:5px;
outline:none;
}
</style>
</head>
<body>
<button>Click to toggle!</button>



</body>
</html>


When I click on the button it does absolute nothing. Any suggestions?

Answer

Move your js before end body tag. or add document ready function :

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
  <script>
  $( document ).ready(function() {
    $("button").click(function(){
      $("button").toggleClass("active-class");
    });
  });
  </script>
  <style type="text/css">
  .active-class {
    background-color:red;
  }
  /* Non-important styles */
  button {
    font-size:15px;
    padding:10px;
    background-color:#E8E8E8;
    border:1px solid rgba(0,0,0,0.3);
    border-radius:5px;
    outline:none;
  }
  </style>
</head>
<body>
  <button>Click to toggle!</button>
</body>
</html>