Please I need help with this JavaScript code, this is what I want it to look like, the balance will be visible and the icon will show as a show icon, and when it is clicked on, the icon will switch to a hide icon and the balance will become password format... Here is my code below:
function changeIcon(anchor) {
var icon = anchor.querySelector("i");
icon.classList.toggle('bx-show');
icon.classList.toggle('bx-hide');
anchor.querySelector("span").textContent = icon.classList.contains('bx-show') ? "Read more" : anchor.querySelector("span");
}
<link href='https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'>
<a onclick="changeIcon(this)" id="myBtn">
<i id="faPlus" class='bx bx-show'></i>
<span class="SPN">Balance: $56,756.00</span>
</a>
This is the result, at the first the balance will be visible but when click to hide and click to show the balance again will not be visible, this is what I got as result below:
[object HTMLSpanElement]
Thanks
Your result isn't working, because you try to set the TextContent of your SPAN-Element to the entire Element itself.
Firstly, you should store the Balance in a separate variable or preferably as a data-attribute for the specific element to access it at any time, cause if you change the TextContent, your Balance value is replace by your "Read more"-String and the original value is gone.
I would oppose the following changes:
Store the balance in a separate value, to access the value if you want to show the balance again, if it was hidden before.
You need to change the ternary-operator a little
Ive edited your source code below with comments:
function changeIcon(anchor) {
var icon = anchor.querySelector("i");
icon.classList.toggle('bx-show');
icon.classList.toggle('bx-hide');
// Changed the falsy state of the ternary operator to return the balance value
anchor.querySelector("span").textContent = icon.classList.contains('bx-show') ? "Read more" : anchor.querySelector("span").dataset.value;
}
<link href='https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'>
<a onclick="changeIcon(this)" id="myBtn">
<i id="faPlus" class='bx bx-show'></i>
<!-- In php the line would be:
<span class="SPN" data-value="<?php echo $x; ?>"><?php echo $x; ?></span> -->
<span class="SPN" data-value="Balance: $56,756.00">Balance: $56,756.00</span>
</a>