skip to Main Content

I am trying to master JS and jQuery, but I can’t resolve this task.
Task : 1 click on button, we are getting black background on website, 2 – click, we are removing all changes and back to default what was before.
It getting black background, but second click does not work.
Thank you for help

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>


<button type="button" id="button">Button for test</button>

script type="text/javascript">

    $(document).ready(function(){

        function on_contrast(){
                  $('body').css('background', 'black');
            
    function off_contrast(){
                  $('body').css('background', 'black').off();
        };

        $('#button').click(on_contrast);
        $('#button').click(off_contrast);
    }); 
</script>

I tried many times and different options, but looks like I do not understand logic in some places.

3

Answers


  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    <button type="button" id="button">Button for test</button>
    
    <script type="text/javascript">
        $(document).ready(function () {
            let isBlack = false;
    
            $('#button').click(function () {
                if (isBlack) {
                    $('body').css('background', '');
                } else {
                    $('body').css('background', 'black');
                }
                isBlack = !isBlack;
            });
        });
    </script>

    I added a variable isBlack to keep track of the current state of the background color. It toggles between true and false each time the button is clicked.

    The if-else block checks the value of isBlack. If it’s true, the background is set back to the default (empty string ” resets it to whatever the default was before). If it’s false, the background is set to black.

    After setting the background color, the code toggles the value of isBlack using isBlack = !isBlack;

    Login or Signup to reply.
  2. If you use CSS for styling and set the class name of the body, you can start to style any element on the page according to the state.

    <button type="button" id="button">Button for test</button>
    
    <script type="text/javascript">
      document.addEventListener('DOMContentLoaded', e => {
        document.getElementById('button').addEventListener('click', e => {
          document.body.classList.toggle('dark');
        });
      });
    </script>
    
    <style>
      body.dark {
        background-color: black;
      }
      
      body.dark button {
        background-color: #444;
        color: white;
      }
    </style>
    Login or Signup to reply.
    • You’re not closing properly your functions body with }
    • jQuery’s .off() method is well documented here and it’s a counter method to the .on() which you’ll learn how to use in this example
    • Avoid the .click() method, use rather the preferred .on() method to assign event handlers like $("#button").on("click", toggle_contrast);
    • If you want to learn now how to off an Event handler, use whenever you want i.e: $("#button").off("click", toggle_contrast); (will stop listening (unsubscribe) to click events for that specific callback function)
    • You don’t need two functions, just use .toggleClass() method to toggle a specific modifier CSS class from a target element
    • styles are best defined in your stylesheet, not disseminated in your JS file, use CSS to define your .dark{} styles and toggle it using JavaScript
    .dark {
      background-color: black;
    }
    <button type="button" id="button">Button for test</button>
    
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
      jQuery($ => { // DOM ready and $ alias in scope
      
        function toggle_contrast() {
          $("body").toggleClass("dark");
        }
    
        $("#button").on("click", toggle_contrast);
        
      });
    </script>
    <!-- Closing </body> goes here -->

    And yes, jQuery is nowadays not that much necessary for those simple tasks. You can rewrite the above in pure JavaScript without the overhead of an entire JS library (like jQuery — or any other)

    .dark {
      background-color: black;
    }
    <button type="button" id="button">Button for test</button>
    
    <script>
      const elBody = document.querySelector("body");
      const elButton = document.querySelector("#button");
    
      const toggleTheme = () => {
        elBody.classList.toggle("dark");
      };
    
      elButton.addEventListener("click", toggleTheme);
    </script>
    <!-- Closing </body> goes here -->
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search