I am trying to create a toggle button that displays two different messages using innerHTML
, along with applying CSS classes from Bootstrap 4 and toggling classes with classList.toggle
.
The "Read more" message should be displayed on a blue button with an up arrow icon inside a circle, styled with the classes btn btn-primary. The "Read Less" message should appear on a green button with a down arrow icon inside a circle, styled with the classes btn btn-success.
Fontawesome icons are being used for the arrow icons.
It is essential to work with CSS classes as I am implementing Bootstrap styles for each button.
However, when I run this code, the result is not synchronous after clicking the button three times.
Thank you all for your help.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
<style>
#more {
display: none;
}
</style>
</head>
<body>
<h2>Read More Read Less Button</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus
imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span
id="dots"
>...</span
><span id="more"
>erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec
congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut
aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac.
In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae
dui eget tellus gravida venenatis. Integer fringilla congue eros non
fermentum. Sed dapibus pulvinar nibh tempor porta.</span
>
</p>
<button type="button" class="btn btn-primary" onclick="myFunction()" id="myBtn">
Read more <i class="fas fa-arrow-alt-circle-up"></i>
</button>
<script>
function myFunction() {
var dots = document.getElementById("dots");
var moreText = document.getElementById("more");
var btnText = document.getElementById("myBtn");
var switchCss = document.getElementById("myBtn");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more <i class='fas fa-arrow-alt-circle-up'></i>";
switchCss.classList.toggle("btn-primary");
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less <i class=' fas fa-arrow-alt-circle-down'></i>";
switchCss.classList.toggle("btn-success");
moreText.style.display = "inline";
}
}
</script>
</body>
</html>