Refactored JavaScript Without jQuery

The Example

I was googling the other day for some ideas for a new post. I was looking at using the GitHub API in order to demonstrate the ES6 fetch API. I came across this user’s GitHub hosted page. The is a cool idea, as a small project. It’s a great example of how to use the GitHub publicly exposed rest API, however, I noticed a few things in the code. At this point, I changed the focus of my post. Caius, if you’re reading this post, it’s nothing personal. You can see his original repository here. This site is using JavaScript with jQuery where a user submits a form with their GitHub username in it. This then hides some elements, shows some others and allows a user to hit a link and tweet the response.

Keep in mind I’m not opposed to using jQuery, I use it all the time and it’s great for a lot of repetitive tasks that we can make shorter with jQuery. At the same time, it’s also important to realize that the code below is actually shorter in my implementation and I achieve the same outcome. My code is not perfect either, but I wanted to prove a point. That you can get away without jQuery. Many of my first projects using JavaScript, I relied heavily on jQuery not realizing that it was possible to do many of the same things just as easily in Vanilla JS.

Original Source Code

View the original source JavaScript and jQuery below. In my project, I split it out into HTML, CSS and JavaScript files, but this original was all in one html file and still works well.

function get_github_id_for (username, callback) {
 
      $.getJSON('https://api.github.com/users/' + username + "?callback=?", {},
       function(json){
         var id = json["data"]["id"]
         if (id) {
           callback(username, id)
         }
         return false
      });
    }
 
    function add_twitter_link_for (username, id) {
      var tweet = $('<a>').text("Tweet this").attr('href', "https://twitter.com?status=" + encodeURIComponent("Found out I'm GitHub user " + id + " by using http://caius.github.com/github_id/#" + username + " #GitHub_id")).insertAfter("#success h1")
    }
 
    function show_user (username, id) {
      $('#username').text(username)
      $('#id').text(id)
      $('form').hide()
      $('#success').show()
    }
 
    $(document).ready(function() {
 
      if (document.location.hash) {
        // $('form p').show()
        var name = document.location.hash.match(/^#(.*?)$/)[1]
        get_github_id_for(name, function(username, id) {
          show_user(username, id)
          // $('form p').hide()
          $('form h1').hide()
          $('form').show()
        })
      }
 
      $('form').submit(function(event) {
        event.preventDefault()
 
        $('form p').show()
        var name = $("#github_username").val()
 
        get_github_id_for(name, function(username, id) {
          add_twitter_link_for(username, id)
          show_user(username, id)
          document.location.hash = "#" + username
        })
 
        return false
      });
 
    });
 
</a>

How to do the Same Using Vanilla JavaScript

Below is the refactored code, not using jQuery to do the same, I put in the HTML, the button click event to submit the form, but other than that all functionality is in this script, and not need to import the jQuery library via CDN.

//show and element
let show = function (elem) {
    elem.style.display = 'block';
};
// Hide an element
let hide = function (elem) {
    elem.style.display = 'none';
};
 
async function getUser(name) 
{
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}
 
const success = document.querySelector("#success")
const input = document.querySelector("#input")
const finding = document.querySelector("#finding")
const submit = document.getElementById('submit')
 
function add_twitter_link_for (username, id) {
    let tweetLink = "https://twitter.com?status=" + encodeURIComponent("Found out I'm GitHub user " + id);
    let a = document.querySelector('#tweet'); //or grab it by tagname etc
    a.href = tweetLink;
}
 
function show_user(username, id) {
  document.querySelector('#username').innerHTML = username;
  document.querySelector('#id').innerHTML = id;
  hide(input);
  show(success);
}
 
let submitForm = function() {
  show(finding)
  let name = document.querySelector("#github_username").value;
  getUser(name).then(function(data){
    add_twitter_link_for(data.login, data.id)
    show_user(data.login, data.id)
  })
};

Show and Hide

You’ll notice that I’ve created two functions for showing and hiding elements, jQUery has this same functionality out of the box, with using an element selector and then show or hide it. Easy using Vanilla code.

Fetch or Ajax

Something else that was quite common a few years ago was using jQuery’s ajax/getJson functions for working with REST api’s. They’ve since deprecated some of the callback functionality, in order to avoid callback hell. fetch makes this so much cleaner in my opinion, especially when using it as an async function and the then() to call the needed functions for working with the DOM to modify it.

document.querySelector()

If you really wanted to shorthand this you could write a similar function to how I did the show and hide functions. But for this example, all I did was was use document.querySelector('#example_id'). This is in my opinion just was easy and clean enough to use. There is also the document.querySelectorAll() which will return an array list of elements that have the class or id that’s passed into it. Very similar to jQuery, the newer ES6 implementation took a lot of what was being used regularly and made it a part of the specifications.

The add twitter link function was also in my mind something that was actually more straightforward using plain JavaScript. Notice the implementation is setting and modifying the DOM, and needn’t one line of jQuery.

In the End

In the end, my code is about 10 lines shorter, and in my opinion easier to read and follow. Believe it or not, this probably the most important part about writing code. Making sure that those who come across it in the future (this includes yourself), understand it. For a view of your GitHub Id, you can check out the refactored form submission page here.