Kartones Blog

Be the change you wanna see in this world

You don't always need jQuery

Update #1: Added .addEventListener alternative to .onclick to keep existing handlers. Thanks @JohnHackworth.

Update #2: Added an excellent and way more complete reference at the end.


Disclaimer: Pretty introductory Javascript follows. If you were looking for advanced tips, migration techniques and the like, go somewhere else.


It's been at least one year since I last touched client-side javascript. Back then, we were quite pragmatic and relied on jQuery for most Javascript tasks; it's easy, quite well documented and has really good maintenance, bugfixing and updates. But I was also either using it or ZeptoJS even for tiny personal projects, so the other day I thought: "maybe vanilla Javascript and its query selectors are enough for simple tasks".

Chrome and Firefox have always been quite fast adopting changes, but the burden of Internet Explorer was everpresent. Now that everything below IE8 (and soon IE9) is considered not worth the effort and even mobile phones ar on par, I decided to do some small tests. And my results cannot be more satisfying... For trivial stuff you no longer need to rely on jQuery at all.

I'll simply provide four small code examples to summarize the scenarios I had to change: Clicking things, attaching events (with and without delegation/bubbling up), selecting N items and showing/hiding nodes. There are many scenarios where jQuery is of use or maybe not so easily replaceable, but for quick PoCs, pet projects and internal tools... .

 

Click on a node

jQuery

$("myId").click();

Vanilla

document.getElementById("myId").click();

 

Show/Hide

jQuery

function ToggleSection(eventData) {
  $("p").each(function (index) {
      $(this).hide();
  });
    $("s" + eventData.currentTarget.id).show();
}

Vanilla

function ToggleSection(eventData) {
  var i, len, $p = document.querySelectorAll("p");
  for (i = 0, len = $p.length; i < len; i++) {
    $p[i].style.display = 'none';
  }
  document.getElementById("s" + eventData.target.id).style.display = 'block';
}

 

Attach event handlers

jQuery

$("h3").each.on("click", ToggleSelection);

Vanilla

var i, len, $h3 = document.querySelectorAll("h3");
for (i = 0, len = $h3.length; i < len; i++) {
  // Option A: Overriding previous handlers
  // $h3[i].onclick = ToggleSection;
  // Option B: Adding a handler keeping existing ones
 
$h3[i].addEventListener("click", ToggleSection);
}

 

Attach event handlers (event delegation)

jQuery

$("bookmarks").on("click", "h3", ToggleSelection);

Vanilla

document.getElementById("bookmarks").onclick = function(eventData) {
  var target;
  eventData = eventData || event;
  target = eventData.target || eventData.srcElement;
  if (target.nodeName == 'H3') {
    ToggleSection(eventData);
    return false;
  } else {
    return;
  }
};

 

I have ommited other query selectors and additional properties but Mozilla Developer Network has really good documentation for them.

This post series also have much more detailed guides of migrating from jQuery.

On Consumerism

Offtopic rants about how I see consumerism and try to fight it. Instead of vague advices, real brand names and real numbers (in Euros, current prices at Spain).

 

Consumerism is the way capitalism tries to counterattack the fact that we could have many goods last for a lot more than before, being much better and for a fraction of the original price, but tricking us into constantly buying new "versions" of things, no matter if is a real need or not.

This are just a few tech-related examples of how I recently (last months) triend to be a bit more rational:

  • I now pay almost half of what I paid for a Pepephone's 10Mb DSL line (24€/month). In a world where you suck if you don't have optical fiber and "at least 100Mb", I'd rather pay the lowest DSL rate (with a provider that has good reputation) than pay twice or more for something I'm not going to use even at 10% of its capacity.
  • I dropped the house landline, despite Movistar giving it for free to me "if I stayed". It was just a source of phone spam, so let's be lean and "elimitate waste", if I don't need it, out of the equation.
  • I pay the lowest data plan for my mobile line with Pepephone because I almost don't make calls (~10€/month). I have no push notifications except for Whatsapp (and no lock screen notifications except a green Android "notifier light"), I don't need "audio tethering" as I have my old beloved MP3s which I can just copy in the phone's memory, so I'm far from consuming not even half of my data plan (1.2GB).
  • I gave my iPhone 4 to my girlfriend after 3 years of using it and bought a cheap bq Android phone (145€, Aquaris 4.5E model). It's faster than my old iDevice and I charge it twice a week, plus is way more open for development if I want to dig into. I could also destroy 4 of this phones and still be cheaper than a the cheapest iPhone 6.
  • I sold my XBox 360 & games* and used that money and a bit more to buy a PS3 and 21 games for about the price a PS4 costs (I spent ~430€). The console and a few games are new, others are 2nd hand. For me the quality or interest of a console is the sum of its games, not some hardware specs.
  • I used to buy tons of Steam games (408 games) and Kickstarters (14 projects backed including boardgames). As my time is quite limited, I now wait and think twice before shopping or directly wait for sales/offers, as I already have lots and lots of "pending entertainment".
  • I hate Macs (except their trackpads which are awesome), so when I switched my laptop a year ago (after ~5 years of service of last one) I chose a Dell XPS 12.5" ultrabook (1200€). 4th gen i7, SSD, 8GB RAM, 8h of battery and FullHD "pseudo-retina" screen for less than a MacBook Pro. And a touch screen I disabled the first day and never used again.

 

With all this I am not saying "I rock, you suck", I am just asking "are you sure you really need that?".

Consumerism will always reply "yes, don't think and just do it!". I'd rather spend more money in buying better organic food and having the pleasure of tasty meals, than in the latest tech**. And I love my tech-related job.

 

 

* The collector inside me is strong, but I no longer get so attached to physical consoles and games. I already have lots of consoles and games like a perfectly working original Game Boy, but I prefer to "exchange" consoles and play more titles than pile up games I've finished and might not get back to ever again.

** I know a lot of people who prefers to save on food (eat worse & cheaper) than cut on technology.

OpenSSL certificate verify failed on Ruby & Windows

I was just checking a more automated way of cleaning my non-recent Twitter posts when, running the small program, I got hit by an error like:

OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=...
read server certificate ...: certificate verify failed

 

If you check around the net, the first solution they say is to add this dangerous line:

OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE

 

But, deactivating security is not the best approach, so after some digging I came across a nice post that explains the issues, how to debug the specific problem, and partially how to solve it. As I use Windows, the instructions weren't so complete, but it all sums to:

  • Download a CA certificate bundle, like for example Mozilla's
  • Install the .crt file (I installed it for All Users)
  • Setup the following OpenSSL system variables:
    • SSL_CERT_DIR: Point to where you left the CA bundle
    • SSL_CERT_FILE: Point to the .pem file

Restart your command line, and you should be able to run with SSL peer verification active (as you should).