One of the things I’m currently trying to improve in my development is moving away from JQuery. I know I’ve written about JQuery and indeed frameworks like Bootstrap before, even going as far as to bake them into some of the starter projects I’ve published to GitHub, but the reality I’ve learned over the last year of working in an agency environment is that they are a bloaty crutch.
Again, JQuery would, in the past, allow me to repidly implement my own versions of such functions with ease, but as we’ve already established, it’s a big library from a time when vanilla JS would have you go round the houses to tackle a simple task. Modern JS is far more user friendly and DOM manipulations can be impemented just as easily as they can in JQuery.
As an exercise, I put together this simple example of a universal function to control show/hide elements in Modern JS:
As you can see, the results are pretty cool – with a very straightforward bit of JS and some reserved CSS classes we can control the visibility of elements on the page based on interactions with their respective triggers. This functionality extends from dropdown menus to modals and even a mobile nav menu.
For the latter, the inclusion of a class popout–static was key, implementing a popout element that wouldn’t be closed by interactions with other popouts which may be contained within it, only by its own triggers. JS making it simple to check for the existance of this class with classList.contains was the last part of that puzzle, allowing me to make my code as lean as possible.
This is a fairly basic but effective function, but it’s one that I’m already planning on expanding with some accessibility considerations for shifting focus into the popout once it’s triggered, as well as allowing active popouts to be closed using the esc key or by clicking outside of the element itself.
Obviously you can check out the code in the Pen above, but if running things locally is more your flavour, here’s an Express driven Node.JS project you can grab from GitHub.
Let me know if you find this code useful at all by dropping a comment below!