javascripthtmlcssanki

Change Text To Button With hidden and shown


I have this code that I use in a app called Anki, Which is a flashcard app that helps me remember new words. I have this code that writes a text when I click on it shows the content of the hint field which that I added when adding the new card,

{{#Hint}}
    <div id="hint" class="hidden">
        <p class="trigger">[ click to show hint ]</p>
        <p class="payload">{{Hint}}</p>
    </div>
    <script>
        var hint = document.getElementById('hint');
        hint.addEventListener('click', function() { this.setAttribute('class', 'shown'); });
    </script>
{{/Hint}}

All I want is write function of that text above to button with style like this code, for example.

<!DOCTYPE html>
<html>
<head>
<style>
.button {
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

.button1 {background-color: #4CAF50;} /* Green */
</style>
</head>
<body>

<button class="button button1">Green</button>

</body>
</html>

And I want that when I press the button for the first time, it shows me the content of the hint field, And when I press it for the second time, it hides it, and so on...

Thanks in advance


Solution

  • If i understood correctly you wanna add and remove some certain css class on each sequential click?

    In that case, toggling class will do the thing:

    hint.addEventListener('click', function() {  hint.classList.toggle("shown"); });
    

    And css can be for example something like:

    #hint .payload {display: none};
    
    #hint.shown .payload {display: block}