Search code examples
javascriptcsstypescripttailwind-css

Change button color in Tailwind/TypeScript when button is Active


I have a Carousel Object which contains Buttons. These buttons represent the "Semester" content shown below (an image is provided below).

enter image description here

I want the "semester 1" button to be Dark Blue by default and when another button is clicked I want that button to be Dark Blue.

At the moment I can achieve this when I add the following focus: class to the Button Component but since it's a focus class it turns light blue the moment I click somewhere else and the button "semester 1" is not dark blue by default:

class="rounded-full w-64 dark:bg-blue-300 dark:hover:bg-blue-500 focus:bg-blue-500"

enter image description here

I tried adding an class="active:bg-blue-500" but was unsuccessful. Why doesn't adding an active class work, and how can I make this work?


Solution

  • The pseudo class active is corresponding to when the user has an interaction with an element (in this case, when the user is clicking on the button), but once the interaction is over the pseudo class won't be active.

    What you want cannot be done with only css, you need some javascript to add a stlye or a class to the button you clicked on (and remove those class / style on the last clicked button)

    For example if you are in vanilla js and you have three buttons with the class "navigation-buttons", what can do what you want is to add a class 'active' when one is clicked.

    
    const buttons = document.querySelectorAll('.navigation-buttons')
    buttons.forEach((button) => {
      button.addEventListener('click', () => {
        // Remove active class on all buttons
        buttons.forEach((b) => b.classList.remove('active')
        // Add active on the one clicked
        button.classList.add('active')
      });
    });