Hello developers! π¨βπ»π©βπ»
I'm a CS student and im learning javascript because i want to be a frontend developer , and today I wanted to share a concept I recently learned while making a simple "Show More / Show Less" button using JavaScript.
can you tell what the diffrence between the first code and the second
and witch one is true !!
I was trying to create a button that toggles the visibility of text, like this:
simple html 2 paragrah one of them with the class of text hidden-text
it the one we will toggle and a button that will do the job
<p>lorem ipsum dolor sit amet consectetur adipisicing elit. </p>
<p class="text hidden-text">fsdfsfsd .... </p>
<button class="show-more">show more....</button>
css:
.hidden-text {
display: none;
}
ive declared all the variable i need
let showButton = document.querySelector(".show-more");
let text = document.querySelector(".text");
let value = false; // Initially, the text is hidden
my first code was :
showButton.addEventListener("click", (value) => {
value = !value;
text.classList.toggle("hidden-text");
showButton.textContent = value ? "show less..." : "show more..."; // Update button text
});
but this didn't work the value was always false even that i swithced using value=!value
after some search i found out why this happend
Every time the button was clicked, the local value parameter inside the callback function was being redeclared, which shadows the outer value.
that means that The outer value remains unchanged, always staying false.
and The local value is toggled inside the callback, but it only exists during that function's execution and doesnβt affect the outer value.
To solve this, I needed to remove the value parameter from the callback and directly use the outer value that persists across button clicks.
let value = false; // Persistent state variable
showButton.addEventListener("click", () => {
value = !value; // Toggle the outer value
text.classList.toggle("hidden-text");
showButton.textContent = value ? "show less..." : "show more..."; // Update button text based on value
});
Top comments (0)