Five Things (Almost) That You Don’t Need jQuery For

You might be in the habit of using jQuery to perform quick and relatively simple tasks on the front-end of the stack. But especially nowadays, you don’t need jQuery for many everyday web dev tasks. Vanilla Javascript will do the job fine, and with less overhead.

The Problem with Using JQuery

There are a few things you need to do to set up jQuery on a webpage. First, add a script reference to jQuery in the page head. Then make sure that script src points to a CDN or a copy of the jQuery library living on your company’s server. Finally, write the script and test to make sure jQuery has loaded.

Easy, right? But what if the CDN goes down? What if the company server coughs up the script, or, more likely, it clashes with another copy of jQuery somewhere? One of the most stressful parts of web development is unforeseen deployment issues, and you just want to code, right?

Nowadays you don’t need jQuery for a lot of tasks. Javascript does these jobs just fine.

The thing is, nowadays you don’t need jQuery for a lot of tasks. Javascript does these jobs just fine, and with less overhead. Here are five things you can do in Javascript alone, without the help of jQuery:

Selecting an Element

Selecting an element is one of the most fundamental things we use jQuery for. It’s pretty simple. In jQuery:

That dollar sign is called syntatic sugar, and it’s supposed to make reading a language easier. But you really don’t need jQuery to do this. You can just as easily write this expression in Javascript:

Changing CSS Styles

You can directly change the CSS styles of elements with jQuery, right? It’s something you might do like so:

See the Pen aGayEx by Float Nine (@floatnine) on CodePen.

But why use an external library when you can do it with Javascript:

See the Pen vjzJoy by Float Nine (@floatnine) on CodePen.

Adding a Class

jQuery makes this easy! Like this:

Why would you do it any other way? Because you don’t need jQuery to do it. It’s just as easy in Javascript:

 Adding a Click Event

This is one thing that jQuery certainly does better than Javascript, right?

See the Pen pVOWwB by Float Nine (@floatnine) on CodePen.

Again, NO. Why not just do this with Javascript:

See the Pen odPGyw by Float Nine (@floatnine) on CodePen.

Wrapping Your Script in a $(document).ready Function

Okay, surely this is a job for jQuery. The $(document).ready wrapper ensures your code is scoped and gets executed after the page has loaded. For example:

See the Pen ELebaW by Float Nine (@floatnine) on CodePen.

This codepen doesn’t really do anything, but if there were code inside the $(document).ready function, you could be assured that it would execute after all of your HTML elements loaded. That’s a handy feature, as it takes time for your browser to render each element on the page, and if your script is manipulating elements, you want to make sure they’re there. Well, you don’t need jQuery for this either. Not exactly, that is…

Here is one way to try to mimic $(document).ready with simple Javascript:

See the Pen VxGrex by Float Nine (@floatnine) on CodePen.

This will do the trick in most browsers, but not IE8. Increasingly, that’s not a problem anymore, as a lot of companies are phasing out support for anything before IE9, or IE10. If you must support IE8, you can do something like this:

See the Pen aGaVmy by Float Nine (@floatnine) on CodePen.

By putting your script after all HTML elements (other than the closing body and html tag) you are safeguarding against the browser not having loaded the elements the script uses. The generic function wrapper makes sure the script fires without prompt. This isn’t perfect, either, as there are times when a browser renders some objects or elements after the initial page has loaded. But it’s a pretty good alternative, and will work fine most of the time.

But this last example brings up a greater point. We’ve gotten into territory where the solution to the problem has gotten a little complicated. Do we use jQuery here, or do we try to achieve the same with vanilla Javascript? Those kinds of decisions are ultimately up to you, and you should get in the habit of knowing what you do and you don’t need jQuery for. What is important is not that you make flawless decisions every time, but that you know the benefits and drawbacks of the different routes, and stand behind your decisions accordingly.

Taking Risks in Code to Build Your Confidence

If you’re a programmer, you probably fall into the bad habit, at least sometimes, of comparing yourself unfavorably to other programmers. That guy or gal who sits across the office from you and seems to be able to tackle large and complex problems with ease. “Will I ever be as smart or as skilled as them?” you wonder. “What separates them from me?” While experience and talent no doubt play a role in programming, one thing that programmers often overlook is the power of confidence gained from risk taking. Since computers can only do exactly what we tell them to, and it’s easy to make small mistakes with large consequences, changing even a small part of your code can often be an anxiety inducing experience. While the best code is loosely coupled and appropriately abstract, all code is susceptible to being broken by change. So we’re conditioned to make as small a change as possible, sometimes manually altering the input we feed into a program instead of altering existing code, in order to mitigate the risk. The result is that we miss out on the opportunity to build confidence as programmers.

Take the following example: Your boss gives you a spreadsheet with 1,100 rows of data, each one representing a car that the company has recently purchased. Your boss wants you to enter each car into the database. Obviously, this is a job for a small script. No problem. You look at the first five rows and see this (we’re keeping things simple for the sake of example):

3LexusES 3002014

Seems easy. The script needs to import the file, and then read it line by line. For each line it needs to create a record in the database, with the make, model, and year of the car. So this is your solution:

This script reads the file, cars.csv, into a while loop, and line by line, it calls the function “insertIntoDB()” and passes in an array representing the row it is currently looking at. You run the script on the test database and leave to grab a cup of coffee, confident that you have tackled the job quickly and painlessly. When you return to the office, however, your boss comes to you and says, “Actually, we need to make sure that only cars made on or after the year 2005 get entered into the database.” Okay, this is a little more complex, but an if statement should do the trick. Just wrap it around the call to insertIntoDB, so only those cars made on or after 2005 get through. Something like this:

Is it really going to be this easy? Your programming instincts are telling you no. You take a closer look at the spreadsheet, and just as you suspected, there are some complications further down the line:

8TeslaModel S2018

Lines one through five were fine, but lines six and seven have a year format of XX, and line ten has a year with quotes around it, like this: “XXXX”. Your new code will not work in any of these instances. You scan through the next hundred records and see that every fifth record or so uses the XX format for the year, and every tenth record uses quotation marks.

Well, now we have a decision to make, we can solve the problem in a non-programmatic, less risky, and less confidence building way, or we can do it the programmatic, riskier, more confidence building way. Let’s take a look at both.

The Less Risky, Initially Easier Way

Here are the first ten lines of the spreadsheet, all together this time:

3LexusES 3002014
8TeslaModel S2018

We’ve already identified the problem, we have differently formatted years. 1,100 rows isn’t nothing, but we could go through the spreadsheet ourselves (as in, opening up a spreadsheet app and tabbing through each cell one by one) and manually change the oddly formatted years to be four digit numbers with no quotes around them. Sure, it would take a little bit of time, but you wanted to take a break from thinking too hard today, anyways. Just put your headphones on and mindlessly plug through it. It will be like taking a mini break from your job, while still appearing productive, you tell yourself. Sounds tempting, and as an added bonus, you will be able to see to it yourself that all of the years are formatted properly, reducing the risk that the output in the database will not be as expected. But let me argue here that it is the very thing that makes this appealing, the idea of kicking back and wasting an hour doing something repetitive but easy, that makes it a bad idea.

Ask yourself, “What do computers do well that humans don’t?” Not a lot. In addition to being able to make calculations and logic based comparisons (just another kind of calculation), us humans can write symphonies, books on philosophy, and yes, even tech blogs (cue applause). But there are some things we’re not as good at. While a math wiz can bang out a hundred calculations in a minute, that’s nowhere near as fast as even an older model computers can. Plus a computer can do these calculations for weeks on end without rest, while humans get tired after the first couple of hours. Think of everyday things  computers do for us, like compressing video, sending it halfway around the world, and decompressing it on our friend’s computer screen so fast that it appears we are speaking to them in real time. At its heart this too is just a computer doing a large amount of simple calculations very, very fast.

I know this might be pretty obvious to a lot of people reading this, but the point I want to drive home is that to be a good programmer, you have to always keep this in mind, and let computers do this one thing they know how to do very well. In this particular instance, that means asking it to loop through a list of 1,100 records and format the dates itself. You could do the formatting yourself, and there are obvious advantages to it, but you are missing the opportunity to build skills that will let you tackle the next data set that is say, 10,000 records long, much too big for you to complete efficiently. And more importantly, the risk you take by doing things the hard way will build your confidence as a programmer, which is a much greater gain than saving yourself a little time and stress in the shortrun.

The Riskier, Initially Harder Way

So we’ve decided to do things the slightly riskier way, and we’re back to our original problem: we’ve got three different year formats and we need to compare each one to an integer, 2005, and filter out the ones that are lower in number (or earlier in year, whatever you prefer). Here’s a snippet of our data set again:

3LexusES 3002014
8TeslaModel S2018

The question before us is, what are the (potentially code breaking) features we need to add to our script? Well, we need a function that does essentially what we were thinking of doing by hand a minute ago. It needs to trim the potential quotation marks off the year, and, since some year values will be two digits, it needs to grab only the last two digits of the year for the comparison. A few lines of code should get us set up:

rtrim() and ltrim() remove the quotation marks. Then substr() gives us just the last two digits of the year. Finally, a ternary operator returns true if the last two digits are higher than 05, for 2005 and lower than 18, for 2018 (it’s unlikely that any cars on the spreadsheet were made between 1905 and 1918, so this should be fine).

Note that while in this example, adding an extra function is not likely to break your code in any way that is difficult to repair, when you have an existing script that is say, 5,000 lines long, adding a new function and calling it from within the code could mess things up in unexpected ways. But it’s still worth doing!

So what did we do here that a computer couldn’t do just as easily? We asked ourselves a philosophical question. “What is a year, in this context?” We decided, “A year is at minimum a two digit number, with no quotation marks.” But what if there are some values in the spreadsheet like this:


Or this:


After a little thought, we decide that we want to strip off all non-numerical characters from our string, not just quotation marks. Here is a function that will do that:

Now we’ve accounted for not just the unusual formats we’ve come across already, but also a large set of potential formats that we’ve anticipated might exist, based on what we’ve seen so far. This sort of intuitive problem solving is what we are still much better at doing than computers, so it’s beneficial that we’ve taken on this task ourselves, and asked the computer to do the repetitive stuff. Humans for the win! The preg_match() function just compares a string, in this case $year, to a regular expression,  “/\d{2}$/” and puts the results into an array called $matches. For more on preg_match, see this, and take a look here to learn more about regular expressions.

Now, there could be some nonsense year values in the spreadsheet that our function hasn’t accounted for: “2022956,” or “unicorn,” for example. But who knows what these are supposed to mean in the first place? The above function will take the number “2022956” and return “56,” which is as good a guess as any, and it will return a blank string for “unicorn,” which is also as good a guess as any, because there’s no such thing as “unicorn” year (at least as far as I know). What we have written will probably work for 95% of our records, and possibly for 100% of them. So that’s a pretty good spot to be in. Here is our final code:

What’s The Point, Even?

So you might reasonably ask, “What was the point, really, of doing things the harder way? 1,100 records isn’t that many. In the time it took to conceptualize what a year is, and write a function that covered as many potential formats for it as possible, we could have just changed the values in the spreadsheet ourselves, and with less expended brain power.”

The answer is, while I understand the urge to do it this way, that won’t ever build your confidence as a programmer. Anyone can go through a spreadsheet and manually change numbers. By doing things programatically, and enhancing your code as you go, instead of mitigating risk by avoiding making changes to existing code, you are taking on some manageable risk and building your confidence as a programmer, and confidence is a valuable thing to have. Today you’ve tweaked some code that affects 1,100 records. Tomorrow you will be comfortable adjusting code that accepts 2,000 records, and after that 5,000 and 10,000. You will be better at reading large blocks of source code, and seeing what the effects are of changing a specific part of the code to make it more robust. And if you mess up, you will be better in the future at finding where the problem occurred in the code, and how to fix it.

The more you are willing to risk making mistakes, the better you’ll become at programming, and the stronger and more error free your code will be. That knowledge and confidence pays off in the end, because you’re really not as different from that person across the office from you as you might think.

What Is an Event Object?

Web developers use them commonly, but most can’t answer the question: What is an event object? The answer lies in a broader question: what, exactly, is an event? When a user is interacting with a web page, they are triggering a series of events based on their actions.  When they type something into a form field, click a link, or scroll down the page, they are creating a new event. It’s just a matter of capturing them. A captured event exposes an event object for the developer to work with.

Capturing an Event

The web developer has the opportunity to capture every event the end user triggers. The user triggers events of course by providing input to the computer through the mouse or keyboard. To answer the question, what is an event object, the developer has to first capture one of these events. The developer captures events by creating event handlers, chunks of code that fire when the event is triggered. Then and only then does he or she have access to the event object.

Consider the following code:

This is a simple event handler. The event object is passed into the function in the variable “event.” It doesn’t matter what you name it, but you will often see it referred to as “event” or simply with the letter “e.”

So What is An Event Object?

Event objects are special objects (a collection of methods and properties) that are only available inside event handlers. They are used in two main ways, to stop the expected results of the event from happening, and to get useful information about the event.

First Purpose: Stop the Expected Results of the Event From Happening

Let’s look at the event handler again:

Here we have called a function of the event object: preventDefault( ). When a user clicks a link, the browser’s default action is to load a new page. preventDefault( ) tells the browser, “Don’t load the new page, stay on this one.” preventDefault( ) is useful in these cases, because often times you want to stay on the current page. At least until you have executed the code inside the event handler.

Second Purpose: Use Information About the Event to Make a Decision

Now consider the following code:

timeStamp is an event object property that tells us the number of milliseconds that have elapsed since the event was created. In most cases, this is when the page was loaded. This information isn’t particularly useful on its own, but we could add it to an “if” statement to achieve something a little more meaningful:

Here we are saying, “if it has been six seconds (6,000 milliseconds) since the page has loaded, stop the link from working and provide an alert message to the user.”

The event object can also tell us what other input the user gave when the event occurred. Consider the following code:

The shiftKey property is only true if the Shift key is depressed.  So here we are saying, “if the user had the Shift key pressed down when they clicked the link, show this alert message.”

In Conclusion

Whenever an event occurs on a page, we can capture information about the event in an event handler, and take some useful action. Event objects are the collection of functions and properties that allow us to do get this special information about the event, and act directly upon it. For example, event.preventDefault( ) allows us to stop the default actions of the event from occurring. Properties like event.timeStamp and event.shiftKey tell us when the event occurred, and one thing that was happening at the time of the event, respectively. In a nutshell, event objects give you fine grained control over real time events occurring on your site.


Thanks for reading. Please let me know what you thought in the comments below.