Reverse Parallax Effect

Getting started…

This demo requires the use of javascript so please consider your users before implementing this in a professional setting. I haven’t included any graceful degradation, please have a backup plan if the parallax effect is required.

First…

We need to setup a page structure:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head> 
 
Parallax Background with Javascript and CSS 





</head> 
<body id='background'> 
    
<h1>Parallax Background</h1>

Written by Mike Newell

<h2>Scroll left and right to see the effect</h2>
</body> </html>

This page structure is simple. We include the jquery library from google so users will most likely already have it cached in their browsers. Then we include the stylesheet that will load background images. Finally, we setup a page with some elements inside a container. We’ll write in a script that will grab these elements and make them mobile in the last portion of this tutorial.

Next…

We’ll include a css file to provide a psuedo parallax effect with two background images.

/* 
    Document   : style
    Created on : Apr 3, 2011, 8:28:49 PM
    Author     : Mike Newell
    Description:
        Parallax effect with css background images and elements.
*/
body {
	background-color: white;
	margin: 0;
	padding: 0;
	font-family: "Trebuchet MS", Verdana, Helvetica, Arial, sans-serif;
        background-image: url(../images/bg.gif);
	background-repeat: repeat;
	background-attachment: fixed;
}
#parallax {
	background-image: url(../images/midground.png);
	background-repeat: repeat;
	background-attachment: fixed;
	padding: 5em 0;
        height: 900px;
}
* html #parallax {
	/* because IE6 can't do transparent PNGs for backgrounds */
	background-image: url(../images/midground.png);	
}

#wrap {
    width: 3000px;
}

#content {
    padding: 20px;
    z-index: 999;
    background: black;
    -moz-opacity:0.5;
    opacity: 0.5;
    color: white;
    -moz-border-radius: 250px;
    border-radius: 250px;
    width: 350px;
    height: 260px;
    top: 50%;
    margin-top: -150px;
    position: fixed;
    left: 50%;
    margin-left: -150px;
    padding-top: 90px;
    text-align: center;
}

/*
    GENTEST
*/
.mover {
    z-index: 998;
    background: greenyellow;
    color: white;
    -moz-border-radius: 100px;
    border-radius: 100px;
    position: absolute;
    text-align: center;
}

The base background image is loaded on the body and scrolls with the user scroll on the page. The second background image is a png and overlays the body. This image is loaded in the page #wrap div and moves a bit faster than the underlayer, giving the impression of a parallax. We also style a top layer in a circular div to have some text on the page.

Finally…

We write out a script to grab all the elements with a class of “genTest”.

/*
 *  Written By: Mike Newell
 *  Mike@iwearshorts.com
 *  http://iwearshorts.com/
 *  
 *  No license - Feel free to copy.
 *  
 */
$(window).load(function () {

    var layers = $('.mover').get();
    var layersCount = layers.length;
    var master = [];
    for(var i = 0; i < layersCount; i++) {
       master[i] = {
           speed : 1 - (i / layersCount),
           pos : $(layers[i]).position()
       }

    }

    var top;
    var left;
    var winWidth;
    var docWidth;
    var winHeight;
    var percentLeft;
    var percentTop;
    var absPercent;

    winHeight = $(window).height();
    winWidth = $(window).width();
    docWidth = $(document).width();
    absPercent = (winWidth / docWidth);

   $(window).scroll(function () {

       top = $(this).scrollTop();
       left = $(this).scrollLeft();

       for(var t = 0; t < layersCount; t++) {
           percentLeft = (left / winWidth) * master[t].speed;
           percentTop = (top / winHeight) * master[t].speed;

           var newPositionLeft = master[t].pos.left - (percentLeft * master[t].pos.left);
           var newPositionTop = master[t].pos.top - (percentTop * master[t].pos.top);


           $(layers[t]).css({"left":newPositionLeft, "top":newPositionTop});

       }
   }); 
});

This script grabs all the elements in order and designates a "speed" for each element. Then moves each element according to a percentage based off that speed and the user scroll amount. I deliberately programmed it this way in order to allow user scrolling with mouse wheels and two finger scrolling for mac users. It also works on smartphones, #mobile.

View the Demo. Download the Source.

Inspiration...

Recently I've been building a parallax style website inspired by the lallapalooza site. I had to develop my own little script to move elements based dynamically on how many elements on the page there are. Since we don't have content yet, I won't be able to hard code anything so elements with a certain class must be dynamically included.

Simple HTML DOM PHP

For those of us who wonder about things like whether or not there is a dom manipulation library that could easily select elements from a page captured from a cURL script with jQuery style selectors…

Simple HTML DOM Library.

I needed this for a project recently where I had to grab dynamic elements from other sites and then capture only bits and pieces from the pages. This library saved my life. If you’re interested, check out the project here.

Business Cards for SXSW

For SXSW I wanted to do something memorable with my business cards, something that would separate me from my peers and entice potential employers to actually visit my website!

The plan…

A bunch of students here at BDW decided to go analog and create business cards by hand using an old printing press. I began documenting the process of creating a business card and came up with the idea to film every business card I made and have a custom video produced for each business card. That was people could go to my website and see their individual business card being made.

The process only lasted for about 16 cards before I got bored and stopped filming. But I did manage to produce 16 videos! Below is a list of links to each individual business card! If your a recruiter, please check out the rest of my site while your here!

  • http://iwearshorts.com/business-cards/business-card-16/
  • http://iwearshorts.com/business-cards/business-card-15/
  • http://iwearshorts.com/business-cards/business-card-14/
  • http://iwearshorts.com/business-cards/business-card-13/
  • http://iwearshorts.com/business-cards/business-card-12/
  • http://iwearshorts.com/business-cards/business-card-11/
  • http://iwearshorts.com/business-cards/business-card-10/
  • http://iwearshorts.com/business-cards/business-card-9/
  • http://iwearshorts.com/business-cards/business-card-8/
  • http://iwearshorts.com/business-cards/business-card-7/
  • http://iwearshorts.com/business-cards/business-card-6/
  • http://iwearshorts.com/business-cards/business-card-5/

Red Dirt Collective

The Project:

Boulder Digital Works is teaming up with Nile Southern and Open Road media to revive Terry Southern’s career. We initially intended to build an interactive environment online where users could weigh in on how Terry has affected their lives, give commentary and submit Terry-inspired content. However, as most things do, plans have changed and we’ve taken a new direction with the Terry Southern brand. This site is due for an upgrade and was intended to be the first iteration of the interactive environment.

The Tech:

PHP, HTML5, CSS, JS. We also used Facebook comments and like buttons.

My Role:

Developer/Project Lead

A semi-working version currently exists here.

DIY Parking Sensor Tutorial

The last time I was home visiting my parents I noticed bumper imprints caused by my mother suburban on the stairs leading up from the garage. Their garage it turns out is just barely long enough to fit their gigantic vehicles. So I decided it would be nice to have some visual cue for parking. Out came the arduino and a sonar range finder from Radio Shack and the result was this tutorial.

Materials…

  • Arduino (I had a duemilanove available)
  • Ultrasonic Range Finder
  • Wire
  • Small box
  • 9V power supply (You can find old power supplies for cheap at thrift stores)
  • Tri Color LED
  • Hot Glue Gun
  • Breadboard

Assembly…

  1. Hot glue the arduino to the bottom of the box and run the power supple to it
  2. Connect the 5V and Ground wires to the range finder.
  3. Connect the Pulse cable from the range finder to a “PWM” input on the arduino (this is necessary because we’ll be sending pulses through the same leed that we listen for a return on). I used digital pin 7 with PWM for the pulse connection.
  4. Test the tri color LED to find out which connectors make which colors. You will need to keep track of which wire creates which colors and connect them to three digital pins on the arduino. Keep track of the pin numbers. For instance, I connected to digital pins 11, 12 and 13 with red, green and blue respectively.
  5. Once you have everything connected we’ll start writing the program. After your finished with the programming and you’re sure it works, it’s a good idea to seal everything up in the box to make sure none of the wires get disconnected before you mount the sensor to your wall.

Programming…

Luckily, Arduino already provides an example of how to use the pulse sonar sensor. Select the File -> Examples -> Sensors -> Ping example in the Arduino programming kit. Once open, select the code and copy it to a blank sketch. Save the new project under sketches I used the name “parking Example”.

Now we have something to work with. Begin customizing the code. First, we are only going to be measuring inches, not cm so lets comment out the code snippet about halfway down that runs a function to calculate cm. Comment out:

//cm = microsecondsToCentimeters(duration);

Next we don’t need to send sonar pings out at such a high interval. We only need to ping about every second because the car will (hopefully) be moving slowly into the garage. So at the bottom of the loop function set the delay to 1000:

delay(1000);

Next we need to tell arduino which pins we’ll be using for our LED output. At the top where we have:

const int pingPin = 7;

We’ll add:

pinMode(13, OUTPUT); // blue
pinMode(12, OUTPUT); // green
pinMode(11, OUTPUT); // red

Now that ardiuno has a setup for those pins, we’ll need to send a signal whenever we want that color to show. So After receiving the signal from our ping, we’ll compute the distance and if it falls within certain ranges we’ll show a specific color. I want the driver to see green until they get within 24 inches of the wall, at that point, I want the light to turn blue, signaling that they are getting closer. Then when they are within 6 inches of the wall, the red light should turn on, indicating to the driver that they should stop.

Include the following code below the inches distance calculation:

inches = microsecondsToInches(duration);
// show LED colors
  if(inches > 0 && inches <= 6) {
    // show red, all other leds are off
    digitalWrite(13, LOW);
    digitalWrite(12, LOW);
    digitalWrite(11, HIGH);
  } else if(inches <= 24 && inches > 6) {
    // show blue, all other leds are off
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(13, HIGH);
  } else {
    // show green led, all other leds are off
    digitalWrite(13, LOW);
    digitalWrite(11, LOW);
    digitalWrite(12, HIGH);
  }

This code tells arduino to send a signal to a specific pin when an object comes within a certain distance. The entire script should look like:

/* Ping))) Sensor
  
   This sketch reads a PING))) ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse 
   to return.  The length of the returning pulse is proportional to 
   the distance of the object from the sensor.
     
   The circuit:
	* +V connection of the PING))) attached to +5V
	* GND connection of the PING))) attached to ground
	* SIG connection of the PING))) attached to digital pin 7

   http://www.arduino.cc/en/Tutorial/Ping
   
   created 3 Nov 2008
   by David A. Mellis
   modified 30 Jun 2009
   by Tom Igoe
 
   This example code is in the public domain.

 */

// this constant won't change.  It's the pin number
// of the sensor's output:
pinMode(13, OUTPUT); // blue
pinMode(12, OUTPUT); // green
pinMode(11, OUTPUT); // red
const int pingPin = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{
  // establish variables for duration of the ping, 
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  // show LED colors
  if(inches > 0 && inches <= 6) {
    // show red, all other leds are off
    digitalWrite(13, LOW);
    digitalWrite(12, LOW);
    digitalWrite(11, HIGH);
  } else if(inches <= 24 && inches > 6) {
    // show blue, all other leds are off
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(13, HIGH);
  } else {
    // show green led, all other leds are off
    digitalWrite(13, LOW);
    digitalWrite(11, LOW);
    digitalWrite(12, HIGH);
  }
  //cm = microsecondsToCentimeters(duration);
  
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  
  delay(1000);
}

long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

All that’s needed after that is upload the code to your arduino, mount the device to the front wall of your garage and hang the led somewhere where the driver can see it! Let me know how these instructions work for you. I can always adjust this tutorial later.

Upgrading WordPress Breaks All My Links!

Recently, I wrote about moving a wordpress blog from one domain to another. Whilst transferring my girlfriends blog to another domain I noticed her blog was out of date. So I decided to update to wordpress 3.1 before I moved it. Bad choice, a simple rule to making changes in programming is this, “Make one change at a time and test after each change.” This rule of thumb helps establish a line of credibility and allows the programmer to know what change broke the code. In this case, not only did I transfer to a new domain, I also updated wordpress and had no way of knowing which change broke my website.

I went on a bit of a tangent, but basically when I finished the transfer none of the links on my girlfriend’s site worked. I couldn’t figure it out and spent close to 8 hours today troubleshooting her site. After running a simulation of transferring an older version of wordpress I realized the problem was caused by updating to wordpress 3.1.

This led me to investigate if anyone else had similar problems. It turns out there are a whole slew of problems associated with wordpress 3.1 and permalinks. Here are some common fixes:

  1. Refresh the wordpress permalinks. Simply navigate to “permalinks” under “Settings” and click the save button. Make sure WordPress is updating your .htaccess file properly.
  2. Make sure the problem links aren’t hard coded into the template you’re updating.
  3. (This fix solved my problem) Update all your plugins! I had a plugin called Simple Tags installed on the site and that was causing the .htaccess to act a bit funky. If you upgrade, make sure all your plugins are up to date, if there is no update for them, make sure you individually test each plugin by deactivating it.

That’s if for now, just remember to update all your shit before you start hardcore troubleshooting!

Moving a WordPress Blog to a New Domain

I’ve had to move many WordPress blogs from one domain to the next. As a result, this process has become fairly┬árepetitious. So I thought I would share my experience. First, some disclaimers.

  1. If you don’t know what your doing, it might make sense to pay someone else to move your blog…
  2. If you’ve never run an SQL query, this tutuorial probably isn’t for you. However, if your still feeling adventurous try it out!
  3. You will need FTP access, phpMyAdmin or some other SQL client access, and you may need root or WHM access if you run a VPS.
  4. If you have hardcoded any urls into your themes you will need to manually change these urls to match the new domain.

Getting started…

Our goal is to move the site to a new domain first. Once we’re sure the site is up and running on the new domain, we can safely redirect the old domain to the new one. Make sure you have access to the name servers of both your domains. If you’re using godaddy to purchase your domains you should be able to configure this under “Domains” -> “Domain Management” -> “Domain Manager”. We’ll talk more about this in the next step. For now, just make sure you have:

  1. FTP client (filezilla)
  2. Live site editor (Coda)
  3. Access to your hosting account
  4. Domain management tool and
  5. Sql client

Setup…

Let’s say you just bought the new domain you wish to host the wordpress site on. Let’s also say you’re using Godaddy to register domains (domain registrar). In my case, I have a Virtual Private Server that I host my sites with and I register all my sites with godaddy, so I usually point my domains at my hosting and then set up a package for each one. If you have no idea what I just said, don’t worry. Keep reading…

  1. The first thing I want to do is point my domain to the proper hosting account (if you are hosting with godaddy skip this step). I do this by going to Domains -> Domain Management ->Domain Manager -> new-domain.com and click on “set nameservers”. Point your name server to wherever you’re hosting your sites (usually ns1.yourhostingdomain.com and ns2.yourhostingdomain.com).
  2. Make sure you have a package and account setup to receive incoming requests from that domain. This is done by setting up a new package and account on your hosting server. It’s beyond the scope of this tutorial for me to tell you how to do this, but I can tell you that you will need to have this completed before your server will receive and act on requests coming from your new domain.
  3. Double check that your current domain is working properly and the site is behaving as normal.

Download the Original Site…

You will begin by opening up your ftp client and downloading your wordpress installation at your old domain. Double check that there are no failed file transfers. Once the download is complete, make sure you keep these files. This is your site backup.

You will also make an sql dump of your old domain. Do this by going into the back of phpMyAdmin or any sql client, click on the database your wish to download and click “export.” Make sure you have the settings shown in the image below and then click “Go”.

Save the downloaded zipped file to your computer and move to the next step.

Upload to the New Domain…

Now that your have downloaded your entire wordpress installation and the database associated with your site, you need to upload it all to the new domain. If you are hosting with godaddy, it should create a directory for the root of your domain. If you want your blog to appear when you type in “domain.com” then this is where you would upload you wordpress installation. If you want your blog to appear at “domain.com/blog” then you would create a folder in your root directory and name it “blog” then upload the entire wordpress installation to /blog.

Once your are finished uploading the wordpress site to the proper hosting directory you need to add the SQL Database. Create a new database on your new domain hosting account and navigate in you SQL client to that database. Click “Import” and upload your zipped sql file.

You should see a green box appear indicating a successful upload. Now you need to enter some SQL commands to change the database to operate with the new domain name. navigate to your SQL tab and begin entering:

UPDATE wp_options SET option_value = replace(option_value, 'http://old-domain.com', 'http://new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl';

Then enter:

UPDATE wp_posts SET guid = replace(guid, 'http://old-domain.com','http://new-domain.com');

Then enter:

UPDATE wp_posts SET post_content = replace(post_content, 'http://old-domain.com', 'http://new-domain.com');

Doing this ensures wordpress knows it’s on the new domain and won’t make links and such reminiscent of the old domain. Now we just have one more step to go!

Change wp-config.php…

So far, we’ve uploaded the wordpress site on the old domain to the new one. We’ve updated our sql to reflect the new domain name and we’ve double check to make sure our old site is still working just fine. Now we just need to hook it all together.

Open up your favorite live site editor (I prefer coda but you can use anything you like, notepad++ is a great editor if you are on a Windows machine). Connect to your new domain and navigate to your wordpress installation root. There your should find a file called wp-config.php, open it. Scroll down and enter in the new Database connection information. This will allow the new wordpress installation to connect to the new database.

Once you’ve edited the wp-config.php file. Save it and navigate to your new domain in your browser! You should see an exact replica of your old site on your new domain! Start clicking some links real quick and make sure everything is working correctly.

Groove Shark Widget Trouble

For everyone out there who has had trouble getting their playlists to be recognized when they login to the grooveshark widget platform here: http://widgets.grooveshark.com/my_widgets

The problem seems to be something where Grooveshark can’t pull in your account information associated with any past widget IDs. However, if your widget is still playing on your website you in luck!

Requirements:

Make sure you have firefox or some other browser with an html inspector. If you don’t, this tutorial probably isn’t for you.

What to do…

Go to your web page where you embedded the widget. Inspect the element containing the flash object. Look at the actual embed code and find the variable that says “widgetID=” this is your widget ID stored somewhere on the Grooveshark servers. It’s also the key to your widget. Now that Grooveshark has lost track of you widget, you need to manually tell it where to find it. You will use your widgetID to find it.

Now that you have the widgetID copied somewhere safe, let go back to our widget editor and find our widget!

Navigate to the widget editor page, and click on the “Make a New Widget button.” Once the page loads and you are in the widget editor click “Next Step” since we don’t actually care what the style (it will change once we load in your old widget).

Once the page loads again, you will notice the URL has a space for “?widgetid=0”.

This is where we want to enter in our old widget ID. Simply replace the “0” with your widgetID. Hit enter after you have copied in your widgetID and whablam! Your old widget appears before your eyes. At this point the editor will work on your widget and you can edit and re-save you widget. You account will probably not find this widget so you may have to manually enter your widget ID every time. But if it works it works!

Thanks for checking in!

jQuery Flashlight

It’s simple really…

The text is black and the background is black, so you can’t see the text, it looks blank. However, when you hover your mouse over the page, a background image with a color of white follows your mouse, giving the illusion of a flashlight on the page!

Simply make an html page like this. Then give the page or a block a black background.

			#black {
				background-color: black;
			}

Then give the element a background image, with the flashlight.jpg file.

			#black {
				background-color: black;
				background-image: url(http://iwearshorts.com/flashlight/images/flashlight.jpg);
				background-repeat: no-repeat;
				cursor: crosshair;
			}

That’s it! The jQuery just makes sure to track the mouse and move the background image along with it, this gives users the illusion that a flashlight is being shown over the text.

			jQuery(document).ready(function() {
				jQuery("#black").mousemove(function(e){
					jQuery("#black").css('background-position',(e.pageX - 250)+'px '+(e.pageY - 250)+'px');
				});
			});

View the Demo.

Goo.gl URL Shortener

Here’s a simple class for URL shortening using Google’s new URL API:

<?php

class GUrl {
	$api_url = "https://www.googleapis.com/urlshortener/v1/url?key=";
	$key;
	
	function __construct ($key = "YOUR_API_KEY") {
		// set up the API key if it exists
		$this->key = $key;
	}
	
	public function shortenUrl ($url) {
		curl_init();
		// concatenate the API url
		curl_setopt($ch,CURLOPT_URL,$this->api_url . $this->key);
		curl_setopt($ch,CURLOPT_POST,1);
		// send the json ecoded long version of the url
		curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
		curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		// execute
		$result = curl_exec($ch);
		// close
		curl_close($ch);
		// return the result
		return ($result['id'] = json_decode($result,true)) ? $result['id'] : false;
	}
}

?>

That’s it! Just one function to have cURL send Google the URL to be shortened and it should return a response with the shortened version contained within the parameter [‘id’]. The great thing about using google for this is later we can build a class to retrieve periodic analytics on these urls and see which links are performing well.