the script changes the class and, accordingly, the background of the button. But does not change. Help! `

<script type="text/javascript"> $(function(){ $("#old").change(function(){ $(".but").toggleClass('active'); }); }); </script>` <style> .active{ background: #000000; } .but{ background: #00BFCD; border: none; } </style> <input type="checkbox" id="old" >go <button class="but">скачать</button> 
  • First html, then script. Or instead of creating and calling the function $(function(){ ... }); execute script on loading DOM elements $(document).ready(function() { ... }); - Mr. Black
  • @Doofy, $(function(){ ... }) is a short form of the record $(document).ready(function() { ... }) - Grundy
  • I advise you first to learn the basics of javascript, then take on jquery type frameworks. $(function() { ... }) is not a wrapper for jquery functions. Inside, an event handler is already assigned .change() - Mr. Black
  • does not work! If you specify color, only the color changes, and background changes to nothing. And no matter where the script is located - at the beginning of the document or at the end. - Proshka

2 answers 2

In principle, you can do without JS:

 .but { background: #00BFCD; border: none; } #old:checked +.but { background: #000000; color: #fff; } 
 <input type="checkbox" id="old">go <button class="but">скачать</button> 

    The whole problem is in cascading styles, the class active is described earlier and sets the same property as the class but , therefore the value from the class but is used .

    To solve, you just need to swap the definition of classes

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> $(function() { $("#old").change(function() { $(".but").toggleClass('active'); }); }); </script> <style> .but { background: #00BFCD; border: none; } .active { background: #000000; } </style> <input type="checkbox" id="old">go <button class="but">скачать</button> 

    • cool. I spent 2 hours. Thanks for the smart and quick reply. - Proshka