Search code examples
javascriptjquerybuttonsafarifocus

Alternative solution for :focus on multiple buttons


I'm struggling to find a different solution for :focus when clicked on a button, as Safari doesn't support :focus on buttons.

I have a field of 16 buttons, which should change colours when clicking on it and loose it when different button is clicked.

I have created this fiddle to show the events. toggleClass is not the right solution and would like to avoid :focus.

Current JS code:

$(".tbl-button").on("click", function() {
        $(".tbl-button:focus").addClass("table-btn-color");
});

Solution

  • You can just change your css declaration from .table-btn-color to .tbl-button:active.

    but if you want to use jQuery you can do it like this

    $(".tbl-button").on("mousedown", function() {
      $(this).addClass("table-btn-color");
    }).on('mouseup', function(){
      $(this).removeClass("table-btn-color");
    });
    

    In order to retain the class on the selected element you can do it like so:

    $(".tbl-button").on("mousedown", function() {
      // remove the class form all .tbl-button elements
      $(".tbl-button").removeClass("table-btn-color");
      // add it to the currently pressed element
      $(this).addClass("table-btn-color");
    })