Archive

Archive for the ‘css – cascading stylesheet’ Category

Creating a Keyboard with CSS and jQuery

December 18, 2009 1 comment
Creating a Keyboard with CSS and jQuery

Sometimes it’s just fun to play around with the programming languages we know and see what we can create. I thought it might be nice to create a little online keyboard with CSS, and then make it work with jQuery. The keyboard includes “action” keys (caps lock, shift, and delete) which dynamically changes the keyboard when clicked. I’ll show you how to build it today.


Step 1: Basic HTML and Files

Final Product

This keyboard requires a lot of HTML setup and playing around with CSS. Each of the keys will be represented by a list item in an unordered list. Each of the list items will have a class attached to them, used in both the CSS and jQuery. Most of the classes are just “letter”, “lastitem”, or something similar. This will make finding out which list item is which easy.

Make sure you have setup a folder wherever you are going to be using this keyboard. Inside this new folder, create an index.html file along with a css and a js folder. Finally, create a keyboard.js file in the js folder and a style.css file in the css folder.

Organization of the files

Inside the HTML file we’ll be including two JavaScript files and one CSS file. Inside the body tag there will be a HUGE unordered list containing all the letters, numbers, and some “action” keys. The HTML will also have a textarea in it with an id of “keyboard”. This will be the place where all the characters are added. The below code should be placed inside the index.html file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

	<title>Online Keyboard</title>
	<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>

<div id="container">
	<textarea id="write" rows="6" cols="60"></textarea>
	<ul id="keyboard">
		<li><span>`</span><span>~</span></li>
		<li><span>1</span><span>!</span></li>
		<li><span>2</span><span>@</span></li>
		<li><span>3</span><span>#</span></li>
		<li><span>4</span><span>$</span></li>
		<li><span>5</span><span>%</span></li>
		<li><span>6</span><span>^</span></li>
		<li><span>7</span><span>&amp;</span></li>
		<li><span>8</span><span>*</span></li>
		<li><span>9</span><span>(</span></li>
		<li><span>0</span><span>)</span></li>
		<li><span>-</span><span>_</span></li>
		<li><span>=</span><span>+</span></li>
		<li>delete</li>
		<li>tab</li>
		<li>q</li>
		<li>w</li>
		<li>e</li>
		<li>r</li>
		<li>t</li>
		<li>y</li>
		<li>u</li>
		<li>i</li>
		<li>o</li>
		<li>p</li>
		<li><span>[</span><span>{</span></li>
		<li><span>]</span><span>}</span></li>
		<li><span>\</span><span>|</span></li>
		<li>caps lock</li>
		<li>a</li>
		<li>s</li>
		<li>d</li>
		<li>f</li>
		<li>g</li>
		<li>h</li>
		<li>j</li>
		<li>k</li>
		<li>l</li>
		<li><span>;</span><span>:</span></li>
		<li><span>'</span><span>&quot;</span></li>
		<li>return</li>
		<li>shift</li>
		<li>z</li>
		<li>x</li>
		<li>c</li>
		<li>v</li>
		<li>b</li>
		<li>n</li>
		<li>m</li>
		<li><span>,</span><span>&lt;</span></li>
		<li><span>.</span><span>&gt;</span></li>
		<li><span>/</span><span>?</span></li>
		<li>shift</li>
		<li>&nbsp;</li>
	</ul>
</div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="js/keyboard.js"></script>
</body>
</html>

You won’t have to worry too much about the classes on the list items for now. I’ll explain them more when we’re using jQuery. However, some of the classes (like right-shift and lastitem) are just there because of the CSS we’ll be using.

The HTML before CSS is applied.

Step 2: Making the List Pretty

The JavaScript for the keyboard would work perfectly fine without any CSS, but it wouldn’t look like a keyboard. I’m not going to explain every style because a lot of them are pretty self-explainitory, but there are a couple that I will go over. Save the following CSS in the style.css file located in the css folder.

* {
margin: 0;
padding: 0;
}
body {
font: 71%/1.5 Verdana, Sans-Serif;
background: #eee;
}
#container {
margin: 100px auto;
width: 688px;
}
#write {
margin: 0 0 5px;
padding: 5px;
width: 671px;
height: 200px;
font: 1em/1.5 Verdana, Sans-Serif;
background: #fff;
border: 1px solid #f9f9f9;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
#keyboard {
margin: 0;
padding: 0;
list-style: none;
}
	#keyboard li {
	float: left;
	margin: 0 5px 5px 0;
	width: 40px;
	height: 40px;
	line-height: 40px;
	text-align: center;
	background: #fff;
	border: 1px solid #f9f9f9;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	}
		.capslock, .tab, .left-shift {
		clear: left;
		}
			#keyboard .tab, #keyboard .delete {
			width: 70px;
			}
			#keyboard .capslock {
			width: 80px;
			}
			#keyboard .return {
			width: 77px;
			}
			#keyboard .left-shift {
			width: 95px;
			}
			#keyboard .right-shift {
			width: 109px;
			}
		.lastitem {
		margin-right: 0;
		}
		.uppercase {
		text-transform: uppercase;
		}
		#keyboard .space {
		clear: left;
		width: 681px;
		}
		.on {
		display: none;
		}
		#keyboard li:hover {
		position: relative;
		top: 1px;
		left: 1px;
		border-color: #e5e5e5;
		cursor: pointer;
		}

Take notice of the following styles because they are very important.

  • .on – In some of the list items, there are two spans. These are the keys that have more than one character per key; like the numbers. The span with the on class will be hidden. This changed when a user clicks on the shift key, but more on that later with the JavaScript.
  • .lastitem – The last jey in any row will have its right margin zeroed out so the layout won’t break.
Before and after the CSS is applied.

Step 3: Bringing the Keys to Life

If you were to click on a list item nothing would happen. We’re about to fix that with a little jQuery. The main idea we’ll be using is to attach a click handler to each of the list items, grab the text when clicked, and do some magic to it depending on the list item’s class. From here on out, all the JavaScript code will go into the keyboard.js file.

The Setup

We need to open up jQuery and define three variables that will be used through the code. These variables are the textarea, a shift status, and a caps lock status.

$(function(){
	var $write = $('#write'),
		shift = false,
		capslock = false;

	// The rest of the code goes here.
});

What comes next is attaching the click handler to all the list items (keys). Two variables are setup when the key is clicked. $this is defined just to required less typing from us, and character is defined as the HTML of the list item. If the list item is a letter, nothing will happen to this variable, and it will be returned.

$('#keyboard li').click(function(){
	var $this = $(this),
		character = $this.html(); // If it's a lowercase letter, nothing happens to this variable

	// Code for processing the key.
});

The Shift Key and Caps Lock

If the shift key (list items with the class of “left-shift” or “right-shift”) is clicked, we want to toggle the “uppercase” class of each letter. Then for the list items with a class of “symbol,” we want to toggle the display between the nested span tags. What we want to do next is set shift to the opposite boolean value (if it’s true set it to false, and vice versa), and the caps lock variable to false, and finally return false to not do anything else with the character variable.

// Shift keys
if ($this.hasClass('left-shift') || $this.hasClass('right-shift')) {
	$('.letter').toggleClass('uppercase');
	$('.symbol span').toggle();

	shift = (shift === true) ? false : true;
	capslock = false;
	return false;
}

Now, if the caps lock key is clicked, we will toggle the “uppercase” class on letter list items; set the caps lock variable to true; and return false.

// Caps lock
if ($this.hasClass('capslock')) {
	$('.letter').toggleClass('uppercase');
	capslock = true;
	return false;
}

The Delete Key

For the delete key, we need to assign another variable: html – the contents of what’s currently in the textarea. Once we have that, we set the new HTML of the textarea to everything but the last character. This is done with JavaScript’s substr method. Once again we return false as to not run anything else.

// Delete
if ($this.hasClass('delete')) {
	var html = $write.html();

	$write.html(html.substr(0, html.length - 1));
	return false;
}
The markup behind the delete key.

Special Characters

For all the list items which aren’t a letter and aren’t one of the “actions” keys, we change the character variable to something special. For a list item with the “symbol” class, character is set to the contents of whatever span is visible. A space is (obviously) used for the space bar. The tab character is represented by \t, and finally a new line (the return key) is \n.

// Special characters
if ($this.hasClass('symbol')) character = $('span:visible', $this).html();
if ($this.hasClass('space')) character = ' ';
if ($this.hasClass('tab')) character = "\t";
if ($this.hasClass('return')) character = "\n";
The markup behind the symbol keys.

Uppercase Letters

If you can remember to when we handled the shift and caps lock keys, an “uppercase” class was either added or removed using the toggleClass function. If the uppercase class is found, the character is converted to its uppercase form with the help of the toUpperCase method.

// Uppercase letter
if ($this.hasClass('uppercase')) character = character.toUpperCase();

The Aftermath

On a normal keyboard, you usually only need the shift key for one letter. If the shift variable is found to be set to true, we want to toggle the display of the symbol’s spans. What also happens is that if the caps lock key is “on”, the letters are once again toggled between uppercase and lowercase.

To finish off, the character is added to the textarea and the user can continue “typing”.

// Remove shift once a key is clicked.
if (shift === true) {
	$('.symbol span').toggle();
	if (capslock === false) $('.letter').toggleClass('uppercase');

	shift = false;
}

// Add the character
$write.html($write.html() + character);

Final JavaScript Code

$(function(){
	var $write = $('#write'),
		shift = false,
		capslock = false;

	$('#keyboard li').click(function(){
		var $this = $(this),
			character = $this.html(); // If it's a lowercase letter, nothing happens to this variable

		// Shift keys
		if ($this.hasClass('left-shift') || $this.hasClass('right-shift')) {
			$('.letter').toggleClass('uppercase');
			$('.symbol span').toggle();

			shift = (shift === true) ? false : true;
			capslock = false;
			return false;
		}

		// Caps lock
		if ($this.hasClass('capslock')) {
			$('.letter').toggleClass('uppercase');
			capslock = true;
			return false;
		}

		// Delete
		if ($this.hasClass('delete')) {
			var html = $write.html();

			$write.html(html.substr(0, html.length - 1));
			return false;
		}

		// Special characters
		if ($this.hasClass('symbol')) character = $('span:visible', $this).html();
		if ($this.hasClass('space')) character = ' ';
		if ($this.hasClass('tab')) character = "\t";
		if ($this.hasClass('return')) character = "\n";

		// Uppercase letter
		if ($this.hasClass('uppercase')) character = character.toUpperCase();

		// Remove shift once a key is clicked.
		if (shift === true) {
			$('.symbol span').toggle();
			if (capslock === false) $('.letter').toggleClass('uppercase');

			shift = false;
		}

		// Add the character
		$write.html($write.html() + character);
	});
});
Final Product

Conclusion

Sometimes it’s nice to play around, even if the final product isn’t truly “real world.” By applying a few classes to our list items, we were able to create a CSS and jQuery powered keyboard. The keyboard isn’t totally useless. I’ve seen websites were there’s an option for an on-screen keyboard. But mostly, this allows us to gain a better understanding of the capabilities of CSS and jQuery.

Perfect Full Page Background Image

December 3, 2009 2 comments

We visited this concept of re-sizeable background images before… but reader Doug Shults sent me in a link that uses a really awesome technique that I think is better than any of the previous techniques.

This technique and the above background image is credited to this site. Here is what this technique is going to accomplish:

  • Fills entire page with image, no white space
  • Scales image as needed
  • Retains image proportions
  • Image is centered on page
  • Does not cause scrollbars
  • Cross-browser compatible
  • Isn’t some fancy shenanigans like Flash

This is a very tall order, and we are going to be pulling out all kinds of different stuff to make it happen. First of all, because the image needs to scale, a traditional CSS background-image is already disqualified. That leaves us with an inline image.

Technique #1

This inline image is going to be placed on the page inside of a bunch of wrappers, each necessary for accomplishing all our goals.

<div id="bg">
    <div>
        <table cellspacing="0" cellpadding="0">
            <tr>
                <td>
                    <img src="images/bg.jpg" alt=""/>
                </td>
            </tr>
        </table>
    </div>
</div>

And the CSS:

* {
    margin: 0;
    padding: 0;
}

html, body, #bg, #bg table, #bg td {
    height:100%;
    width:100%;
    overflow:hidden;
}

#bg {
    position: fixed;
}

#bg div {
    height:200%;
    left:-50%;
    position:absolute;
    top:-50%;
    width:200%;
}

#bg td {
    text-align:center;
    vertical-align:middle;
}

#bg img {
    margin:0 auto;
    min-height:50%;
    min-width:50%;
}

That’s quite a little load of markup and CSS, but it does the trick very well! Just doing this alone gets the job done, but what about if we want actual content on the page. Setting that overflow to hidden on the html and body elements should scare you a little bit, as that will totally cut off any content that is below the fold on a site with no scrollbars. In order to bring back scrollable content, we’ll introduce another wrapper. This one will sit on top of the background, be the full width and height of the browser window, and set the overflow back to auto (scrollbars). Then inside of this wrapper we can put content safely.

<div id="cont">
    <div>
          <!-- content in here -->
    </div>
</div>
#cont {
    position:absolute;
    top:0;left:0;
    z-index:70;
    overflow:auto;
}

.box {
    margin: 0 auto;
    width: 400px;
    padding: 50px;
    background: white;
    padding-bottom:100px;
    font: 14px/2.2 Georgia, Serif;
}

JavaScript Fixes

For IE 6, there is some MooTools stuff going on to fix it up

In Firefox, default “focus” is placed on the body element when the page loads. That means that pressing the space bar will scroll down the body, which would reveal some ugly white space. We can use some jQuery for a quick fix, to remove that focus and place it on a hidden element instead, removing that problem:

$(function(){
       $(".box").prepend('<input type="text" id="focus-stealer" type="hidden" />');
       $("#focus-stealer").focus();
});

The addition of fixed positioning on the #bg wrapper eliminated the space bar/scrolldown problem. CSS FTW!

View Demo Download Files

Current Bugs

  • In Safari 4 & Chrome, the min-height isn’t catching and doesn’t resize vertically to fit.

Technique #2

Big thanks, as usual, to Doug Neiner for this alternate version.

Here, we can use CSS with no JavaScript fixes, and the image is just an inline image with a class name of “bg” and no extra markup. That’s a big win for all the folks unhappy about the extra markup.

The only caveat is that it doesn’t quite meet all the requirements layed out about, in that it doesn’t center in IE 7, doesn’t work at all in IE 6, and may not always be proportionate depending on the original image size. BUT, since it’s simpler and bug-free, it’s defenitly a solid option. Here is the CSS:

img.bg {
	/* Set rules to fill background */
	min-height: 100%;
	min-width: 1024px;

	/* Set up proportionate scaling */
	width: 100%;
	height: auto;

	/* Set up positioning */
	position: fixed;
	top: 0;
	left: 0;
}

@media screen and (max-width: 1024px){
	img.bg {
		left: 50%;
		margin-left: -512px; }
}

div#content {
	/* This is the only important rule */
	/* We need our content to show up on top of the background */
	position: relative; 

	/* These have no effect on the functionality */
	width: 500px;
	margin: 0 auto;
	background: #fff;
	padding: 20px;
	font-family: helvetica, arial, sans-serif;
	font-size: 10pt;
	line-height: 16pt;
	-moz-box-shadow: #000 4px 4px 10px;
	-webkit-box-shadow: #000 4px 4px 10px;
}

body {
	/* These rules have no effect on the functionality */
	/* They are for styling only */
	margin: 0;
	padding: 20px 0 0 0;
}

View Demo