skip to Main Content

I have a set of buttons functioning as "tabs" using anchor tags. The function of the tabs work smoothly, button remain hover untill I click another button. However, all buttons un-hover after I clicked outside of the buttons. How can I prevent this from happening?
Any suggestion would be much appreciated. Thank you!

image: button stays hover after I clicked it

image: buttons un-hover after I click on the blank space

$(document).ready(function(){
  $('.tab-content').hide();
  $('.tab-content:first').show();
  $('.tabs-nav .wp-block-button__link').click(function() {
    let currentTab = $(this).attr('href');
    $('.tab-content').hide();
    $(currentTab).fadeIn();

    return false;
  });
});
.wp-block-button.custom-tab-button .wp-block-button__link:hover,
.wp-block-button.custom-tab-button .wp-block-button__link:active,
.wp-block-button.custom-tab-button .wp-block-button__link:focus {
    background: #CBB07A !important;
    border-color: transparent !important;
    background-color: brown !important;
    color: white !important;
}

.wp-block-button.custom-tab-button .wp-block-button__link:active {
  background-color: #FFF; // Reset background color to default
  color: #000; // Reset color to default
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

I know the focus style works in some cases but it is not the solution.

2

Answers


  1. You can’t do that. But you can add a class to your button when you click on it, and style your class in the same way you style the hover.

    Login or Signup to reply.
  2. :hover occurs when the mouse cursor (pointer) is "hovering" over the element. :focus occurs when the element currently has focus. As soon as you click somewhere else, you move focus somewhere else. So now neither of these conditions apply.

    It sounds like the condition you want to emulate is "the last one that I clicked". One way to do this would be to set a class when you click the element, and style that class as you want. For example:

    $('.tabs-nav .wp-block-button__link').click(function() {
      $('.tabs-nav .wp-block-button__link').removeClass('currentButton');
      $(this).addClass('currentButton');
    
      // the rest of your click handler...
    });
    

    And just add styling for that currentButton class:

    .wp-block-button.custom-tab-button .wp-block-button__link:hover,
    .wp-block-button.custom-tab-button .wp-block-button__link:active,
    .wp-block-button.custom-tab-button .wp-block-button__link:focus,
    .currentButton {
        background: #CBB07A !important;
        border-color: transparent !important;
        background-color: brown !important;
        color: white !important;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search