The Easiest Way to Add Spoilers to Your Blog
2018 February 07

This post describes what I think is the easiest way to add spoilers to your blog. Spoilers are useful when you talk about fiction and don’t want to spoil the ending for a user.

An example of this would this text. This is some hidden text. You can click to show the hidden text and click again to hide it again. All done without any frameworks and minimal css.

This solution defines a class called spoiler that may be attached to any text that is a spoiler.

You just add this css to your site, where $textColor is the color of the text being spoiled. This will only work on sites that use a single text color.

.spoiler {
    background-color: $textColor;
}

Then include the following javascript on your page. It maybe more convient for you to download the source file to include it on your site.

function get_prop(elem, prop) {
    return window.getComputedStyle(elem).getPropertyValue(prop);
}

const TEXTCOLOR = get_prop(document.body, 'color');
const BGCOLOR = get_prop(document.body, 'background-color');

document.querySelectorAll('.spoiler').forEach((spoiler) => {
    console.log(spoiler);
    spoiler.addEventListener('click', () => {
        c = get_prop(spoiler, 'background-color')
        if(c == TEXTCOLOR) {
            spoiler.style.backgroundColor = BGCOLOR;
        } else {
            spoiler.style.backgroundColor = TEXTCOLOR;
        }
    });
})

Now all you have to do is include it on pages where you have spoilers that you care to hide with virtual black outs, and surround that text like the bellow example.

<span class="spoiler">Hidden Text</span>

And that’s how you easily add simple electronic blanks to your blog.


Remember you can also subscribe using RSS at the top of the page!

Share this on → Mastodon Twitter LinkedIn Reddit

A selected list of related posts that you might enjoy:

*****
Written by Henry J Schmale on 2018 February 07
Hit Counter