Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

February 07 2014

11:00

Responsive Images: Still Waiting for a Standard? Try Rwd.Images.Js Instead!


  

Responsive Images is a topic far from resolved. Will it be the picture element as proposed by the W3C or will it be the srcset attribute as proposed by WHATWG in the end? No matter what time will bring, responsive images are a problem that needs to be solved today and not sometime in the future. No wonder that JavaScript is the remedy of choice. There are quite a few scripts targeting responsive imaging, quality varies though. A brand-new script by Matt Stow from Australia shows the potential to become the best available client-side interim solution…

January 30 2014

14:00

JavaScript Animation That Works (Part 2 of 4)

In the last post, we introduced the idea of spriting, an easy way to animate in JavaScript that works in all browsers. We also walked through how to set up the sprite as a background image for a div and then use a line of JavaScript to change the background position to make it appear as if the image has moved.

In this post, we will use this technique to animate both running and jumping motions. In order to create the animation, we will need to quickly change the background position at a regular interval. Take a look again at the sprite we are using.

javascript-spriting-j

Meet J, the mascot for my company, Joust Multimedia.

In our example, we have ten total images: one of J standing facing right, three of J running to the right and one of J jumping while facing right (with the same number of each frame facing left). Let’s start with making him run to the right. In order to make our image look like it is running, we will need to do two things: change the sprite to a different image and move the div towards the right.


Running to the Right Animation

We certainly won’t want to be stuck clicking different buttons to cycle through the sprites, so we will need to create some functions that do this automatically.

For our running function, we want to:

  1. Move the div towards the right slightly
  2. Move to the next frame of animation
  3. Pause for a fraction of a second (to preserve the “persistence of vision” illusion)
  4. Loop the function again

Fortunately, there is an easy way to loop with functions. A native command in JavaScript called setTimeout will allow us to create a timed delay, after which we will call the function again (from inside the function).

function run_right(){
  // Move slightly to the right ...
  // Change to the next frame of animation ...

  // this will call 'run_right' again after 200 milliseconds
  setTimeout(function(){run_right();}, 200); 
}

So now we have a function that will call itself again five times a second (which will be fast enough to create animation for our purposes). Remember here that browsers are not terribly accurate with their timers. You can specify timing to the millisecond, but that doesn’t mean your script will run at that timing exactly!

Our next problem to tackle is how is our function going to know which sprite to change to? In our example, we will need to cycle back and forth through our three images (to have four total frames of animation). To do this, we are going to pass our function a bit of information to tell it which slide to switch to. Once in the function, we will do a test that will check which slide we should be on, then switch the background position to the correct sprite. When we call the function again, we will pass the next slide as the argument.

function run_right(slide){
  // Move slightly to the right ...
  switch (slide){ // this switch statement checks for different possibilities for 'slide'
    case 1: // if 'slide' equals '1' ...
      document.getElementById('j').style.backgroundPosition = "-40px 0px";
      setTimeout(function(){run_right(2);}, 200);
      break;
    case 2: // if 'slide' equals '2' ...
      document.getElementById('j').style.backgroundPosition = "-80px 0px";
      setTimeout(function(){run_right(3);}, 200);
      break;
    case 3: // if 'slide' equals '3' ...
      document.getElementById('j').style.backgroundPosition = "-120px 0px";
      setTimeout(function(){run_right(4);}, 200);
      break;
    case 4: // if 'slide' equals '4' ...
      document.getElementById('j').style.backgroundPosition = "-80px 0px";
      setTimeout(function(){run_right(1);}, 200);
      break;
  }
}

And now when we call the function for the first time, we will need to make sure we pass the starting slide.

<input type="button" value="Run Right" onclick="run_right(1);" />

Similarly, to move our div to the right slightly, we can pass the initial left attribute of the div, then move the div slightly each time the function is called.

function run_right(slide, left){
  
  left = left + 15; // Increase his left attribute by 15px
  document.getElementById('j').style.left = left+"px";
  
  switch (slide){ // this switch statement checks for different possibilities for 'slide'
    case 1: // if 'slide' equals '1' ...
      document.getElementById('j').style.backgroundPosition = "-40px 0px";
      setTimeout(function(){run_right(2, left);}, 200);
      break;
    case 2: // if 'slide' equals '2' ...
      document.getElementById('j').style.backgroundPosition = "-80px 0px";
      setTimeout(function(){run_right(3, left);}, 200);
      break;
    case 3: // if 'slide' equals '3' ...
      document.getElementById('j').style.backgroundPosition = "-120px 0px";
      setTimeout(function(){run_right(4, left);}, 200);
      break;
    case 4: // if 'slide' equals '4' ...
      document.getElementById('j').style.backgroundPosition = "-80px 0px";
      setTimeout(function(){run_right(1, left);}, 200);
      break;
  }
}

And when we initially call the function, we need to make sure we pass the current left position of our div.

<input type="button" value="Run Right" onclick="run_right(1, document.getElementById('j').offsetLeft);" />

Stopping the Animation

So, now we have a function that, when called, will animate J to run to the right. Unfortunately, we have no way to stop it. First of all, we will need to make the function stop calling itself if J runs to the edge of our stage. To do that, every time the function runs, we will check an if statement to see if J has room to keep running. If so, we will run the function like normal. If not, we will stop calling the function and return him to the standing sprite.

function run_right(slide, left){
  // If we can add 15 pixels to the left and have J's right edge not be at the stage's right edge ...
  if ((left + 15) < (document.getElementById('stage').offsetWidth - document.getElementById('j').offsetWidth)){
    // We have room! Continue like normal here
  } else { // if we are on the right edge, we need to stop calling the function and return to standing
    document.getElementById('j').style.backgroundPosition = "0px 0px";
  }
}

Finally, we will want to have a way to stop the function, when needed. We can set the setTimeout() command to a variable, then stop it with the clearTimeout() command. In order to do this, we will need to declare that variable outside of the function, so that we will be able to refer to it later. For now, we will declare it as a global variable. This is terrible coding practice, but we will correct this in the next post. This is what our function looks like.

var timer;

function run_right(slide, left){
  if ((left + 15) < (document.getElementById('stage').offsetWidth - document.getElementById('j').offsetWidth)){
    left = left + 15; // Increase his left attribute by 15px
    document.getElementById('j').style.left = left+"px";
  
    switch (slide){ // this switch statement checks for different possibilities for 'slide'
      case 1: // if 'slide' equals '1' ...
        document.getElementById('j').style.backgroundPosition = "-40px 0px";
        setTimeout(function(){run_right(2, left);}, 200);
        break;
      case 2: // if 'slide' equals '2' ...
        document.getElementById('j').style.backgroundPosition = "-80px 0px";
        setTimeout(function(){run_right(3, left);}, 200);
        break;
      case 3: // if 'slide' equals '3' ...
        document.getElementById('j').style.backgroundPosition = "-120px 0px";
        setTimeout(function(){run_right(4, left);}, 200);
        break;
      case 4: // if 'slide' equals '4' ...
        document.getElementById('j').style.backgroundPosition = "-80px 0px";
        setTimeout(function(){run_right(1, left);}, 200);
        break;
    }
  } else {
    document.getElementById('j').style.backgroundPosition = "0px 0px";
  }
}

And we can create another function to stop the running timer and return the sprite to the standing image.

function stop_running(){
  document.getElementById('j').style.backgroundPosition = "0px 0px";
  clearTimeout(timer);
}

Running to the Left Animation

Now by borrowing the code from our run_right function, we can create another function to make a run_left function, with just a few modifications.

function run_left(stage, left){
  if ((left - 15) > 0){
    left = left - 15;
    document.getElementById('j').style.left = left+"px";
    switch (stage){
      case 1:
        document.getElementById('j').style.backgroundPosition = "-40px -50px";
        timer = setTimeout(function(){run_left(2, left);}, 200);
        break;
      case 2:
        document.getElementById('j').style.backgroundPosition = "-80px -50px";
        timer = setTimeout(function(){run_left(3, left);}, 200);
        break;
      case 3:
        document.getElementById('j').style.backgroundPosition = "-120px -50px";
        timer = setTimeout(function(){run_left(4, left);}, 200);
        break;
      case 4:
        document.getElementById('j').style.backgroundPosition = "-80px -50px";
        timer = setTimeout(function(){run_left(1, left);}, 200);
        break;
    }
  } else {
    document.getElementById('j').style.backgroundPosition = "0px -50px";
  }
}

Jumping Animation

Finally, we need to create a jump function. We will pass two arguments to this function, one that will track whether the div is currently moving up or down and another that will track the current top attribute of the div. Between the two, we will determine which direction the div needs to move next, and how far (we will move the div less distance near the arc of the jump to simulate acceleration with gravity).

function jump(up, top){
  /*
   * We change J to his jumping sprite ...
   */
  document.getElementById('j').style.backgroundPosition = "-160px 0px";
  /*
   * Here, we need to decide whether he should be traveling up or down...
   */
  if (up && (document.getElementById('j').offsetTop > 20)){
    // if he is currently moving up, and he is more than 20 pixels from the top of the stage ...
    top = top - (top * .1); // This gives us a slight arc in the jump, rather than a constant movement like running
    document.getElementById('j').style.top = top+"px"; // Change his position
    timer = setTimeout(function(){jump(up, top);}, 60); // Then call the function again
  } else if (up) {
    // if he is currently moving up, but he is almost at the top of the stage and needs to come back down...
    up = false; // we switch the 'up' variable so he will be falling in the next loop
    timer = setTimeout(function(){jump(up, top);}, 60);
  } else if (!up && (document.getElementById('j').offsetTop < 115)){
    // if he is moving down, but is more than 5px from the ground, he will continue to fall...
    top = top + (top * .1); // His fall will slightly accelerate
    document.getElementById('j').style.top = top+"px";
    timer = setTimeout(function(){jump(up, top);}, 60);
  } else {
    // If he is moving down, and he is within 5px of the ground...
    document.getElementById('j').style.top = "120px"; // Place him on the ground
    document.getElementById('j').style.backgroundPosition = "0px 0px"; // return to standing sprite
    // We do not call the loop anymore since he is standing still at this point
  }
}

Now we can put all four of our functions into buttons and have a working prototype of a running and jumping animation! Please check out the source code for this page with comments and download the sprite sheet that I used, if you’d like.


Conclusion

Now, although we have a working prototype here, you may notice it is a little buggy. When you click on more than one button at a time, the script will try to run both at once. Or, if you click the jump button again on the way down, J will continue to fall forever. Also, as I mentioned earlier, we have global variables in our script, which means it might be difficult to add this code into an existing page without crashing other JavaScript (which is also why I didn’t try to run this code within this blog page). In our next post, we will clean up all of these bugs and talk about the concept of encapsulation and why it is important to write good code in the real world.

07:30

Perfect Match: Adaptive Backgrounds for jQuery Colors Your Website Automagically


  

This plugin for jQuery is gas. Adaptive Backgrounds by Brian Gonzalez analyzes the colors of the images in your website, determines which ones are dominant and colors the background of the element containing the image accordingly. As Adaptive Backgrounds works with the nearest parent by default, you can have multiple different backgrounds on the same page. The effect is impressive.

January 27 2014

11:00

Slip.js: Small Script Touch-Optimizes Lists in Web Apps


  

Slip.js is not exactly new to me. I stumbled upon it a few weeks ago, yet didn’t get impressed at first sight. These days I had a real life usecase and faintly remembered Slip.js. Now, having worked through a real project with the help of that small script, I have to admit that Slip.js really is a clever tool for the creation of touch-sortable or – more general – editable lists in web apps.

January 22 2014

18:03

SVG and JavaScript: What Is Possible, What To Consider?


  

SVG has been around for quite some time now, waiting. Waiting for proper browser support. The wait is now over as all modern browsers support the format today. With Flash being on the decline, SVG has grown even more popular. Just like the proprietary Flash format, SVG is vector-based and can even contain animations. You need not even miss out on scripting, as SVG supports JavaScript right inside its own format. Think of an open ActionScript, only more commonly known.

January 14 2014

18:31

JavaScript Animation That Works (Part 1 of 4)

HTML is the language the web is built in, and it is kind of a strange beast. Although it was originally intended as a way to easily share academic information across the Internet, it has been slowly transformed to accommodate the media-rich environment we know and love, sort of like a cherished lawn mower that has been fitted with jet engines.

Because of the haphazard nature of HTML (and JavaScript, the programming language that manipulates elements in HTML and makes them interactive), sometimes we have to think outside the box a bit. In this tutorial series, I will show you how to do cross-browser animation using a method called spriting, using only JavaScript and HTML (and a bit of CSS too). And, because this is a learning opportunity (and I am stubborn and like to do things the hard way), we will be doing it all without any external libraries (like jQuery).

This will be a four-part series – I will explain the spriting itself in part one (this article) with some basic JavaScript, but then in later installments we will move into some intermediate techniques like encapsulation, event handling, and touch screen support.

So let’s get started!


What Is Animation?

Animation is based on a phenomenon called persistence of vision, which basically says that if your brain sees lots of similar still images fast enough, then it will appear as though it is one moving image. Every kind of film or video uses this basic technique – many, slightly different frames are shown in quick succession to make something appear moving. Film typically runs at 24 frames per second (₁), while broadcast television in North America is shown at 29.97 frames per second (₂). So, in other words, what we want to do is create something that shows similar frames really quickly (several times a second).


The Difficulties on the Web

There are two main reasons animation is difficult to use on the web:

  1. The first is that different web browsers have different ways they interpret HTML and JavaScript, so what works on one device often doesn’t work on another. Flash works great on most browsers, but support is starting to drop for it and iOS devices won’t allow it at all. Canvas has a lot of potential, but Internet Explorer 8 doesn’t support it. Same goes with Adobe Edge Animate. GIFs work on everything, but you can’t control the animation or make it interactive.
  2. And for the second, every time an image is served on a web page, a separate request is made between the browser and server. These requests can add up, even over a lightning fast Internet connection, making having several frames each second unmanageable.

The Solution: Spriting

One way around these problems is to make a sprite sheet. In elements like div‘s, we can set a background image for the div that may be larger than the element itself. We can also set the background position so that we determine exactly which part of the larger image will show. A sprite sheet is a larger image made of several smaller images that we can move around so that it could take the place of many small images. Take a look at the example below, using J, the mascot of my company Joust Multimedia:

javascript-spriting-j

Although there are ten different images of J, they are placed together on one larger PNG file (we are using PNGs because they can show transparency). If we have a div that is only the size of one of the images, and we set this PNG as the background, it will look like a single image.

See the Pen hazdm by Steven Riche (@StevenRiche) on CodePen.

Although this seems like a lot of trouble to go through to show an image, this method nicely fixes the two issues we had before. With very little JavaScript (one line!), you can change the background position of a div, and it works on everything. Also, since all of these frames are on the same image, it will only take one request to load that image in the page. So, once the page loads, it can switch between sprites with no problem at all.

So how do we set this up to animate easily then? The first step is to create the sprite sheet. You will want to know what the final dimensions of your image should be, and space the sprites accordingly in a grid. For instance, my J image is going to be 40px wide by 50px tall, so I lined up my sprites exactly 40px apart horizontally and exactly 50px apart vertically. It will probably be easiest if you set your starting sprite in the upper left corner.

Then we will set up a div with a bit of CSS to make sure that everything appears properly.

<div id="stage">
	<div id="j" class="character"></div>
</div>

And here is our CSS to make sure the sprite is showing correctly:

.character {
	/*
	 * Very important that we set the height and width of 
	 * our characters to the height and width of the sprites
	 */
	height:50px;
	width:40px;
	/*
	 * We need to position them absolutely so we can have full  
	 * control over their position within the stage
	 */
	position:absolute;
	left:100px;
	top:120px;
}

#j {
	/*
	 * And now we set the background image for the character div 
	 * to be the first sprite (in the upper left corner)
	 */
	background-image: url('j.png');
	background-repeat:no-repeat;
	background-position:0 0;
}

Notice the following things:

  • We specify the width and height of the div to the size of our sprite
  • We specify the background-repeat to 'no-repeat'
  • We specify the background-position to '0 0' – this will show the sprite in the top left corner

Now, it will just take a single line of JavaScript to change the background position to show the next sprite.

document.getElementById('j').style.backgroundPosition = '-40px 0px';

Here, we are selecting the element (with id='j'), and setting the style attribute 'backgroundPosition'. Notice that it is spelled 'backgroundPosition' in JavaScript, and not like 'background-position' in CSS. Also notice that in JavaScript, the 'px' is required for both the x and y amount – we cannot just pass it numbers. And because we are moving the background image, we have to move it in the opposite direction from what you might expect – to move to the sprite on the right, we have to have the image move 40px to the left.

Now, if we just have something simple to execute this code (like a button), we can see the frames changing in action.

See the Pen DIsgk by Steven Riche. Check out the source code for this page. It has all of the examples here with thorough comments. And here is a link to the sprite sheet I am using.

Next Up

This is still not really animation though – in part two of this series we will actually animate some running and jumping, by creating loops with the different sprites.

By part four, we will be creating mouseovers for a bit of robot action.

See the Pen ByGtv by Steven Riche.


In Conclusion & Drawbacks

Although this can be a great method for animating on the web, there are a few drawbacks. First, it can require you to create each individual frame of animation, which can be time-consuming. Second, browsers don’t have the most accurate of timers for animation, so if it is critical for your animation to be timed perfectly, then this may not work. Finally, mobile Safari (used on iPhones and iPads) has a “feature” where if you have a background image that is either larger than 2MB or larger than 1024 X 1024 X 3 pixels (or 3,145,728 total pixels), it will automatically rescale the image, ruining the spriting effect. This means that really large sprites, or animations with a very large number of sprites, is out of the question. But, for simple, small animations that you want to be very interactive, this is an easy and great way to get something that works everywhere.

Interesting Side Notes

1: Before sound was introduced with film, there wasn’t really a standard frame rate. The cameras were operated by a hand crank, so if you had a rookie cameraman the frame rate might slow down and speed up dramatically unintentionally. Similarly, less reputable theaters were notorious for telling their projectionists to crank the projector quicker to speed up the show so they could fit in more screenings. This is also why we stereotypically think of pre-sound movies as moving around comically fast – most were filmed around 16-18 fps, so when we play them today at 24 frames per second, they are moving faster than they were originally intended.

2: Television was originally broadcast at 30 fps in North America, but color television caused a glitch when shown at that speed. Engineers figured out that they could fix it by slowing down the frame rate by 0.1%, which is why it is now set at 29.97 fps. Also, besides all of the wacky technical issues involved with converting a film in 24 fps to display on television at 29.97 fps, showing television at a faster fps has had an interesting effect on the public. Many people watching the test screenings of “The Hobbit” at 48 fps reported that the increased frame rate made the film look “cheaper”, even though it was much higher quality than a typical film, just because they had grown to associate faster frame rates with watching something on television.

January 10 2014

11:00

Wallpaper for jQuery Adds Image or Video Backgrounds to Any Website Easily


  

Such is life. Client X needs a landing page within the next 15 minutes. It’s a rather simple page with not a lot more than a full-screen background image. Now, how can I achieve that in the quickest and easiest way? Having evaluated a few alternatives I decide to go with Ben Plum’s newest jQuery plugin Wallpaper. This lets me do the job in less than ten minutes. Being able to change the image to a video background using the very same solution made my client smile with joy…

January 08 2014

11:00

DevDocs: The Ultimate Work of Reference for Web Developers


  

Thibault Courouble is back. The philosopher and front-end developer from France created yet another useful web service for developers. His new project DevDocs has the potential to become the ultimate work of reference for anybody building web apps. DevDocs integrates a plethora of different documentations and equips them with a spanned search function. This is a very good idea…

January 06 2014

11:00

Summernote: Powerful WYSIWYG-Editor for Bootstrap 3


  

Today I stumbled upon a fresh JavaScript, which I think you will like, too. This little tool helps you integrate a feature-rich WYSIWYG editor into your next Bootstrap project. And it is entirely free. Summernote – say hi – is under ambitious development and bound to reach version 1 in the course of the next few weeks. You need not wait, though, as Summernote is perfectly ready for prime time just yet.

December 30 2013

07:30

Codeblock.js: Edit and Run JavaScript Directly from Within Your Browser


  

Talking about introducing JavaScript frameworks, libraries or just step by step tutorials, it is always useful, if you are able to support all your words by a handful of fitting live examples. So, instead of just posting dead code snippets, would it not be far better, if you could embed JavaScript in a way that it can be edited and run by your readers, without forcing them to download examples and what not first? That’s what Codeblock.js offers…

December 17 2013

10:00

Let It Snow: Festive Resources to Santa up Your Website


  

In these special times we tend to not only decorate houses, streets, the whole country, basically. We don’t even leave our websites untouched. Christmassy looks are mandatory these days. If you are on the lookout for a bunch of effects to implement on your blog, portfolio, whatever, look no further. We have compiled a small collection of just what you need to bring that Santa sparkle to the eyes of your visitors.

December 11 2013

03:32

Grunt for People Who Think Things Like Grunt are Weird and Hard

Chris Coyier grabs Grunt by the snow-white fur of its Santa suit and places it firmly (but gently) in your webdev grotto to dish out its Christmas gifts — and maybe even chuck you under the chin and sit you on its broad and comfy knee. Not at all creepy. No. Nope.

Brought to you by Shopify, the fully customizable ecommerce platform loved by designers around the world.

December 05 2013

02:52

JavaScript: Taking Off the Training Wheels

Tom Ashworth exhorts us to become more familiar with JavaScript so we can better understand and use new tools like Node and Grunt — it’s always the box the gift comes in that’s more useful and fun, right?

December 02 2013

12:00

Make Your Browser Dance

Ruth John ushers the Christmas party disco online using the Web Audio API to festoon your browser with some twinkling scripted lights that pulse along with your favourite festive tunes. So don’t be a wallflower — Santa’s up all night to get lucky…

Brought to you by Shopify, the fully customizable ecommerce platform loved by designers around the world.

November 13 2013

11:00

Deal of the Week: jQuery Trickshots Teaches You 100 Advanced Techniques for Less than a Movie Ticket


  

The neat thing about programming is that there are always tons of different ways to accomplish the same result. Some are tougher, more complex, and take a lot longer to implement. Others, however, can make your life incredibly easier and save you a load of time… like JavaScript and the wonderful jQuery library. With the right knowledge, jQuery can perform some fantastic functions with very little programming needed.

October 22 2013

06:30

Bento: One-Stop Shop for Online-Courses on Web Development


  

It’s merely a few weeks ago, that we brought you a comprehensive overview of 22 of the online learning resources the planet has to offer. Just today we stumbled upon another effort for web designers, developers and programmers. An offering by the name of Bento curates the best learning resources in its field. The collection is community-based and as such more helpful than any Google search result could ever be ;-)

October 21 2013

06:30

The 500 Dollar Blogger Bundle Giveaway: Noupe is Looking for 3 Winners


  

Dear readers of our lovely Noupe magazine. Today we teamed up with Envato to bring you the opportunity to win The Blogger Bundle. The Blogger Bundle consists of over 500 dollars worth of files. For a limited time, you can buy this bundle over at Codecanyon for just 20 dollars. But we encourage you to first try your luck and participate in our giveaway game. Three readers will be randomly drawn from all correct entries. Read on…

October 15 2013

06:30

One-Stop Shop: PHP-Tool Munee Cares for All your Website’s Assets


  

Cody Lundquist, Australian with a Swedish sounding name, created a free asset-management based on PHP 5.3. Its feature-set is astounding, yet demands a special preliminary treatment of the websites, it’s supposed to be working on. Munee is able to manage any kind of possible asset, be it images or other files, JavaScript, CSS, LESS, SCSS or even CoffeeScript.

September 25 2013

06:30

Flat, Mobile, Responsive: Fresh JavaScripts and jQuery Plugins Made in September 2013


  

jQuery plugins and JavaScript tools are collectibles you can’t get enough of. Just like WordPress themes, fonts, icons, basically any resource for designers and developers, they are available in masses. To separate the wheat from the chaff is harder than simply finding them. Regarding JavaScript tools keeping up with development is especially important. If you choose to integrate a third-party tool you should not decide to go for any medieval creations but make sure to get something recent and modern. We have curated some of the best and most recent tools. THey are all free and they are all fresh…

September 18 2013

14:00

How to Easily Manage Cookies Within jQuery

tutorial screenshot cookies with jQuery howto

Web browsers can generate unique sessions organized for each user on a website. Often these are handled on the backend using languages like PHP or Ruby, but we can also utilize cookie sessions on the frontend with Javascript. There are many tutorials out there explaining how to generate pure JS cookies. But a newer library jQuery Cookie simplifies the whole process.

I want to explain how we can build a very simple authentication system using jQuery Cookies. The code is all handled on the frontend but you will need a live testing server to see any results. Browser cookies are created on the local IP which comes from the web server, and so unfortunately you can’t just run these scripts locally. But definitely check out my live demo to get an idea of what we are creating.

Live DemoDownload Source Code

Document Base

First I am creating a sample HTML5 document with a single link to the jQuery library, along with the jQuery Cookies function. You can download this directly from the Github repo and the only file we need is jquery.cookie.js.

<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Managing Cookies with jQuery - Live Demo</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://designshack.net/favicon.ico">
  <link rel="icon" href="http://designshack.net/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
  <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
  <script type="text/javascript" src="js/jquery.cookie.js"></script>
</head>

The tutorial itself will focus on creating two distinct views for the page. First we have a login form which displays when the cookie is not set. Using the default values of demo/demo you can log into the form and it will store your session in a cookie.

Obviously when connecting into a database you can pull from a large number of usernames. This means you can authenticate many people using the same script and storing their username or user ID into a local cookie. This example provides a starting point where we don’t need any Ajax requests or backend scripts to authenticate a user.

Inner Body Contents

The first containing div is a wrapper which holds all the rest of the page. There is a form with the ID #loginform which is first to display. This will be hidden using jQuery only if the visitor is currently logged into the demo account with a session cookie.

<div id="w">
  <div id="content">
    <h1>Basic Cookie Management</h1>
    <p>Login to the demo account with the following username/password: demo/demo</p>
  
    <form id="loginform" method="post" action="#">
      <label for="username">Username:</label>
      <input type="text" name="username" id="username" class="basic" placeholder="username...">
    
      <label for="password">Password:</label>
      <input type="password" name="password" id="password" class="basic">
    
      <input type="submit" name="submit" class="button" value="Login">
    </form><!-- @end #loginform -->
  
    <div id="logindetails">
      <!-- when user is logged in we display this div -->
      <p>You are logged in as <strong>demo</strong>! The cookie is set to expire in 1 day from the original login.</p>
    
      <p>Want to logout? Easy!</p>
    
      <p id="logoutcontainer"><a href="#" id="logoutbtn" class="button">Logout Now</a></p>
    </div><!-- @end #logindetails -->
  </div><!-- @end #content -->
</div><!-- @end #w -->

You will notice in the HTML after the login form there is another div with the ID #logindetails. I have this hidden using CSS styles because we only want this displaying to the user if they are currently authenticated. The internal HTML is static always displaying the username as demo – but when pulling from a database you can update this with JavaScript for any username.

The CSS styles are not too confusing but it is worth going over some pieces. I have built a glossy CSS3 button from this Codepen post which also has some other examples. The styles are quite in-depth but worth saving to possibly reuse on other websites.

/** form elements **/
form label { font-size: 1.1em; line-height: 1.25em; font-weight: bold; margin-bottom: 5px; }

form input.basic {
  display: block;
  outline: none;
  font-size: 1.5em;
  color: #525252;
  width: 300px;
  padding: 10px 8px 10px 8px;
  margin-bottom: 7px;
  border: 1px solid #888;
  border-radius: 5px;
  -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,0.4);
  -moz-box-shadow: inset 0 1px 2px rgba(0,0,0,0.4);
  box-shadow: inset 0 1px 2px rgba(0,0,0,0.4);
}

#logindetails {
  display: none;
}

I also redesigned the basic form inputs to blend nicely into the page. The login details container is given display: none so it will not take up any room in the rendered page. However it is still an active part of the DOM which means we can manipulate this display value in jQuery. Now let’s look into this jQuery code located at the bottom of the page right before the closing </body> tag.

Cookies in jQuery

This plugin offers a number of standard features which would require a whole lot more logic in regular JavaScript. There are pre-built internal methods for calling a new cookie and deleting any existing one. We can look at the first opening code block to understand the displays:

$(function(){
  if($.cookie('username')) {
    $('#loginform').hide();
    $('#logindetails').show();
  }

There is likely a better way to handle this form using backend languages, but jQuery works great for this demo. By calling an if statement against $.cookie(‘username’) we are checking if the cookie “username” exists. If so then we know a user is currently logged into their account, so we hide the login form and show the login details. Otherwise nothing happens and we just see the page with the login form as it would normally appear.

  $('#loginform').submit(function(e){
    e.preventDefault();
    var inputuname = $('#username').val();
    var inputpass  = $('#password').val();
    
    if(inputuname == "demo" && inputpass == "demo") {
      // successful validation and create cookie
      $.cookie('username', 'demo', { expires: 1 });
      var currentusr = $.cookie('username');
      window.location.reload();
    }
  });
  
  $('#logoutbtn').on('click', function(e){
    e.preventDefault();
    if($.removeCookie('username')) {
      $('#logoutcontainer').html('<strong>Successfully logged out! Refreshing the page now...</strong>');
      window.setTimeout('location.reload()', 2000); // refresh after 2 sec
    }
  });
});

I’ve combined these two functions into a single block of code because they are closely related. Once the user attempts to log into an account we make sure the username/password is equal to “demo”. If successful then we call $.cookie(‘username’, ‘demo’, { expires: 1 }); which includes a number of options.

First we set the cookie name to “username” which is how we can check its value. The string “demo” is the value of this cookie, but remember we could pass any username or even an ID string if that works better. Finally the last parameter is a collection of options which sets the number of days before the cookie would expire. If we omit the expires option then the cookie will be deleted once the user closes out of their browsing session. This is also referred to as a session cookie and I’ve written a basic example commented out at the bottom of the script.

The second code block is listening for a user to click on the #logoutbtn link. Naturally the logout link will only display when the current visitor is already logged in. This function will terminate the session by calling $.removeCookie(‘username’) inside an if statement. So if we can delete the cookie, then we remove the logout button to show a success message followed by a refresh to present the original login form again.

Live DemoDownload Source Code

Final Thoughts

Cookies are very helpful even aside from storing logins to various user accounts. You can organize an ecommerce website based on backend sessions with a unique cookie ID. Shopping carts are so popular nowadays and the advancements in web development have made them much easier to setup. Feel free to download a sample copy of my script and see if you can implement live cookies on any of your own web projects.

Tags: JavaScript
Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!

Schweinderl