Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a grayscale button for a website?

I hope everyone’s doing well.

I’m trying to create a grayscale button that changes the background of my whole website to grey, and when I click this button again, it returns to the original colour of the website.
I’m using JavaScript, HTML & CSS.
I’ve tried creating two functions in a button, which also didn’t work out.

My code below

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  <button onclick="grayscale()">Grayscale</button>
        <style>
        body
        {
        -webkit-filter: grayscale(0);
        filter: none;
        }
        </style>
        <script>  
      function myFunction() {
      document.getElementById("myImg").style.filter = "grayscale(100%)";
      else function myFunction(){
    document.getElementById("myImg").style.filter = "grayscale(0%)";
    }
}

</script>
</button>

>Solution :

Using an image to demonstrate the grayscale effect from Freepik

<!-- Grayscale button -->
<button onclick="grayscale()">Grayscale</button>
<!-- An image to demonstrate the grayscale effect -->
<hr>
<img src="https://img.freepik.com/free-vector/abstract-colorful-fluid-background_23-2148901720.jpg?w=2000" width="200">
<!-- CSS -->
<style>
  /* Remove the following three lines to remove animation */
  body {
    transition: filter 1s; /* Change "1s" to any time you'd like */
  }
  body.grayscale {
    /* grayscale(1) makes the website grayscale */
    -webkit-filter: grayscale(1);
    filter: grayscale(1);
  }
</style>
<!-- JavaScript -->
<script>
  // Grayscale function
  function grayscale() {
    // Toggling the class "grayscale" on the body
    document.body.classList.toggle("grayscale");
  }
</script>
1 comments

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading