Search code examples
htmlcsstoggle

I need two HTML tags so that one is visible when the other is hidden, and vice-versa


I am creating a page to learn Japanese words. Each word is contextualized within a sentence like this one.

故郷に手紙を出す write home to one's family

I made it so that I can only see the phonetic reading of the word, so that people can train writing the word in ideograms. The above sentence looks like this.

こきょうに手紙を出す write home to one's family

Now I want to be able to click on こきょう to hide こきょう and show 故郷, and also the reverse. This is the CSS and HTML I wrote so far.

CSS

x { display: none; }

HTML

<x>故郷</x><y>こきょう</y>に手紙を出す write home to one's family

I basically want to toggle between y { display: none; } and x { display: none; } if I click on the word.

Can I achieve this purely with CSS and HTML or is Javascript necessary?

I don't think it would be difficult to toggle between the two if I was hiding ALL <x> or <y> on the page, but I don't like that result. I was looking for a way to toggle only between <x> or <y> of the clicked word.

As I will have hundreds/thousands of sentences on the page, it would be impractical to have a different ID or class for every word to target a specific word.

All solutions I found involved using an ID for the specific tag, or toggling all tags at the same time, and I couldn't figure out how to achieve this.


Solution

  • Are you familiar with the checkbox hack? This can be done very simply with a single checkbox and both word contexts inside a label. Like this:

    [type=checkbox]:checked+span {
      display:none;
    }
    [type=checkbox]:not(:checked)+span+span {
      display:none;
    }
    [type=checkbox] {
      display:none;
    }
      <label>
        <input type=checkbox>
        <span>故郷</span>
        <span>こきょう</span>
      </label>に手紙を出す write home to one's family