Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
jQuery HOTSHOT
jQuery HOTSHOT

jQuery HOTSHOT: Ten practical projects that exercise your skill, build your confidence, and help you master jQuery

eBook
$25.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

jQuery HOTSHOT

Chapter 2. A Fixed Position Sidebar with Animated Scrolling

The position:fixed CSS style adds an interesting effect that allows a targeted element to retain its position on the screen even when the page it is on is scrolled. However, its effectiveness is limited by the fact that no matter how deep the element is nested within other elements, it is always fixed relative to the document as a whole.

Mission Briefing


In this project we'll create a sidebar that emulates the position:fixed CSS style but doesn't suffer from the same limitations as a pure CSS solution. We can also add an attractive animation to the page so that when navigation items in the sidebar are clicked, different parts of the page are scrolled into view.

The following is a screenshot that shows the final result of this project:

Why Is It Awesome?

Being able to fix an element in place on the page is an incredibly popular UI design pattern used by many large and popular websites.

Keeping the visitor's main tools or calls-to-action within reach at all times improves the user experience of the site and can help keep your visitors happy. Making things convenient is important, so if a visitor has to scroll down a long page, then scroll all the way up just to click something, they will soon lose interest in the page.

This same principle is also an emerging trend on mobile devices. Actual position:fixed styling has pretty poor...

Building a suitable demo page


In this task we'll prepare the demo page and the other files we'll need ready for the script.

To make the benefits of this technique obvious, we'll need to use a number of extra elements that strictly speaking aren't part of the required elements for the sidebar that we'll be fixing in place.

The sidebar that we'll use as the focus of this example will need to sit within the structure of a complete page, and to see the fixed position effect, the page will also need to be quite long.

We'll be using a range of HTML5 elements when building our demo page and you should be aware that these are not supported in older versions of some browsers. If you find that you do need to support legacy browsers, you'll need to use the html5shiv script available at Google Code (http://code.google.com/p/html5shiv/).

Prepare for Lift Off

We should first save a new copy of the template file to the root folder of our project and call the new file fixed-sidebar.html. We can also create a...

Storing the initial position of the fixed element


Before we can fix the element in place, we'll need to know where that place is. In this task we'll obtain the current starting position of the <aside> element that we're going to be fixing in place.

Engage Thrusters

In fixed-sidebar.js we should start with the following code:

$(function() {
  
});

We can cache a couple of jQuery-selected elements at the top of our function, and to store the initial position of the fixed element, we can then add the following code within the function we just added:

var win = $(window),
    page = $("html,body"),
    wrapper = page.find("div.wrapper"),
    article = page.find("article"),
    fixedEl = page.find("aside"),
    sections = page.find("section"),
    initialPos = fixedEl.offset(),
    width = fixedEl.width(),
    percentWidth = 100 * width / wrapper.width();

Objective Complete - Mini Debriefing

We've used the same outer wrapper for our code that we used in the first project. As I mentioned then, it...

Detecting when the page has scrolled


Our next task is to detect when the page has been scrolled and fix the element in place when that occurs. Detecting the scroll event is made easy for us by jQuery, as is setting the position to fixed, because there are simple jQuery methods we can call to do these exact things.

Engage Thrusters

Add the following code to the script file directly after the variables we initialized in the last task:

win.one("scroll", function () { 
    fixedEl.css({
        width: width,
        position: "fixed",
        top: Math.round(initialPos.top),
        left: Math.round(initialPos.left)
    });
});

Objective Complete - Mini Debriefing

We can use jQuery's one() method to attach an event handler to the window object that we stored in a variable. The one() method will automatically unbind the event handler as soon as the event is detected for the first time, which is useful because we only need to set the element to position:fixed once. In this example we are looking for...

Handling browser window resizes


At the moment, our <aside> element will be fixed in place as soon as the page scrolls, which suits our needs while the browser remains the same size.

However, if the window is resized for some reason, the <aside> element will fall out of its fixed position and could be lost outside of the boundaries of the viewport. In this task, we'll fix that by adding an event handler that listens for the window's resize event.

Engage Thrusters

To maintain the fixed element's correct location relative to the rest of the page, we should add the following code directly after the one() method that we added in the last task:

win.on("resize", function () {
    if (fixedEl.css("position") === "fixed") {
        var wrapperPos = wrapper.offset().left,
            wrapperWidth = wrapper.width(),
            fixedWidth = (wrapperWidth / 100) * percentWidth;

        fixedEl.css({
            width: fixedWidth,
            left: wrapperPos + wrapperWidth - fixedWidth,
  ...

Automating scrolling


At this point, we should be able to click on any of the links in the navigation menu we added to the fixed element, and the page will jump to bring the corresponding section into view. The fixed element will still be fixed into place.

The jump to the section is quite jarring however, so in this task we'll scroll each section into place manually so that the jump to each section is not so sudden. We can also animate the scroll for maximum aesthetic effect.

Engage Thrusters

For this task we should add another event handler, this time for click events on the links in the navigation list, and then animate the page scroll to bring the selected <section> into view.

First, we can add a general function for scrolling the page which accepts some arguments and then performs the scroll animation using those arguments. We should define the function using the following code directly after the one() method that we added in the last task:

function scrollPage(href, scrollAmount, updateHash...

Restoring the browser's back button


At this point, we can click any of the links in the <aside> element and the page will be smoothly scrolled to the desired location on the page. The address bar of the browser will also be updated.

However, if the user tries to go back to a previous <section> using the back button of his/her browser, nothing will happen. In this task we'll fix that so that the back button works as expected, and can even use smooth scrolling when the back button is used to go back to the previous <section>.

Engage Thrusters

We can enable the back button very easily by adding another event handler directly after the one for click events that we just added:

win.on("hashchange", function () {

    var href = document.location.hash,
        target = parseInt(href.split("#part")[1]),
        targetOffset = (!href) ? 0 : sections.eq(target - 1).offset().top;

    scrollPage(href, targetOffset, false);
});

Objective Complete - Mini Debriefing

We use jQuery's on() method...

Handling the hash fragment on page load


At the moment the functionality of the browser's back button has been restored, and the visitor can see the bookmarkable URL in the address bar.

If the page is requested with a hash fragment in it, the page will automatically jump to the specified <section> when the page loads. In this part we'll add some code that checks the hash property of the document.location object and if a hash is detected, it will scroll to the corresponding part of the page smoothly.

Engage Thrusters

To enable this, we should add the following code directly after where we define our starting variables near the top of the script file, and directly before where we listen for the scroll event:

if (document.location.hash) {

    var href = document.location.hash,
        target = parseInt(href.split("#part")[1]),
        targetOffset = sections.eq(target - 1).offset().top;

    page.scrollTop(0);
    document.location.hash = "";
    scrollPage(href, targetOffset, true);

}

Objective...

Mission Accomplished


In this project we looked at a very simple way of mimicking CSS's position:fixed styling to fix an important element into place. The technique to only apply the fixed positioning when the page starts to scroll is simple but effective, and is an excellent way to circumvent the shortcomings of actual position:fixed when working with complex or liquid layouts.

We saw how to handle window resizes and added a smooth scrolling facility that scrolled the page between different named sections of the page.

We also looked at how we can read and write to the document.location.hash property of the window object, and how to manually scroll to the requested section when the page is loaded. We also fixed the browser's back button to work with our smooth-scrolling animations.

You Ready To Go Gung HO? A Hotshot Challenge


Very often, with the kind of in-page navigation we've used in this project, it is useful to show an on-state on the navigation links when a section is scrolled to, either manually, or by clicking on one of the links. Have a go at adding this simple but effective addition to the code that we've looked at over the course of this project.

Left arrow icon Right arrow icon

Key benefits

  • See how many of jQuery's methods and properties are used in real situations. Covers jQuery 1.9.
  • Learn to build jQuery from source files, write jQuery plugins, and use jQuery UI and jQuery Mobile.
  • Familiarise yourself with the latest related technologies like HTML5, CSS3, and frameworks like Knockout.js.
  •  

Description

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.

Who is this book for?

This book is aimed primarily at front-end developers, preferably already with a little jQuery experience, or those people that simply want to build on their existing skills with jQuery.

What you will learn

  • Learn how to use the latest version of jQuery (1.9) in real-world situations
  • Create a jQuery plugin structured for organisation and maintainability
  • Construct a custom version of jQuery using Node.js and Grunt.js, and learn how to run unit tests using qUnit
  • Build on top of online services like Google Maps to create interactive interfaces
  • Use templating frameworks to easily and efficiently create repetitive areas of the page populated with data
  • Get started with the related jQuery-powered frameworks jQuery UI and jQuery Mobile
  • Produce interactive interfaces that respond to user interactions using the Model-View-View Model framework Knockout.js
  • Use the latest web standards like HTML5 and CSS3 to create attractive and semantic web pages
  •  

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 26, 2013
Length: 296 pages
Edition : 1st
Language : English
ISBN-13 : 9781849519106
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Mar 26, 2013
Length: 296 pages
Edition : 1st
Language : English
ISBN-13 : 9781849519106
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 92.98
Learning jQuery - Fourth Edition
$43.99
jQuery HOTSHOT
$48.99
Total $ 92.98 Stars icon

Table of Contents

10 Chapters
Sliding Puzzle Chevron down icon Chevron up icon
A Fixed Position Sidebar with Animated Scrolling Chevron down icon Chevron up icon
An Interactive Google Map Chevron down icon Chevron up icon
A jQuery Mobile Single-page App Chevron down icon Chevron up icon
jQuery File Uploader Chevron down icon Chevron up icon
Extending Chrome with jQuery Chevron down icon Chevron up icon
Build Your Own jQuery Chevron down icon Chevron up icon
Infinite Scrolling with jQuery Chevron down icon Chevron up icon
A jQuery Heat Map Chevron down icon Chevron up icon
A Sortable, Paged Table with Knockout.js Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(10 Ratings)
5 star 80%
4 star 20%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Robert A. Balfe May 31, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Did you ever go to a web site and think, wow, how did they do that? Or, wouldn't that be cool to write? I know I do.Well, this book is filled with 10 small projects you can use in real life. So unlike an API book where it focuses on the small granular API calls this book focuses on completed solutions.It starts off in the preface with a high level summary of what jQuery is and the basic concepts of the API so you really don't even have to know jQuery to read this book. You do however need to know HTML and JavaScript basics but I will add, all of the source code is available and the massive 296 page book does a great job going step by step. The beauty of the book is it covers a lot of areas for where jQuery can be used - from developing games to building your own jQuery. Many of the techniques used in the book are very creative and well thought through. Each project has plenty of screen shots and narrative to help you digest the content. Did I mention all of the source code is downloadable? Yep, so you can casually read the book and then go back and play with the finished source code if you wanted.From beginner to advanced this book is a valuable resource to see how different things can be done with jQuery. It mixes some really good JavaScript API's along with jQuery API's to create real life projects.
Amazon Verified review Amazon
Danny Jul 09, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Where most books cover minutia of Jquery or Javascript. This book gets you coding in a hurry. A very pleasant experience. As a web developer, the chance of coming across a book that gives you step by step instructions on what could be real projects and not boring theory is a rare treat. I would highly recommend this book for anyone with at least a basic understanding of JavaScript. Some of the JavaScript concepts you will need to understand to get the most out of this book are callbacks,events,functions,arrays and object literals. Dan Wellman provides great little insight to every code example and really breaks it down into everyday language everyone can understand. He also provides you with bits of Classified Intel on how JavaScript works in the sections called "Classified Intel". A must have for anyone wanting to get past the dry theory based books and build some functional projects.
Amazon Verified review Amazon
Mikhail Svirkin Nov 04, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Clear and practical book
Amazon Verified review Amazon
James Gonzales May 20, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you're new to jQuery, read this book to see good working projects that explain why these techniques are used. If you're experienced, you'll like the more comprehensive projects and the challenges on how to extend them even more.You will use HTML5 and some of the newer APIs in these projects. They range from interactive Google maps, jQuery UI, SPAs (single page applications), jQuery Mobile and more! One of the best parts is the debriefing where the design is described in each project. If you come across a new topic or subject, there are always handy hyperlinks that lead you to more detailed information. I liked this book and learned a lot from it.
Amazon Verified review Amazon
DB May 26, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
So you've built a few web sites that use some of jQuery's most common methods. Perhaps you've used jQuery for a few simple DOM manipulations, form validations, smooth animations, or tacked on some plugins and feel like you've seen what jQuery can do. If this sounds like you, this book will quickly dispel your notion of jQuery as simple, convenience javascript library, but a powerful tool that can be used in a vast and surprising array of scenarios. This book is not for jQuery beginners or for those who are only interested in creating simple informational web sites. A look at the table of contents alone will quickly expand the boundaries of what you thought was possible. Yes, jQuery is used in every project and that is why it's name is on the cover, but you'll see it used in conjunction with many other libraries and APIs. And as you dive in to the chapters, you'll start to uncover some best practices and important intricacies with not just jQuery but with native Javascript programming as well (i.e. performance tweaking, variable hoisting, function expressions, namespacing, etc).Simply put, this book is for the passionate and curious developers that are looking to expand their knowledge of where and how jQuery can fit in the broad range of web development.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.