Add class to each link when it has focus (jQuery)

39 Views Asked by At

I have the code below. The problem is the class is added to all links on the page and not the one in focus.

$('a.going__outside').on('focusin', function(){
        $('a.going__outside').each(function(){
            $('a.going__outside span').removeClass('sr-only');
            }).on('focusout', function(){
                $('a.going__outside span').addClass('sr-only');
            });
        });
1

There are 1 best solutions below

0
Barmar On BEST ANSWER

Use $(this) to operate only on the element that received the event.

$('a.going__outside').on({
  'focusin': function() {
    $(this).find("span").removeClass('sr-only');
  },
  'focusout': function() {
    $(this).find("span").addClass('sr-only');
  }
});