I need to add a css class to elements focused by tab key. I'm able to do this with focusin and focusout events using jquery.
But I don't need to add the class when focus using mouse click. How can I achieve this? Below is my code
$('#main-nav').focusin(
function () {
$(this).find('.submenu').addClass('focused');
}
);
$('#main-nav').focusout(
function () {
$(this).find('.submenu').removeClass('focused');
}
);
Thank you in advance...
$(window).keyup(function(e) {
var pressedKey = (e.keyCode ? e.keyCode : e.which);
if (pressedKey == 9 && $('.something').is(':focus')) {
$('.something').each(function() {
$(this).removeClass('focused');
});
$('.something:focus').addClass('focused');
} else if (pressedKey == 16 && pressedKey == 9 && $('.something').is(':focus')) {
var pressedKey = (e.keyCode ? e.keyCode : e.which);
if (pressedKey == 9 && $('.something').is(':focus')) {
$('.something').each(function() {
$(this).removeClass('focused');
});
$('.something:focus').addClass('focused');
}
}
});
body {
margin: 0;
padding: 0;
}
input {
display: block;
margin: 10px;
font-size: 20px;
background-color: #efefef;
}
.focused {
background-color: #a0a;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form>
<input class="something" name="foo">
<input class="something" name="bar" id="somethingWaitingForFocus">
<input class="something" name="baz">
</form>
</body>
</html>