jqueryclassfocusoutfocusin

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


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');
            });
        });

Solution

  • 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');
      }
    });