DEV Community

Cover image for Fixing a "Show More / Show Less" Button with JavaScript
AZIZ NAJLAOUI
AZIZ NAJLAOUI

Posted on

Fixing a "Show More / Show Less" Button with JavaScript

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:
show more

show less

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>

Enter fullscreen mode Exit fullscreen mode

css:

.hidden-text {
  display: none;
}
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)