i'm running into a problem. Next to the "Show More" there is an icon. When pressed it disappears, because the innerText gets replaced so I tried this:
document.getElementById("toggleButton").innerText = "Show Less <i class="fas fa-caret-down"></i>" ;
This doesn't seem to work any suggestions?
var status = "less";
function toggleText()
{
if (status == "less") {
document.getElementById("textArea").style.display = "block";
document.getElementById("toggleButton").innerText = "Show Less";
status = "more";
} else if (status == "more") {
document.getElementById("textArea").style.display = "none";
document.getElementById("toggleButton").innerText = "Show More";
status = "less"
}
}
<!DOCTYPE html>
<html>
<head>
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
</head>
<body>
<div id="textArea" style="display: none;">
test
</div>
<button type="button" id="toggleButton" onclick="toggleText();" href="javascript:void(0);">Show More <i class="fas fa-caret-down"></i></button>
<div id="textArea" style="display: none;">
</div
</body>
</html>
You need to use innerHTML instead of innerText if the text string contains html that needs to be rendered:
document.getElementById("toggleButton").innerHTML
The problem is that you are replacing the whole content of the button here:
document.getElementById("toggleButton").innerText = "Show Less";
You are overwriting the original text and the icon with just "Show Less".
To fix this, you could use innerHTML instead to set the new text and the HTML for the icon:
buttonText.innerHTML = `Show Less <i class="fas fa-caret-up"></i>`;
Or you can also wrap the text in a different element to just change that part:
const button = document.getElementById("button");
const buttonText = document.getElementById("buttonText");
const more = document.getElementById("more");
let hidden = true;
button.onclick = () => {
if (hidden) {
more.style.display = "block";
buttonText.innerText = "Show Less";
buttonText.nextElementSibling.setAttribute("data-icon", "caret-up");
hidden = false;
} else {
more.style.display = "none";
buttonText.innerText = "Show More";
buttonText.nextElementSibling.setAttribute("data-icon", "caret-down");
hidden = true;
}
};
<!DOCTYPE html>
<html>
<head>
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
</head>
<body>
<button id="button">
<span id="buttonText">Show More</span>
<i id="buttonIcon" class="fas fa-caret-down"></i>
</button>
<p id="more" style="display: none;">
MORE
</p>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With