Issue with JQuery event handler

Hello. I'm animating a navbar which responds to mouse and keyboard events using JQuery event handlers to ensure a proper UX. Most part is done, however there remains one last issue where clicking/focusing on a link and un-hovering right after, the "highlighter element" returns back to its initial location. https://codepen.io/Suggon/pen/MWzqByj?editors=0010 The highligher is a live element conrolled by JS. In order to animate moving towards the target, I used the .on('mouseenter focusin', function() method which is working nicely. Out of intuition, I also used .on('mouseleave focusout', function() for its "reverse" - that's the one which did not work. The apparent reason being that it's listening to EITHER mouseleave OR focusout. So assuming we clicked on a link to gain a focus state, the highlighter doesn't retain itself, since the mouseleave event is fired despite the element being still on focus state. I thought of googling the issue but got lost on words on how exactly to search for it. Much appreciated if someone could help me out.
2 Replies
RAiDeRTuRbO
RAiDeRTuRbOβ€’6mo ago
To ensure that the mouseleave event does not occur when the tab item is clicked or focused, you need to check if the element is currently focused and prevent the mouseleave action in that case. Here’s how you can adjust the code: 1) Add an event handler for the click event to set a flag indicating that the tab item is clicked. 2) Modify the mouseleave event handler to check if the tab item is clicked or focused before removing the style. Hopefully that points you in the right direction!
Suggon
SuggonOPβ€’6mo ago
Thanks, I'll try getting something out of it! I tried following your suggestions and amidst of it, coincidentally figured out a different way to get the issue solved πŸ˜… So all that had to be done was to pass the active tab between clicked items, and now the result is looking satisfactory enough without adding further event handlers and checks (also updated in the codepen above)
// retain highlight on clicked tab by delegating the active tab to it
$tabNavListItems.on('click', function() {
$(currentActive).removeAttr('class');
currentActive = this;
setProps(this, $tabNavList);
$(this).addClass('active-tab');
});
// retain highlight on clicked tab by delegating the active tab to it
$tabNavListItems.on('click', function() {
$(currentActive).removeAttr('class');
currentActive = this;
setProps(this, $tabNavList);
$(this).addClass('active-tab');
});
Nevertheless, thank you very much for the tips, they'll surely be of help in the future πŸ‘
Want results from more Discord servers?
Add your server