Home > Net >  Change Text To Button With hidden and shown
Change Text To Button With hidden and shown

Time:10-28

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

CodePudding user response:

With your contribution of style and general idea, it is to add a small part of js to your script.

In relation to what was said by @munleashed, it could also be used by onclick event.

var hint = document.getElementById('hint');

function hide() {
  hint.classList.toggle('shown');
}
.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;
}
#hint .payload {
  display: none;
}
#hint.shown .payload {
  display: block;
}
<div id="hint" class="hidden">
  <button class="button button1" onclick="hide()">[ TOUCH ]</button>
  <p class="payload">SOME HINT HERE</p>
</div>
<!-- 
<button  onclick="hide()">[ TOUCH ]</button>

<div id="hint" >
    <p >SOME HINT HERE</p>
</div> 
-->
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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}
  • Related