Vanilla JS - So Yummy

June 15, 2020
dev js

Having used a framework or library for so long, one forgets - it's just JavaScript

It's pretty simple, it's just so easy. Brong out some jQuery (or it's already on your page), write some component, because, you now: Reuse. But do you need it?

What I beleieve to be True

The framworks and libraries we use are hardened. They have 10s, 100s, 1000s of people using them and bitching when things go wrong and thus they get fixed. Also, everyone has an opinion on the "best" way to do something and this starts a dialogue that, usually, gives us a better implementation.

But, the issue - there's usually so many things being considered and so many use cases and features start getting added on and next thing you know, what was once something simple, is now a mess.

All that to say: consider javaScript. Don;t forget it. You don't need to have node, install NPM packages (unless you really want to determine is a number is a number) or fancy looking code.

Here's something I put together (from INternet help) after looking around for the easiest way to filter a table. I have been using AngularJS to do this - cause it's so damn easy. But here's the JS version:

function searchName() {

        // Declare variables

        var td, txtValue;

        var input = document.getElementById("input_search");

        var filter = input.value.toUpperCase();

        var table = document.getElementById("body_table");

        var tr = table.getElementsByTagName("tr");        

        // Loop through all table rows, and hide those who don't match the search query

        for (i = 0; i < tr.length; i++) {

            td = tr[i].getElementsByTagName("td")[1];            

            if (td) {

                txtValue = td.textContent || td.innerText;

                if (txtValue.toUpperCase().indexOf(filter) > -1) {

                    tr[i].style.display = "";

                } else {

                    tr[i].style.display = "none";

                }

            }

        }

    }

There's a lot that can be done to this to clean up and make it mo' better. Remove variables that are not needed and inline them. Do some checks to avoid errors. You know more stuff.

Whether you copy & paste into your pages, add this to your own Util lib (that's another discussion, I know) or whatever else, the point is - that's some pretty simple code.

We're no longer in 2005 when you had to seriously be concerned with browser support and multiple "standards" - that boat sailed. And if you do need to worry about that, well, sorry - maybe you should do need a hug lib with polyfills.

But, if you're catering to the masses in 2020 - some good old Vanilla JS can do it for you.