If you just want to toggle text and asterisks, there is no reason why you have a div
separate, or any very complex structure...
You could simply save the original text in an attribute and toggle the HTML of the element.
Take an example:
$('.hidden-text')
// Começa os textos com ****
.html(function(i, old_text) {
return "*".repeat(this.dataset.text.length);
})
// Alerna os texto
.on('click', function() {
let text = this.dataset.text;
if (this.is_visible) {
this.innerHTML = "*".repeat(text.length);
} else {
this.innerHTML = text;
}
this.is_visible = !this.is_visible;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="hidden-text" data-text="Meu texto escondido"></p>
<p class="hidden-text" data-text="outro texto escondido"></p>
The operation is simple:
- Use the method
.html
to "initialize" all elements with asterisks;
By clicking on the element I check if the property is_visible
is true
- If yes, I hide the text by replacing its contents with asterisks (I am using the method
String.repeat()
to repeat the asterisk N times);
- If not, I show the text replacing its contents with the text contained in
data-text
(see more about data-*
in documentation);
Note that the property is_visible
does not exist, I "invented" to keep the state of that object in memory without having to access the DOM.
But if you hide the
***
where you will click to close hide again?– hugocsl
the idea is to click the 'value' and return to be '***'
– Éo Ronaldo Dll
The
e.preventDefault();
is unnecessary because it has no function in this context. The paragraph click does not cause any action. You would use if instead of the graph it was a<a>
.– Sam
use the value in a stylized text type input and with a click event to switch to password and then to text would be ridiculous?
– flourigh