Book Image

jQuery HOTSHOT

By : Dan Wellman
Book Image

jQuery HOTSHOT

By: Dan Wellman

Overview of this book

jQuery is used by millions of people to write JavaScript more easily and more quickly. It has become the standard tool for web developers and designers to add dynamic, interactive elements to their sites, smoothing out browser inconsistencies and reducing costly development time.jQuery Hotshot walks you step by step through 10 projects designed to familiarise you with the jQuery library and related technologies. Each project focuses on a particular subject or section of the API, but also looks at something related, like jQuery's official templates, or an HTML5 feature like localStorage. Build your knowledge of jQuery and related technologies.Learn a large swathe of the API, up to and including jQuery 1.9, by completing the ten individual projects covered in the book. Some of the projects that we'll work through over the course of this book include a drag-and-drop puzzle game, a browser extension, a multi-file drag-and-drop uploader, an infinite scroller, a sortable table, and a heat map. Learn which jQuery methods and techniques to use in which situations with jQuery Hotshots.
Table of Contents (18 chapters)
jQuery HOTSHOT
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Starting and stopping the timer


At this point, our game is fully functional and the puzzle can be unscrambled; however to make it more fun we should introduce an element of competitiveness by incorporating a timer.

Prepare for Lift Off

In this task we'll need to complete the following steps:

  • Check the timer isn't already running when the Start button is clicked

  • Start the timer from 0

  • Increment the timer every second

  • Update the display on the page so that the player can see how long the current game has taken so far

Engage Thrusters

To check whether the timer is already running when the Start button is clicked we should add the following code directly after where we appended the shuffled pieces to the page, and directly before the call to draggable():

pieces.appendTo(imgContainer).draggable("destroy");

if (timer) {
    clearInterval(timer);
    timerDisplay.text("00:00:00");
}

timer = setInterval(updateTime, 1000);
currentTime.seconds = 0;
currentTime.minutes = 0;
currentTime.hours = 0;

pieces.draggable({

Next we can add the function that increments the timer and updates the display. This code should come directly after where we update currentTime.hours in the previous code:

function updateTime() {
  
    if (currentTime.hours === 23 && currentTime.minutes === 59 &&
currentTime.seconds === 59) {
        clearInterval(timer);          
    } else if (currentTime.minutes === 59 && currentTime.seconds === 59) {

        currentTime.hours++;
        currentTime.minutes = 0;
        currentTime.seconds = 0;
    } else if (currentTime.seconds === 59) {
        currentTime.minutes++;
        currentTime.seconds = 0;
    } else {
        currentTime.seconds++;
    }

    newHours = (currentTime.hours <= 9) ? "0" + currentTime.hours :

    currentTime.hours;
    newMins = (currentTime.minutes <= 9) ? "0" + currentTime.minutes :

    currentTime.minutes;
    newSecs = (currentTime.seconds <= 9) ? "0" + currentTime.seconds : 

    currentTime.seconds;

    timerDisplay.text([
        newHours, ":", newMins, ":", newSecs
    ].join(""));


}

Objective Complete - Mini Debriefing

The first thing we have to do in this task is check whether a timer is already running. The timer will be stored in one of our "global" variables so we can check it easily. We use an if statement to check whether timer contains a truthy value (see the previous information on JavaScript's truthy and falsey values).

If it does, we know the timer is already running, so we cancel the timer using JavaScript's clearInterval() function, passing in our timer variable as the timer to clear. We can also reset the timer display if the timer is already running. We selected the timer display element from the page and cached it when we initially declared our variables at the start of this project.

Next we start the timer using JavaScript's setInterval() method and assign it to our timer variable. When the timer begins this variable will contain the ID of the timer, not the value of the timer, which is how clearInterval() knows which timer to clear.

The setInterval() function accepts a function to execute after the specified interval as the first argument, and the interval as the second argument. We specify 1000 milliseconds as the interval, which is equal to 1 second, so the function passed as the first argument will be called every second until the timer is cleared.

Once the timer has started we can also reset the values stored in the object we'll use to keep track of the timer – the currentTime object. We set the seconds, minutes, and hours properties of this object to 0. We need an object to keep track of the time because the timer variable itself just contains the ID of the timer.

Next we added the updateTime() function that will be called by our interval every second. All we do in this function is update the relevant properties of the currentTime object, and update the display. We use an if conditional to check which parts of the timer to update.

We first check that the timer has not reached 24 hours. I would hope that no one would actually spend that long playing the game, but if the browser is left open for some reason for this length of time, we don't want the time display to say, for example, 24 hours and 1 minute, because at that point, we really should update the display to say 1 day, 0 hours, and 1 minute. But we aren't bothering with days so instead we just stop the timer.

If the timer has not reached this length of time we then check whether the current minutes equal 59 and the current seconds equal 59. If they do we need to increment currentTime.hours by 1 and reset the currentTime.minutes and currentTime.seconds properties back to 0.

If this check fails we then check whether the seconds equal 59. If they do, we increment the currentTime.minutes property and then reset currentTime.seconds back to 0. If this second test also fails we know that all we have to do is increment currentTime.seconds.

Next we need to check whether we need to pad any of the time components with a leading 0. We could use another if else conditional for this, but the JavaScript ternary construct is neater and more compact so we use this instead.

First we test whether currentTime.hours is equal to or less than 9 and if so we add 0 to the start of the value. We do the same for currentTime.minutes and currentTime.seconds.

Finally, we build the string which we will use to update the timer display. Instead of using boring and slow string concatenation, we again use an awesome array comprising the various parts of the display and then join the array.

The resulting string is set as the value of the <span> element contained in the timerDisplay variable and the element on the page is updated using jQuery's text() method.

At this point we can now click on the button to shuffle the puzzle pieces, and watch as the timer starts to increment.