- Overview
- Transcript
1.2 JavaScript Without jQuery
In this lesson, we’ll take some jQuery-enabled code and convert it to vanilla JavaScript step by step. We’ll look at several common parts of jQuery’s API, and I’ll show you how we can accomplish the same thing using the standard DOM and JavaScript ES6.
Code Snippets
For HTTP requests, we’ll use fetch
:
fetch("data.json").then((response) => {
response.json().then((obj) => {
});
});
For selecting elements, we’ll use methods of the document
object:
let doc = document;
doc.getElementById();
doc.querySelectorAll();
For manipulating an element’s CSS classes, we’ll use the classList
object:
element.classList.add("my-class");
1.2 JavaScript Without jQuery
[SOUND] In order to demonstrate this idea of going from jQuery to just pure vanilla JavaScript, I thought that we could rewrite a jQuery enabled script. So, this is the page. There is a button that whenever you click, it's going to make an HTTP request to retrieve a JSON file. And inside of this JSON file is a title, and then the items that are displayed here. So, we are basically going to populate the content of this page. Now, if you'll notice whenever you load the content, the items fade in, so that's something that we also want to replicate as we are rewriting this code. Now, let's look at the HTML, it's very simple. We have our button element, and has an idea of container loader, and then there is this dev element with an idea of container inside of it is an H three element for the title. Then there is a UL element for our list of items. As far as jQuery is concerned, I'm using a CDN, just to keep things simple. And then script.JS is the file that we are going to be editing. Now, as far as CSS, there's just a font size set to make the fonts larger, so that you can see them easier on the screen. And then the UI element has a display of none, so that it will fade in. We will need to change the CSS because in order to make this element fade in, we're going to use CSS transitions, because that's how we do animation now. We don't do it with JavaScript. So, as far as the data is concerned, we have our title. We have our items, and that's basically it. So, here's the script. It's very simple, but it also uses a lot of the API that we would use on a daily basis. For example, we have set up click event a listener, we're using the Get JSON method to retrieve our JSON file. We're using the jQuery function to get elements in the DOM to find elements to set the HTML of elements, as well as appending to another element, then finally, the fade end. So, let's get started. And we'll start at the very top by changing the way that we set our event listener. So, we're going to be using standard methods. That means that we're going to use the document object. Document is quite a bit to type. So, I'm going to create a variable something called Doc, so that we can get to those methods much faster. So, instead of using the jQuery method, we're going to say Doc, and then get element by ID. Now, of course, this is more code, but our code is going to execute faster because, well, it's using the standard API. So, we are retrieving that elements. We want to call the addEventListener method, and we pass and click for the click event, and then we will use the existing function that we have now, except that now, our event object is not a jQuery event object that is going to be a standard Dom event object. Now, let's go ahead and save it. Let's go and look at the browser and make sure that that works. Of course it does, that wasn't a very big change. So now, let's talk about how we can make an http request. Now of course, there is the xml http request object that we could use, but, that's old school. Today, we have the new sexiness that's called fetch, now, all of the modern browsers support fetch. However, if you want to use fetch in older browsers, you have to use a poly fill. Which, in my book, is okay, actually, it's more than okay. Because it allows us to use new standard APIs in older browsers. And while it is technically a dependency, it's one that will eventually go away, and we won't have to rewrite any of our code, unless if the API changes, and we would have to update it, which we would have to do anyway. So, we're calling fetch, and that's going to return a promise. So instead of saying dumb, we're going to say then. And instead of getting the parsed JSON object, we get a response, because that makes sense. We are fetching data using an HTTP request. We are getting a response in return. And with that response, we can get a lot of information. One of those is the parsed JSON. So, we're going to call this JSON helper method, and this returns a promise. So we're going to say then. And we will have a callback, but the argument that's going to be passed to this callback is our parsed JSON object. So basically, we're going to take this code that we had, going to cut it and paste it inside of this callback, and everything should still work. So, let's just make sure, let's go the browser. Let's load content, everything's fine. So, now we want to retrieve our container, well, that's easy enough to do, we'll use the get element by ID method, but then we also want to find the UL element inside of the container. Now, we can do that with querySelector. Because some people, and maybe a lot of people don't fully know that you can use the querySelector method and the query selector all method on element objects in order to search within that element. So, it's exactly like the find, except that it's native, and it's going to execute faster. So, we are retrieving that ul elements, we're going to do the same thing for the h3 element. But instead of calling this nonexistent HTML method, we're going to say innerHTML = the title on our object. And so, next, we want to iterate over our items, which we are already doing, but we want to create an li element. Now, here's where things become less than desirable, because there's no great way to take a string of HTML and say, hey, give me HTML from the string. I mean, yes, we can do it. We can use DOM parser. We can also create an element, set the inner HTML, and then get that HTML, but, those aren't really good solutions. I would like something native so that we can say give me HTML from the string, get it back. But, until that day, we're just going to have to do things. I'm not gonna say the hard way, but the less than ideal way. So, we are going to create an element, that is an LI element, and we are going to set its inner HTML equal to the item, because our item's array is simply an array of strings. So, each item is going to be the string data itself, and then we want to append that LI element to the UL element. So, that's it. Let's go ahead and comment out this call to fade in. And whenever we go to the browser, we click on Load Content, but we don't see anything. Why is that? So, , we have , that's because the CSS, it is hidden. So, yeah, never mind that little faux pas, everything's there. So let's go ahead and modify our CSS. Instead of setting the display property to none, we're going to use opacity. So, opacity, in this case, is going to default to 0. And then let's add a class called fade-in. And we will say opacity is going to be 1, and we will set a transition for opacity. And as far as the time, let's do 500 milliseconds. So, inside of our script, we are going to add that class to the UL element. We're going to do so with the class list property. Going to call the add method, and that is called fade in. So, whenever we go back to the browser, let's close that, we should see that fade in. It doesn't. So, let's inspect once again. Well, at least items are being added. Let's look at the CSS. And the opacity of one is being overridden. So, let's just take the easy way, and let's say, important. So now we'll go back, refresh, and that fades in. So we have, essentially, replicated that jQuery code using standards compliant code. And it is a little bit extra to type, but in the grand scheme of things, it really wasn't. Now, just for kicks, let's do this, let's add another class. We're going to say color-red where we are going to set the color to red, naturally, and let's select all of those LI elements and add that class to them. Now, of course, the best thing to do would be inside of this for each loop, but I don't want to do that because I want to illustrate this. So, we are going to select container ul li. We're going to call the add class method color-red, and if we look at this in the browser, we are going to see those items are now red. So, now let's change this to standards code. So, instead of calling the jQuery function, we're going to use queries selector all. We're going to use that same selector. And instead, we're going to have to iterate over the result sets from calling queries selector all. So we're going to use for each, our callback will have elements, and then index. And then inside of this callback, we will say element class list add, and then color red. So, we will get the same results with just a little bit of extra code. Now, this is one of the things that I've never truly liked about jQuery is that a lot of the methods are iterative, it takes whatever elements you have selected with the jQuery function, or with the find method. And it iterates over all of those elements. Now, I understand the reasoning behind that. But people didn't fully understand what was going on behind the scenes. So, people were actually iterating multiple times over the same elements. When really, they didn't need to, so, here, having an explicit for each is nice, because we know that we are iterating here. And there's no extra iteration, there's no chance of iterating over the same elements, unless if we perform the query selector all again. So, as far as clarity is concerned, I much prefer this, even though it does require extra code. So, with Vanilla JavaScript, you can do anything that you could with jQuery. Now, it might require a little bit of extra code, but the trade off is faster execution, as well as no dependencies, and that's a fair trade in my book.