Lesson 51 JQuery

We left our calculator with a problem. It writes each number over the one before. We want to write them in a line like 2 + 1.

To do that I use something called jquery. It’s a javacript library, a shortcut that enables you to use new commands

For one, instead of document.getElementById(“screen”), we can use $(“#screen”). It’s a shortcut selector. We can use $(‘.number’) if you want to select the elements with the class of number.

If you are going to use something like that over and over, like we do with screen, you can declare a variable $screen as $(“#screen”). That makes it even shorter.

We can also use jquery’s library of commands. Instead of innerHTML, you can append, add on the next number. It looks like this.

$screen.append(1);

$screen.append(“+”);

That’s much shorter than what we originally used.

One last command for you try is empty. Instead of writing in a blank with “ ”, we can just empty what’s in a div.

$screen.empty();

Empty and append are functions so we write the parentheses () after the name of it. Sometimes we want to put something in that that we want to use, sometimes, there’s nothing to put there, but we still need to have them. All functions are “called” with its name and the parentheses.

To use jquery, we list it with our other scripts. This can be in the head of your HTML document, but typically it can also be placed with your other scripts just before the close of your body. Below is one link you can use. Link it with src= in a script tag like you do your regular javascript files. You could also download the jquery library and link to it like your other files, such as ./resources/js/jquery.js

https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js

For this week’s lesson, link in jquery and replace all the get elements by ID with the jquery alternative. I would suggest for the ID screen, you create a variable for it.

lesson51 jquery intro

You can watch this lesson on YouTube.