Week 3
Last week, we learned about writing content to the website with document.write
. That was great but had one major caveat:
document.write
overwrites everything that was there before. If we had any stylesheets or HTML elements we wanted to preserve, there was no chance.
A more sensible approach to manipulating websites
What if we could change the website without deleting everything that's already there? The browser provides us with APIs (tools) to achieve just that.
The DOM
Before we get into specific tools, let us understand what happens behind the scenes when loading a website. Instead of initially reading all files to draw a website, the browser creates an internal data structure. That data structure is the basis for website rendering and any CSS and JavaScript that will run. The data structure is called "Document Object Model", or DOM.
Whenever we make changes to the website through code, we are working with the DOM. The browser notices the changes and will redraw the website accordingly. It may sound not very easy, but we will learn a convenient way of going about it.
Using JavaScript to manipulate the DOM
We can write plain JavaScript to manipulate the DOM. The browser provides us with tools to do that out of the box. These days, these tools (also called APIs, Application Programming Interface) are the same across all browsers.
A few years ago, however, things looked a bit different. Back then, browsers differed in how they implemented the DOM, what JavaScript functions they would provide out of the box and how they behaved. Writing JavaScript at the time required additional effort to navigate these waters, figuring out what APIs were safe to use and available across browsers. A few developers came up with libraries to allow for a smoother development experience to save time and effort.
One of these libraries, one of the oldest, is jQuery. jQuery came into existence around 2005-2006, when Internet Explorer was the most widely used browser. Internet Explorer, Chrome, and Firefox all differed in what APIs they offered. Chrome and Firefox followed the W3C specifications as closely as possible (W3C specifies how HTML, CSS, and JavaScript work), while Internet Explorer interpreted the rules a bit "more freely." Without going too much into the details, could you imagine how much effort it would take to keep track of all these (subtle) differences when writing JavaScript?
That's where jQuery offered a real advantage. Using jQuery, you could focus on your actual application code, and jQuery took care of navigating all these bugs and implementation differences.
Using libraries as a web developer
jQuery is a JavaScript library; code that's meant to be embedded in other applications. Besides jQuery, thousands of other libraries are available to use, solving a different problem. These libraries are written and maintained by other developers. It's common these days to depend on third-party libraries in software projects. Most of them are available on Platforms like GitHub. It wouldn't be feasible for us to "reinvent the wheel" every time we start a new project. For instance, could you imagine writing the same code repeatedly when starting a new project, just to ensure your code behaves the same in all browsers? It would cost so much time and effort. That's why we're leveraging libraries to get a head start. These days, it's normal that these libraries are offered free of charge under an Open Source license. These licenses allow us to take and use the code in our own projects. We save time twice: We write less code, and also if there's a bug in the library, as in something not working unexpectedly, the chances are high somebody else faced that problem before us and fixed it already.
Including other libraries
So, how do we include a library like jQuery? The mechanism is similar to how we include our own code in a website. Consider this example:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="/script.js"></script>
Notice how we're loading jQuery from a different server. Also, the order of the script tags matters because we want jQuery to load before our own code. Otherwise, our code would try to require jQuery functions and fail.
Project Preparation
Create a new Project on Glitch.com and:
- Delete everything in
script.js
- Delete everything in
styles.css
- Replace the contents of
index.html
with:
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Introduction</title>
<link rel="stylesheet" href="/style.css" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="/script.js">
</script>
</head>
<body>
</body>
</html>
jQuery Intro
Open script.js
and delete all code. Then, let's start by writing our first few lines of jQuery Code:
$(document).ready(function() {
console.log("Hi There");
});
You notice the $
at the beginning of line 1. The Dollar sign is the jQuery function. It comes with this unique name for two reasons:
- It's quick to type
- It's unlikely you'll have another function in your source code with that same name. If two functions had the same name, you wouldn't be able to invoke jQuery.
What the above code is doing:
Once the browser finished loading and rendering HTML, it executes the code we provided as an argument to the .ready
function. In this case, we're printing "Hi There" on the Developer Console.
The $
function accepts an argument ($(/* This is where the argument goes*/)
). It's usually text, but in this case, it's another variable (document
). Whatever we provide as arguments, it'll be the target we're operating on (Here: $(document)
). document
is provided by the browser and offers several tools to interact with the loaded website.
Task for tonight
All our code will live inside the function
we passed to $(document).ready
. It works like an extension point where we can provide our own code that only should run when the website finished loading (similar to window.onload
).
We usually want to wait that long because our code will depend on other HTML elements to be there.
Last time, we used document.write
to print text on the website. Now, we want to use jQuery to write something on the website without erasing everything else:
$(document).ready(function() {
$('body').append('<h1>Hi There</h1>');
});
jQuery offers an .append
function to add HTML elements to a specific element or container. In this case, we choose <body>
, but we're free to use any other tag as well!
To ensure that we're not overwriting anything, let's try this. Open styles.css
and delete everything that's in there. Then, add the following CSS:
body {
font-family: Arial;
}
h1 {
font-family: Helvetica;
}
Open the website preview to view the rendered site. How does it look? Everything is still there, and we can rely on styles from our stylesheet!
Explanation:
For the <body>
, we're configuring a different font family, Arial
. For first-level headlines (h1
), we're choosing Helvetica
instead.
Let's generate the rest of our shopping list:
$(document).ready(function() {
$('body').append('<h1>Hi There</h1>');
$('body').append('ul');
$('ul').append('<li>Milk</li>');
$('ul').append('<li>Bread</li>');
$('ul').append('<li>Spread</li>');
});
What's interesting here is how we can use jQuery to add content to the <body>
and an <ul>
as well!
Reacting on user input
What if we're all done shopping, and we want to clear the list?
Let's add a button that hides every item on the list once clicked.
$(document).ready(function() {
$('body').append('<h1>Hi There</h1>');
$('body').append('<button>Clear the list</button>'); //add this line
$('body').append('ul');
$('ul').append('<li>Milk</li>');
$('ul').append('<li>Bread</li>');
$('ul').append('<li>Spread</li>');
});
For now, if you're trying to click the button, nothing happens. That's because we haven't provided the browser any code it should execute once the user clicks on the button!
Let's do that. Below the append
function calls, add the following code:
//...
$('ul').append('<li>Milk</li>');
$('ul').append('<li>Bread</li>');
$('ul').append('<li>Spread</li>');
//add these lines
$('button').click(function() {
alert("Button got clicked!");
});
});
The lines we just added are called Event Handler. It's a piece of code that only gets executed when a specific event happens; in our case, clicking on the button.
For now, we want to ensure that the click handler works. Therefore we'll have it fire up an alert window once clicked.
Go to your preview window and click the button. We'll get an alert that looks like this:
Now that we confirmed it works let's add the actual functionality.
$('<button>').click(function() {
$('ul').hide(); //change this line
});
Now, let's see what happens when you click the button! All list items are gone! How cool is that?