Chapter 2. Selectors and Methods: Grab and Go

image with no caption

jQuery helps you grab web page elements and do all kinds of things with them. In this chapter, we’ll dig into jQuery selectors and methods. With jQuery selectors, we can grab elements on our page, and with methods we can do stuff to those elements. Like a massive book of magic spells, the jQuery library lets us change tons of things on the fly. We can make images disappear and reappear out of thin air. We can select a certain piece of text and animate the change to its font size. So, on with the show—let’s grab some web page elements and go!

You receive an email from your friend, who is a professional portrait photographer. She wants to roll out a “Jump for Joy” promotion that allows users to win deals on a package of prints. She needs your help making the promotion work.

From: Emily

Subject: Jump for Joy Promotion!

Hey,

I saw your tweet that you’re doing more interactive web work these days, so I was hoping you could help me with making some interactive stuff for the “Jump for Joy” promotion on my website. I’d like to give my visitors a chance to receive a discount off their purchase before they check out, to encourage them to click around the site some more (and hopefully buy more as a result!).

The page should have four sections with one of four images per section. I need a message that says “Your Discount is” that displays a random discount amount (between 5 and 10 percent). When a user clicks on one of the sections, the message should appear below the image in that section. If a user clicks again, I’d like to get rid of the last message and display a new one.

I’ve attached a mockup of how I want it to look.

Think you can help??

--

Emily

image with no caption

Emily is a great photographer, but her request is kind of all over the place. Let’s take a closer look at that email and figure out what she is really asking for. Before you can even start writing any jQuery, you want to be super clear on what the project (or user) requirements are.

image with no caption

Whoa! Hold your horses there, hoss!

Working out project requirements first is a good habit to get into for every jQuery project you’ll work on. But before we jump right into writing jQuery code, we need to do a little work setting up the structure and styles first. We did a bit of this in Chapter 1, and now we’ve got even more to set up before we get any jQuery goodness going.

Dig in with divs

We need four clickable areas on the page, so let’s make those first. The most useful and flexible HTML element for our purposes is the <div> tag. The <div> tag serves very well in the structure role, since it’s a block-level element. We can also easily style div elements to act exactly as we want them to.

As we’ve seen, making an element clickable with jQuery is easy.

Clicking on a page element causes an event to trigger on the page, and can also run functions. We’ll get more in depth into events and functions later on, but for now, let’s just review how the click event works on a paragraph (or <div>) tag.

image with no caption
image with no caption
image with no caption

Using the code you put together in the magnets solution on the previous page, update your HTML file to include this script. Don’t forget to put it inside a <script> tag!

Do this!

image with no caption

The issue is that we haven’t been specific enough in our selection. So how can we get at the four sub-divs and leave out the larger container div? Remember from Chapter 1 that jQuery selectors use CSS classes and IDs. We can get even more specific about which elements we want jQuery to grab by adding classes and IDs to those elements.

image with no caption

In CSS, classes are used to group elements together and give them common style attributes. You can have one or more elements on the page that have the same class. For jQuery, we can use the same class selector, and affect the same group of elements with jQuery methods. Both CSS and jQuery use the “.” to signify a class, which makes it super easy to start classing up your code.

image with no caption
image with no caption

An ID selector is used to identify a single, unique element on a page. In jQuery, as in CSS, the # symbol is used to identify an ID selector. IDs are great when you want to get specific with an element, or when there is only going to be one of that kind of element on the page, like a page header or footer.

image with no caption

Classes and IDs are common ground for the three layers of a web page that we looked at in Chapter 1: structure, style, and script. Selectors are where those layers get wired together so they can all work in concert. HTML provides the building blocks (i.e., elements and their attributes), or structure of the web page. CSS provides the style, or the presentation and position of those elements. JavaScript and jQuery provide the script that controls the behavior or function of those elements.

Imagine that we have a class called slideshow for an image we want to run the slideUp method on:

image with no caption

Let’s have a look at our requirements to-do list to see where we are on building everything that Emily asked for:

The page should have four sections with one of four “jump for joy” images per section.

The sections should be clickable.

We need a message that says “Your Discount is” along with a random discount amount (between 5 and 10 percent).

When a user clicks on one of the sections, the message should appear below the image in that section.

If a user clicks again, get rid of the last message and make a new one.

image with no caption

Actually, not very hard.

There are several things involved in displaying a message to the user. Don’t forget, it could be a different message for each user who visits the site.

The next requirement on our list is to show some text that will stay the same as our script runs: “Your Discount is”. But beside that, we need to hold a number that will change or vary depending on the random amount. We need a way to carry that information throughout the script—our page needs a way to store that information. Storing information (or data) that varies is a perfect job for variables. When we want variables in jQuery, we use JavaScript variables.

image with no caption
image with no caption

Now, whenever we want to get the data we stored, we just ask for it by its variable name.

For many of our jQuery scripts, we’ll be storing different kinds of data: numbers, text, or true or false values. In many cases, especially when we need to display different messages to our visitors, we’ll be mixing HTML with these other kinds of data, which gives our web pages even more power. So, how do we go about combining our variables with other values? We use concatenation. Imagine you have a video game where you have a variable called pts that stores the highest score, and you need to display it to the winner:

image with no caption

Which give us:

image with no caption

Now that you’ve got a variable set up to store your concatenated discount message, you just need to update what’s in between your <script> tags, so let’s focus there.

Do this!

image with no caption

You’ve got your message ready to go, but how do you display it on the page below the image that’s been clicked? If you think of adding a new message as inserting it into the page, jQuery provides several ways to insert content into an existing element. We’ll cover some more useful ones in more depth in Chapter 4, but for now, let’s just look quickly at the append action.

image with no caption

The discount variable is generating a random number and appends the message to our page the way we expected, but it has an unexpected side effect: the discount shows up over and over again in every div.

That’s not what we wanted to happen. So what went wrong?

image with no caption

We need to append the discount variable only to the individual div that’s clicked. So, how do we select only the one that was clicked and append the discount variable to that one?

image with no caption

Throughout this chapter, we’ve been looking at jQuery selectors and how they return elements that jQuery methods use. And very often, we want to be really specific about which element we’re selecting. When it comes to specificity, the simplest selector to write is $ (this). (All you have to remember is the pronoun “this,” after all.) The $ (this) selector gives us an easy way to point to the current element.

image with no caption

It’s important to think about $ (this) as context-dependent. In other words, $ (this) means different things depending on where or when you use it. One of the best places to use it is within a function that runs when a jQuery method is called:

image with no caption

Let’s see if $ (this) can help us solve our problem. Update your code to use $ (this), as shown in bold below.

Do this!

image with no caption
image with no caption

Great question!

That leads us right to the last step on our to-do list:

The page should have four sections with one of four “jump for joy” images per section.

The sections should be clickable.

We need a message that says “Your Discount is” along with a random discount amount (between 5 and 10 percent).

When a user clicks on one of the sections, the message should appear below the image in that section.

If a user clicks again, get rid of the last message and make a new one.

So how do we get rid of the last message and make a new one? Use the remove method. The remove method allows us to take an element, or a group of elements, off of the page. Let’s have a look at a really simple page with a list and a button.

Descendant selectors are yet another selector we can use with jQuery, and they happen to fit our situation perfectly. With descendant selectors, we can specify relationships between elements. We can select children, parents, or siblings.

image with no caption
image with no caption

Yes, the order in which you add or remove your elements is important.

You can’t remove an element before you add it, and there’s no point removing an element just after you add it, right?

Congratulations! You nailed the requirements and made the campaign work.

The page should have four sections with one of four “jump for joy” images per section.

The sections should be clickable.

We need a message that says “Your Discount is” along with a random discount amount (between 5 and 10 percent).

When a user clicks on one of the sections, the message should appear below the image in that section.

If a user clicks again, get rid of the last message and make a new one.

From: Emily

Subject: Re: Jump for Joy Promotion!

Thank you so much for doing this for me. My site is so much better.

I hope people enjoy my photos as much as I enjoy my new page!

--

Emily

> PS. I’ve attached a self-portrait of me with my photo gear when I saw the new web page... No prizes for guessing what I’m doing!

image with no caption

You’ve got Chapter 2 under your belt and now you’ve added the basics of jQuery selectors and jQuery methods to your toolbox.