<header class="header">
<div class="header__title">
<h1>
<code>grayscale()</code>
</h1>
</div>
<div class="header__reference">
<ul class="reference-list">
<li><a class="reference-list__link" href="https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/grayscale">MDN reference</a></li>
<li><a class="reference-list__link" href="https://caniuse.com/#feat=css-filters">caniuse Support</a></li>
</ul>
</div>
</header>
<main>
<div class="example">
<p>
In this example, you can toggle the removal of a grayscale effect, bringing <a href="https://birthmoviesdeath.com/2013/09/16/true-movie-magic-how-the-wizard-of-oz-went-from-black-white-to-color">the magic of Technicolor</a> to the land of Oz:
</p>
<button
aria-pressed="false"
class="button"
type="button">
Toggle grayscale
</button>
<div class="example__demo example__demo--grayscale">
<img
class="yellow-brick-road"
alt="Dorothy, The Cowardly Lion, The Tin Man, and Scarecrow walking down the Yellow Brick Road. The city of Oz is visible on the horizon."
src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/11907/emerald-city.jpg" />
</div>
</div>
</main>
// Demo
.js-remove-grayscale {
filter: grayscale(0) !important; // Forces immutability
}
.yellow-brick-road {
filter: grayscale(1);
transition: filter var(--transition-duration-longer) ease-in-out;
}
// Pen Setup
.example__demo--grayscale {
padding: 0.5rem;
}
.yellow-brick-road {
display: block;
height: auto;
width: 100%;
}
View Compiled
const button = document.querySelector('button');
function toggleGrayscale() {
var yellowBrickRoad = document.querySelector('.yellow-brick-road');
yellowBrickRoad.classList.toggle('js-remove-grayscale');
}
button.addEventListener('click', toggleGrayscale);
button.addEventListener('click', event => {
if (button.getAttribute('aria-pressed') === "false") {
button.setAttribute('aria-pressed', 'true');
}
else {
button.setAttribute('aria-pressed', 'false');
}
});
This Pen doesn't use any external JavaScript resources.