Bouncing Balls in the HTML5 Canvas

Published February 3, 2014 by saurav.roy.

Here’s a fun demo I put together using the HTML5 canvas, aided by the excellent sketch.js framework. I’m creating hundreds of semi-transparent balls and bouncing them around on the screen. The demo definitely requires a modern browser (Chrome/Firefox/IE9+).

See the Pen Bouncing Balls in sketch.js by Rob Glazebrook (@rglazebrook) on CodePen.

Sketch.js simplifies getting started building demos like this by providing a bunch of things that would normally have to be built by hand: an animation loop, drawing context, and so on. It also provides a few nice math-y functions, like random(), which you’ll see I’m using all over the place.

I’ll walk through the code briefly to give you an idea of how it works, and how you can edit this one or make your own. You can follow along in the JS tab above. Read On…

Intelligent Select Box Filtering

Published July 16, 2010 by saurav.roy.

One of the great things about building websites for a living is the challenges tend to change from day to day. There’s always a new puzzle to solve.

Take today, for example. I was building a page that contained a series of select (dropdown) boxes. Now, I’ve been around the block once or twice before, and this wasn’t my first time using selects. However, this implementation came with a unique twist: all the boxes contained the exact same options, but we only wanted each to be selectable once. Specifically, each box contained a list of security questions — your mom’s best friend’s grandmother’s maiden name, that sort of thing.

The code looks something like this:

<select class="security" name="security1">
	<option value="0">Select a question.</option>
	<option value="1">Who's your daddy?</option>
	<option value="2">What's your favorite color?</option>
	<option value="3">What time is it?</option>
</select>
<select class="security" name="security2">
	<option value="0">Select a question.</option>
	<option value="1">Who's your daddy?</option>
	<option value="2">What's your favorite color?</option>
	<option value="3">What time is it?</option>
</select>

Now, naturally, we want the user to select several different security questions. But what’s to stop them from selecting the same question several times? Well, in our case, back-end validation… but I wanted to solve the problem before we got to that point. I wanted to eliminate “selected” questions from all the other dropdown boxes, so it wouldn’t even be an option. This has the added benefit of shortening the list of options as the user goes along, which would make scanning the options easier. Read On…

Cross-Browser Rounded Buttons with CSS3 and jQuery

Published April 22, 2010 by saurav.roy.

So here’s the scenario: I was tasked with replacing several dozen Photoshop-generated rounded buttons for a larger site with an HTML/CSS/JS equivalent. Prior, any time anyone wanted to change text on a button (and it seemed to happen often), a graphic designer had to fire up Photoshop, modify a file, adjust for size, output an image, and pass that file off to the person building the page. It was an involved process for something that should have been simple.

So let’s make it simple!

Right away I knew that I wanted to present as simple a solution for the developer as I could. I didn’t want to force them to use tons of extra markup in their HTML to pull this trick off. This was a piece of cake in modern browsers, as you’ll see in a moment. Unfortunately, this site also has a large IE user base, so I needed to account for less-modern browsers as well.

Border-Radius for Those Who Can

I decided I wanted to use border-radius for the rounded buttons for any browsers that could support it. I also decided that I wanted to create a single class, “button,” for any buttons, and it should work more-or-less the same on anchor tags, button tags, and “submit-type input tags. Read On…

Test for Border-Radius Support

Published April 15, 2010 by saurav.roy.

Of all the fantastic magical CSS3 properties out there, border-radius was one of the first I really latched on to. It made sense to me from the start, and I could see immediate practical uses (at least, as far as a border can be practical). If you’re not using the border-radius property yet, be sure to check out my article on how to use it.

Unfortunately, even though more advanced browsers started supporting border-radius years ago, not all browsers are up to speed yet. As of this writing, border-radius is supported in Webkit (Safari/Chrome), Firefox, and rumor has it Konqueror, though I don’t have a Linux install so I can’t prove that. That leaves Opera and Internet Explorer out of the game – I’ve heard rumors that Opera will support border-radius soon, but the latest version is still a no-go.

As I argued in my last article on the topic, most of the places people should use rounded corners today fall into the realm of “progressive enhancement”: the site looks better with the element rounded, but it’s not the end of the world if someone sees a square corner.

Of course, what should be true and what a client requires aren’t always the same thing. Read On…

Show Your Google Analytics Top Content in WordPress

Published March 25, 2010 by saurav.roy.

Google Analytics Top Content on WordPress

If you’re a typical blog owner, one of your biggest goals is to keep visitors browsing your site. One of the best methods for doing that is to provide links to additional content on your site that your visitors might like. I’ve been doing this for a while with the “Related Articles” section at the bottom of every article (check it out if you haven’t noticed it before).

But many top-tier blogs also showcase their overall most popular posts. These are the articles that often bring in a lion’s share of the site’s traffic, so they must have something going for them, right?

There are a lot of plugins out there that help bloggers rate and publicize the popular content on their blogs. Alex King’s Popularity Contest is a perennial favorite, but it has a lot of overhead, and it often breaks when a new version of WordPress comes out. For that reason, I’ve stopped using it on my site. At one point I’d even written a simple WordPress plugin for my own use that tallied up the number of comments, trackbacks and pingbacks each post had and used that to determine “popularity.”

But let’s say you have a WordPress site and are tracking your stats with Google Analytics. You and I have that in common. If that’s the case, then you already know which pages on your site are the most popular. Google Analytics’ Top Content section makes it a breeze to see what pages on your site get the most traffic (Content -> Top Content, in case you haven’t found it before).

What isn’t as easy is to take that information and display it on your site. But earlier this week I figured out a pretty simple way by piggybacking on an existing popular Google Analytics WordPress Plugin. Read On…

Build a Bare-Bones WordPress 2.8+ Widget

Published December 21, 2009 by saurav.roy.

This tutorial is going to be a little more advanced than some of the fare around here, but in the end you’ll have all the information you need to know to create your very own WordPress widget! And that’s worth the effort, I think. However, you will need to understand a little bit of PHP for this to make much sense.

Widgets — essentially fancy drag-and-drop plugins, commonly used in sidebars — have existed in WordPress for quite some time, but with the release of WordPress 2.8, developers have a brand new widget API that makes creating widgets for WordPress a little bit easier. This tutorial will use the new system for developing our barebones “Hello World” widget.

Download the zipped source code here.

I should also note up front that this isn’t the only way to build a widget. This is simply the way I have learned, and a way that is compatible with the new WordPress 2.8+ widget API. Read On…

Advanced jQuery Tabbed Box Techniques

Published January 25, 2009 by saurav.roy.

animated tabbed box interface

Last week’s article covered how to build a tabbed box interface, starting with Photoshop, and moving through XHTML and CSS to our basic jQuery functionality. If you missed it, I would highly recommend starting your reading there. This article will show you how to use jQuery to make your tabbed interface more attractive and interactive. Specifically, I’ll show you how to:

  • Make your tabs all the same height
  • Automatically rotate through your tabbed content
  • Stop the rotation when the user is interacting with the content

Equal Height Tabs

The tabbed interface we built last week was fully functional, but one nicety I’d like to add is the option to have all your tabs be the same height – a height that is determined by the content within the tabs, not any number I arbitrarily determine in advance. Read On…

Show/Hide Content with CSS and JavaScript

Published May 5, 2008 by saurav.roy.

There are plenty of reasons why you might feel the urge to wax verbose on your website’s front page: to prevent your users from having to click through to a new page to find your information, to avoid having to reload the page, or even to improve your front page’s SEO. But just because your front page is text-heavy doesn’t mean it all needs to be visible at once.

Today’s tutorial will show you how to hide away extra bits of content using CSS and JavaScript, to be revealed at the click of a button. This is a great technique, because displaying the additional content doesn’t require a refresh or navigation to a new page and all your content is still visible to search engine bots that don’t pay any attention to CSS or JavaScript.

We’ll start with structuring our XHTML appropriately:

<p>...This is all visible content... 
<a href="#" id="example-show" class="showLink" 
onclick="showHide('example');return false;">See more.</a>
</p>
<div id="example" class="more">
	<p>...This content is hidden by default...</p>
	<p><a href="#" id="example-hide" class="hideLink" 
	onclick="showHide('example');return false;">Hide this content.</a></p>
</div>

There are three things of importance here: the “show” anchor, the “hide” anchor, and our “hidden” div. Each has been given an ID and a class. The IDs are used by our JavaScript to locate and style the items appropriately. I’m then using the classes to set our “default” CSS. Technically you could just use the IDs the set that CSS as well, but if you wanted more than one hidden section on your page, that could get messy.

You’ll notice in the code above that all of our IDs are fairly similar. This is a trick I’m using to simplify our JavaScript, as you’ll see later on down the road, so I suggest doing something similar. The class names have no relationship to the JavaScript whatsoever, and could really be whatever you wanted them to be.

It’s also important to note that we’re calling our JavaScript using the “onclick” call, and passing it the name of our hidden div. Our JavaScript will use that single variable to do the rest of the work.

Now that we have our XHTML in place, let’s put together our default CSS:

.more {
	display: none;
	border-top: 1px solid #666;
	border-bottom: 1px solid #666; }
a.showLink, a.hideLink {
	text-decoration: none;
	color: #36f;
	padding-left: 8px;
	background: transparent url('down.gif') no-repeat left; }
a.hideLink {
	background: transparent url('up.gif') no-repeat left; }
a.showLink:hover, a.hideLink:hover {
	border-bottom: 1px dotted #36f; }

I’m technically doing far more styling than is necessary here, mostly for aesthetic purposes. The only truly important style is the “display: none;” rule on our .more class. This hides our extra content by default. The rest of the CSS simply adds a border to our div (the border is hidden by the display rule, but becomes visible later) and fancied up our show/hide anchors by putting down/up arrows next to them and replacing the standard underline with a dotted border. You could style these yourself however you like, and everything would still work just fine.

Next comes the JavaScript, which looks far more complicated than it is:

function showHide(shID) {
	if (document.getElementById(shID)) {
		if (document.getElementById(shID+'-show').style.display != 'none') {
			document.getElementById(shID+'-show').style.display = 'none';
			document.getElementById(shID).style.display = 'block';
		}
		else {
			document.getElementById(shID+'-show').style.display = 'inline';
			document.getElementById(shID).style.display = 'none';
		}
	}
}

Our JavaScript is doing four things here:

  1. It checks to see if it can find an element with an ID that matches the variable we passed it.
  2. If so, it checks to see if our “show” link is visible (this is where the ID naming convention starts to matter).
  3. If the “show” link is visible, that means our content is still hidden. The JavaScript then hides the link and displays our hidden content.
  4. If the “show” link is hidden, that means our extra content is currently visible. So it just reverses course, displaying our link again and hiding our extra content.

And that’s it! You can see a working example in action here.

Our job has been made much simpler by a few tricksy tricks. First off, we’re using the same function to show and hide our content, which saves us a bit of coding time. Our function simply checks on the state of things: if things are hidden, it shows them, and vice-versa.

Second, by using a defined schema for our element IDs (“example,” “example-show,” and “example-hide,” in our example above), we only need to pass our JavaScript a single variable. It then uses that variable to find all of our other elements and style them appropriately.

And finally, we put our “hide this content” anchor inside the hidden div. This means that we never have to set its display property: it’s hidden when the container is hidden, and visible when the container is. That saves us two lines of JavaScript and at least one line of CSS.

This technique could be used in loads of situations. Say for example that you have a WordPress blog and the front page shows excerpts instead of the full article. You could use this technique to have the whole article on the front page for the search engines to find, visible to your users at the click of a button. Or maybe you have a complex form that could use some detailed in-page explanation, but you don’t always want the help content visible, eating up real estate when some users already know what to do. Or… well, anything, really. Let me know if you come up with any creative uses!

The CSS-Only Accordion Effect

Published April 9, 2008 by saurav.roy.

Update: I’ve created an advanced version of this technique that works in IE6! Read more here.

The Accordion Effect is fast becoming one of the most commonly used (and perhaps abused?) effects of the Web 2.0 world. Most JavaScript frameworks make such an effect fairly easy to pull off – heck, MooTools even built their reputation on it in the early days. So what makes this accordion effect special? It doesn’t require a single line of JavaScript.

First off, what is an “accordion” effect? Generally speaking, the accordion effect takes several larger elements and then compresses them into a small space so that only a small portion (like a heading) of most or all of the elements is visible. Then, when the user interacts with that element — either by clicking on it or maybe only mousing over — the accordion expands so that the element of interest is visible, and the other elements shrink down automatically. When it’s in use, it looks a bit like an accordion expanding and contracting: hence the name.

Our accordion will work exactly the same way: all of the elements will be partially visible when the user loads the page. And then when they mouse over a particular section, it will instantly expand – and the other elements will contract – to make reading more easy.

example of accordion effect before and after the user mouses over it

So how do we accomplish this trick? First, we start with our XHTML, which just consists of a couple of divs with some IDs applied:

<div id="accordion">
	<div id="part1">
		<p>This text is in part 1.</p>
	</div>
	<div id="part2">
		<p>This text is in part 2.</p>
	</div>
	<div id="part3">
		<p>This text is in part 3.</p>
	</div>
	<div id="part4">
		<p>This text is in part 4.</p>
	</div>
</div>

My first div defines where my accordion starts and ends. The divs nested inside are just parts of my accordion – they don’t even technically need IDs unless I want to style them differently. That’s all the XHTML it takes!

So now, let’s start building our accordion. We start by defining the physical limitations of our space:

#accordion { 
	width: 500px; 
	margin: 100px auto; }

All I’ve done is give my accordion a specific width and centered it in the page for a nice visual effect. Now, I have to create the default state for the divs inside of my accordion:

#accordion div {
	float: left;
	width:25%;
	height: 300px;
	overflow: hidden;}

This snippet floats all of my divs to the left and gives them a specific width and height. I’ve chosen a width of 25% because I have four elements in my accordion, so they all split that width up evenly by default. If I’d had five elements, I would have used 20%, and so on. My height of 300 pixels also becomes the height of my accordion div.

The overflow: hidden part here is also crucially important. This is what prevents my divs from either resizing to fit their content or spilling their content out of the containing div and onto our page. It also creates a nice visual effect… people will wonder what content they’re missing, and will mouse over the area to investigate.

extra text is hidden from the user, inspiring curiosity.

So now that we’ve created our default state, we need to create our hover or “active” state. This requires two CSS rules. The first looks like this:

#accordion:hover div { width: 20px; }

We’re using the :hover pseudo-class here in a pretty creative way – we’re telling all of the divs inside of the div we’re hovering over to change. Specifically, we’re shrinking them all down to 20 pixels to make room for our expanded accordion section. So now we just need to make sure it expands:

#accordion:hover div:hover {
	width: 440px;
	overflow: auto; }

The :hover pseudo-class comes into play here again. Now, we’re applying styles to an element we’re hovering over, inside of an element we’re hovering over. We’re styling this element differently than our others by giving it a specific width – 440 pixels, i.e. 500 pixels minus the 20 pixels taken up by our other three divs – and setting its overflow to “auto.” These two classes cause our active div to expand, and then give it a scroll bar if the content is too long.

And that’s all there is to creating a CSS-only accordion box! If you’d like to see it in action, click here. The only change I’ve made to the full version is I’ve added a few background styles and some interior padding to each of the accordion sections to make them stand out and look a little more attractive.

This example creates a horizontal accordion box. But it’s just as easy to create a vertically oriented accordion. All we really need to do is eliminate the floats on our nested divs and turn most of our width tags into height tags. Here is the markup:

#accordion {
	width: 500px;
	height: 400px;
	margin: 20% auto; }
#accordion div {
	height:25%;
	overflow: hidden;}
#accordion:hover div {
	height: 20px; }
#accordion:hover div:hover {
	height: 340px;
	overflow: auto; }

And you can see it in action here.

As with any trick this cool, there are some caveats. Most significantly: this technique does not work in IE6, (update: now works in IE6! Read more here) because IE6 doesn’t support hover states on anything other than anchors. Therefore, you can make it work if you’re willing to make a sacrifice: if you wrap all of your divs in anchor tags, and then apply the hover state to those anchors instead of your divs, the technique should work the same (I haven’t tried it, though). However, that wouldn’t be particularly semantic or valid, so I’m not showing it here.

Also, if you apply any padding or borders to your #accordion div, that can cause some problems. The border and padding are part of your div, and therefore part of your :hover class. However, if you’re hovering over the containing div’s padding, you aren’t hovering over one of the sections of your accordion – meaning all of your interior divs will shrink down to their smallest size, and none will grow to fill the space. It took me half an hour of debugging to figure this one out. :)

So there you have it. Use it, share it, love it. And let me know in the comments if you come up with a particularly interesting or attractive implementation – mine is obviously pretty simple!

Perma-Closing Message Boxes with JavaScript + CSS

Published April 2, 2008 by saurav.roy.

message box

Earlier this week I talked a bit about message boxes – how to style them and position them on your page to get them noticed. But a message that pops up every single time your website is loaded could get annoying. It’d be useful to give your users the ability to close those messages. For that, we’ll turn to our friend JavaScript.

We’ll start by building our message box in XHTML. Mine looks like this:

<div id="message-1" class="msgbox">
	<a href="#" id="close" title="Close This">X</a>
	<p>My uber-important message goes here!</p>
</div>

I’ve made a div with both an ID and a class. This will come in handy later when we need to reference our object in our JavaScript. Inside, I put an anchor tag with a class of “close.” This will become my close button later. And then I simply added a paragraph to hold my message.

Next up, we’ll want to style that message box. You can make it look pretty much however you want, and Woork has a nice article on styling message boxes, if you’re interested in discovering alternative styles. For my message box, I wrote this:

.msgbox {
	position: absolute;
	top: 15px;
	right: 20px;
	width: 20em;
	background-color: #b00;
	border: 1px solid #333;
	color: #fff;
	font-weight: bold; }
.msgbox p {
	margin: 0;
	padding: 5px 10px; }
.msgbox a.close {
	float: right;
	text-decoration: none;
	font-weight: bold;
	color: #333;
	background-color: #fff;
	border-left: 1px solid #333;
	border-bottom: 1px solid #333;
	padding: 0 4px;
	margin-left: 5px; }

Three rules are at play here. First, I’m styling the message box itself, using the class I gave it. I’m absolutely positioning the element and giving it a width. I’m also giving it a red background, bolding the text inside and turning it white, and applying a border. Then I’m applying a bit of styling to the paragraph inside to push it away from the side of the box.

Why didn’t I apply that padding to the message box itself? Because of the “close” link. I wanted to be able to float it to the right of the box and give it some styles to make it look more like a “close” button. After all of that CSS, this is what I have:

example message box

But so far, we just have a message box. That close button doesn’t do much of anything. For the rest, we’ll turn to JavaScript. All we need is a little function like this:

function closeBox(toClose) {
	document.getElementById(toClose).style.display = "none";
}

This function takes a single argument (toClose) which tells it the ID of the element we want to make disappear. We supply argument when we call the JavaScript. In this case, because we want it to happen when someone clicks our close box, we’d add it to our XHTML like this:

<a href="#" class="close" 
onclick="closeBox('message-1'); return false;" 
title="Close This">X</a>

We’ve added the “onclick” attribute to our “close” link tomake it fire a bit of JavaScript when the element is clicked. We’re telling it to call our closeBox function that we just wrote, and we’re giving it the ID of the message box we want to close. The “return false” part basically tells it to stop (that is, not to actually go to our specified href afterwards).

That’s all we need to create a message box that closes! However, if your users close the box and then refresh the page, the message box comes right back. What if we want it to close permanently? For that, we’ll need some more fancy JavaScript, because we’ll need to make use of cookies.

The cookie will act as a check that we can refer back to. When the user closes the message box, we’ll set a cookie. Then, when they come back to the page, we’ll check to see if the cookie is set. If there’s no cookie, we’ll show them the message. If there is a cookie, we’ll keep the message box hidden.

First, we’ll make a small change to our CSS:

.msgbox {
	display: none; /* Start out hidden. */
	position: absolute;
	top: 15px;
	right: 20px;
	width: 20em;
	background-color: #b00;
	border: 1px solid #333;
	color: #fff;
	font-weight: bold; }

All we’re doing is adding a “display: none” to the top of the element. By default, we don’t want our message box to show up. Instead, we’ll use JavaScript to display it if we want to see it. Why? It’s a usability thing: this way, if a user doesn’t have JavaScript enabled, they don’t see the message box. That may seem like a bad thing, but consider the alternative: if we didn’t set this rule, then anyone without JavaScript couldn’t get rid of your message box. And depending on its placement, that could be a big usability problem.

So now we need two extra functions in our JavaScript: one to set the cookie when we close the box, and another to check to see if the cookie exists when the user comes back. Our JavaScript now looks like this:

function closeBox(toClose) {
	document.getElementById(toClose).style.display = "none";
	setCookie(toClose, "closed", 365);
}
function setCookie(cName, value, expiredays) {
	var expDate = new Date();
	expDate.setDate(expDate.getDate()+expiredays);
	document.cookie=cName + "=" + escape(value) + 
	";expires=" + expDate.toGMTString();
}
function loadMsg(msgClass) {
	msg = document.getElementsByTagName("div");
	for (i=0; i<msg.length; i++) {
		if(msg[i].className == msgClass) {
			if(document.cookie.indexOf(msg[i].id) == -1) {
				msg[i].style.display = "block";
			}
		}
	}
}

First off, we modified our closeBox() function to make a call to the setCookie() function after it’s hidden the message box.

Next comes the setCookie() function. It takes three arguments: the name of the cookie, the value to be set, and how long the cookie should last before it expires (in days). We could have hard-coded some of this stuff to save time and space, but this way you can reuse this same function to set cookies all over your site – not just for this purpose.

Also, note that we’re using the toClose variable for our cookie name in setCookie()… which you might also remember is the ID of the message box itself. This is a useful trick, because this means you could theoretically have multiple message boxes with different IDs (all with the same .msgbox class) on your page, and you could open and close them separately, because each of their states would be set in a unique cookie.

Next comes the loadMsg() function. It takes one argument: msgClass. This variable represents the class you’ve set on all your message boxes. Our loadMsg() function cycles through all the <div> tags on your website and checks to see if they have the “msgClass” class set (whatever that happens to be… in my document, that was “msgbox”). If it finds such a div, it checks to see if it can find a cookie with a name that matches the ID set on that div – in our example it would be looking for “message-1.” If it doesn’t find a match (meaning the user hasn’t closed the box), then it sets that div to “display: block,” meaning it will show up normally. Otherwise, the message box stays hidden.

Now, all we need to do is ensure the loadMsg() function runs when the page first loads. To do that, I just modified my body tag like so:

<body onload="loadMsg('msgbox');">

The “onload” attribute fires when the page has finished loading, and it will call the loadMsg() function for us, displaying our message boxes as needed. And that’s all there is to it! You can see a functioning example here.

Now, I did want to mention a couple of things before you try this on your own:

  • I’ve built this example specifically to make it work with multiple message boxes. Otherwise, it would have been easier and faster to reference our message box by its ID in our loadMsg() function.
  • This obviously only works if your users have JavaScript and cookies enabled. If they have JavaScript turned off, they won’t see a message box. If they have cookies turned off, they won’t be able to get rid of your message box. And I don’t know of a good way around this usability problem. That’s just the way the cookie crumbles.
  • You could achieve this same functionality in about half the space using a JavaScript framework. I have nothing against frameworks generally, but I do have something against forcing your users to download 50KB+ of JavaScript if you’re only going to use 1KB (or less) of it. For some things, frameworks make sense. For others, it’s better to just write it by hand.

But enough from me… I want to hear what you have to say about this technique. Leave me a comment!