Home > Enterprise >  How Do I Create A Button That Toggles States?
How Do I Create A Button That Toggles States?

Time:10-31

I want to create a button, that when clicked, changes its name and function. The button is called 'Expand', and when clicked it allows a div to expand. Once clicked, I want it to change its functionality and text to 'shrink', where it then shrinks a div.

let expandButton = document.createElement(`button`);
expandButton.setAttribute(`class`, `listButton`);
expandButton.textContent = ` `

if (expandButton.className == `listButton`) {
  expandButton.addEventListener(`click`, (e) => {
    expandButton.setAttribute(`class`, `listButtonClicked`);
  })
}

if (expandButton.className == `listButtonClicked`) {
  console.log(`active`);
  expandButton.addEventListener(`click`, (e) => {
    expandButton.setAttribute(`class`, `listButton`);
  })
}

When the button is clicked, it only expands. Upon being clicked again, it doesn't do anything; the console.log line in the second area doesn't even register.

CodePudding user response:

Yesterday, I wrote a very similar answer here. I've updated my code to include a "show less" button:

for (const el of document.getElementsByClassName('shorten')) {
  const text = el.textContent;
  const summary = text.substring(0, 70)   '... ';
  el.textContent = summary;

  const showmore = document.createElement('span');
  showmore.textContent = 'Show more';
  showmore.style.fontWeight = 'bold';
  
  const showless = document.createElement('span');
  showless.textContent = 'Show less';
  showless.style.fontWeight = 'bold';
  
  showmore.addEventListener('click', () => {
    el.textContent = text;
    el.append(showless);
  });
  
  showless.addEventListener('click', () => {
    el.innerHTML = "";
    el.textContent = summary;
    el.append(showmore);
  });

  el.append(showmore);
}
/* just for demostration purposes. not actually needed */

.box {
  width: 200px;
  height: 100px;
  background-color: lightgray;
  overflow: auto;
  margin: 10px;
  display: inline-block;
}
<div >
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac elementum nunc. Cras vehicula, ante nec iaculis semper, mi justo ornare ipsum, ac sollicitudin tortor tellus at magna. In augue.
</div>

<div >
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac elementum nunc. Cras vehicula, ante nec iaculis semper, mi justo ornare ipsum, ac sollicitudin tortor tellus at magna. In augue.
</div>

<div >
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac elementum nunc. Cras vehicula, ante nec iaculis semper, mi justo ornare ipsum, ac sollicitudin tortor tellus at magna. In augue.
</div>

It should also be noted that there is a <summary> tag that does something similar. However this will not work in your case because you want to dynamically shorten the page.

  • Related