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
<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>
CodePudding user response:
function grayscale() {
let img = document.getElementById("myImg");
img.classList.toggle("grey");
}
.grey {
filter: grayscale(100%);
/* other styles if I want to add them */
}
<button onclick="grayscale()">Grayscale</button>
<img src="https://picsum.photos/500" id="myImg" />
the better, simple way is to use
.classList.toogle()
(this make you not using if/else) it will do the checking automatically for you. and also you can add more styling inside the class selector, and basically have more control.https://developer.mozilla.org/en-US/docs/Web/API/Element/classList?retiredLocale=it
CodePudding user response:
just use one function and use an if satement
function myFunction() {
if(document.getElementById("myImg").style.filter == 'grayscale(100%)')
document.getElementById("myImg").style.filter = "grayscale(0%)";
else document.getElementById("myImg").style.filter = "grayscale(100%)";
}
body
{
-webkit-filter: grayscale(0);
filter: none;
}
<button onclick="myFunction()">Grayscale</button>
<img id='myImg' src="https://www.fillmurray.com/640/360">
CodePudding user response:
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>
CodePudding user response:
Use the classList.toggle to toggle a class on and off.
function toggleGrey() {
document.getElementById("myImg").classList.toggle("greyscale");
}
.greyscale {
filter: grayscale(1);
}
<button type="button" onclick="toggleGrey()">Grayscale</button>
<img id="myImg" src="https://placekitten.com/200/287" alt="">