Chapter 7. Custom Functions for Custom Effects: What Have You Done for Me Lately?

image with no caption

When you combine jQuery’s custom effects with JavaScript functions you can make your code—and your web app—more efficient, more effective, and more powerful. In this chapter, you’ll dig deeper into improving your jQuery effects by handling browser events, working with timed functions, and improving the organization and reusability of your custom JavaScript functions.

A storm is brewing

The Monster Mashup web app you built in Chapter 5 was a big hit with kids and their parents. But it sounds like there might be a bug that’s making the lightning go haywire. DoodleStuff’s quality assurance manager contacts you with some issues and a feature request for making Monster Mashup better.

image with no caption
image with no caption

Brain Power

Try reproducing the issue. Then think about what’s going wrong with the lightning functions. Why do they all crash together when someone switches from one tab to another?

We’ve created a monster...function

The lightning function we created in Chapter 5 has turned out to be a bit of a monster. It runs and runs, even if the user navigates away from the page. When the user returns to the tab, the timer has to catch up, and it tries to redraw the lightning on screen in rapid succession. It seems that the timer doesn’t work the way we wanted it to, so what happened?

image with no caption

In Chapter 5, we needed a way to call the method again and again, with a timeout in between those calls. In solving that problem, we unknowingly created a new problem: the function continues to run when the window loses the visitor’s focus (i.e., when the visitor opens a new tab and moves away from the active window).

image with no caption

Watch it!

You have to be very careful with functions that call themselves.

Creating infinite loops can eat up CPU resources and crash the visitor’s browser.

Get control of timed effects with the window object

Fortunately, you have a way to get control of your lightning animation using JavaScript’s window object. The window object is created every time the visitor opens a new window in his browser, and it offers a lot of jQuery and JavaScript power. In the world of JavaScript, the window object is the global object. In other words, window is the topmost object of the JavaScript world.

image with no caption

Let’s say you’ve opened three tabs in your browser. The browser creates one window object for each of those tabs. The window object is an object just like the ones you worked with in Chapter 6, so it has properties, event handlers, and methods. And they’re super handy—we can use the window object’s onblur and onfocus event handlers to find out what the visitor is doing at the browser level.

image with no caption

The window object also offers timer methods that you can leverage for running your custom timed functions. window has many more methods, but these are the ones we need to use to fix the lightning functions.

Watch it!

Don’t confuse the JavaScript window object’s onblur and onfocus event handlers with jQuery’s blur and focus methods.

The jQuery blur and focus methods are intended to be attached to HTML form fields and other elements but not the window object.

Brain Power

The window object’s onfocus and onblur event handlers can detect a change to the window’s focus, but what can you do in response to those events?

Respond to browser events with onblur and onfocus

So we know that with window.onfocus, you can tell when the window gains focus (i.e., a visitor activates the page or directs mouse or keyboard input to the window), and with window.onblur, you can tell when the active browser window loses focus. But what can you do in response to these events? You can assign a function reference to onfocus or onblur.

image with no caption

And here’s where the power of writing your own custom functions really starts to come into play. Now you’ve got a window object that gives you a ton of information about what your user is doing in the browser, and you can assign your own custom functions based on what that object tells you. So, really, you can do just about anything you want, as long as you can write your own custom function for it...

Timer methods tell your functions when to run

Both JavaScript and jQuery offer us timer methods that call functions to run based on time passing. JavaScript’s window object has four timer methods for timed control: setTimeout, clearTimeout, setInterval, and clearInterval. jQuery offers us the delay method. Let’s take a closer look at these methods and what they offer us.

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

Great question!

You can use the clearInterval method to stop the repeating schedule of function calls created by setInterval. To do so, you need to pass a variable to clearInterval as a parameter. Let’s take a closer look at how that works.

image with no caption

Write the stopLightning and goLightning functions

Now that you know more about timer methods, let’s review where we need them.

image with no caption

Do this!

You’ll be updating a bunch of code to fix and improve on what you built in Chapter 5, so let’s start with a blank script file. The code files you downloaded for this book contain a folder for Chapter 7. In the folder, you’ll find a begin folder structured like this:

image with no caption
image with no caption

Great idea. We have a bunch of click-related functions for that face that we could likely combine into one multipurpose function.

image with no caption

Feature request for Monster Mashup

Jill and the QA team are really happy with your fixes, and since they like your work, they want to pass along a feature request for Monster Mashup from the product team.

image with no caption
image with no caption

Let’s get (more) random

You’ve been building random functions throughout the book, so you’re likely a pro at that by now. In this case, you need to create a function that randomly animates the monster faces. Let’s divide and conquer the problem by breaking it down into smaller steps. Let’s start with figuring out the current position for each image strip.

image with no caption

From the current position, we need to figure out the target position, which is essentially a random position on the screen. It helps to think of this in two parts:

  1. Get a random number.

    image with no caption
  2. Move each face part to a random position based on that random number.

    image with no caption
image with no caption

It’s not as hard as you think.

In fact, just turn the page to find out how.

You already know the current position...

Fortunately, you don’t have to come up with all new variables or functions here. The index value of the clix array provides the current position because it tells us how many times the user has clicked on each monster face part. So all you need is one line of code:

image with no caption

...and the getRandom function too

We built a function for getting random numbers in Chapter 2, Chapter 3, and Chapter 6. We can reuse that function here with minimal tweaks.

image with no caption
  1. Set your variable and pass it to the function:

    image with no caption
  2. Here’s the core operation of the function:

    image with no caption
  3. And the result (or output) of the function:

    image with no caption

    Next up: the target_position (i.e., the random face part) we want to slide to.

image with no caption

You’re right.

Those custom functions had unintended effects, but they likely did exactly what we wrote in the code. Let’s have a look at what we might not have thought about.

image with no caption
image with no caption

Brain Power

What do you need to do to keep the image strip from going off the grid, and instead landing on a random monster face part?

Move relative to the current position

To keep the image strip from going off the grid—but still falling correctly on a random monster face part—you need to move it relative to the current position, which means including the current position and some conditional logic. Let’s break it down.

image with no caption

Then the user clicks on the Randomize button, which comes up with a random number between 0 and 9. Let’s look at two different scenarios that could happen as a result.

Scenario 1: target > current

The getRandom function returns a value of 5. So the target_position variable gets set to 5, which means that it’s greater than the current_position variable. We need to write conditional logic to handle this situation.

image with no caption

Scenario 2: target < current

The getRandom function returns a value of 1. The target_position variable is 1, which means that it’s less than the current_position variable. Based on the conditional logic from Scenario 1, can you figure out what logic you need here?

image with no caption
image with no caption

Exactly.

Remember that reset button in the index.html file a few pages back? Now you just need to wire it up to a custom reset function.

Below, you’ll find all the code you’ve built in the last few pages. If you haven’t done so already, add the bolded code to your my_scripts.js file and get ready to test all the new functionality you’ve built.

Do this!

image with no caption

Monster Mashup v2 is a hit!

image with no caption

Your jQuery Toolbox

You’ve got Chapter 7 under your belt and now you’ve added the window object, timed functions, and custom functions to your toolbox.

window object

This is the topmost object in JavaScript.

It has properties, event handlers, and methods that help you detect and respond to browser events.

onFocus tells you when a browser window is active.

onBlur detects when a window loses focus.

Timed functions

Methods available for the window object.

setTimeout waits a set period of time before telling a function to run.

setInterval runs a function repeatedly, with a certain amount of time in between.

clearInterval wipes clean the schedule of repeated function calls.

Optimized custom functions

Writing your own custom functions allows you to really start making interactive web pages that people will want to use.

But you can also get carried away, and it’s important to look at how best to combine and optimize your functions so you’re writing less code that is easier to maintain and debug.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.176.80