skip to Main Content

I have a div which contains several buttons. I would like for only the button that was pressed last to have a different style, to indicate that it was button that has been most recently pressed. Clicking elsewhere on the page or on another page should not affect the buttons in the div.

For example:
There are two styles in CSS for the button: unselected and selected. All buttons have the unselected style when the page loads. If I press button 1, it should change to the selected style. If I then press button 2, button 1 will revert back to the unselected style, and button 2 will change to the selected style.

I’ve tried using the active parameter for the buttons, but the button loses active status if I click on another page.

2

Answers


  1. You can archive this by adding an event listener and maintaining the button lastclicked button.

    document.getElementById('buttonContainer').addEventListener('click', function(event) {
      if (event.target.tagName === 'BUTTON') {
        buttonClicked(event.target);
      }
    });
    
    let lastClickedButton = null;
    
    function buttonClicked(clickedButton) {
      const buttons = document.querySelectorAll('#buttonContainer button');
    
      if (lastClickedButton) {
        lastClickedButton.classList.remove('active');
      }
    
      clickedButton.classList.add('active');
    
      lastClickedButton = clickedButton;
    }
    .inactive {
      background-color: #ccc;
    }
    
    .active {
      background-color: #4CAF50;
      color: white;
    }
    <div id="buttonContainer">
      <button class="inactive">Button 1</button>
      <button class="inactive">Button 2</button>
      <button class="inactive">Button 3</button>
    </div>
    Login or Signup to reply.
  2. Maybe something like this? I am assuming you are just using javascript and not React for states. Hope this helps!

    html:

    <

    let lastSelectedButton = null;
    
    function selectButton(buttonNumber) {
    
      if (lastSelectedButton) {
        lastSelectedButton.classList.remove("selected");
      }
      const clickedButton = document.querySelector(
        `button:nth-child(${buttonNumber})`
      );
      clickedButton.classList.add("selected");
    
      lastSelectedButton = clickedButton;
    }
        .button {
          padding: 10px;
          margin: 5px;
          border: none;
          cursor: pointer;
          background-color: #ccc; 
        }
    
        .selected {
          background-color: #4CAF50; 
          color: white; 
        }
    <div id="buttonContainer">
      <button class="button" onclick="selectButton(1)">Button 1</button>
      <button class="button" onclick="selectButton(2)">Button 2</button>
      <button class="button" onclick="selectButton(3)">Button 3</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search