Archive for the ‘javascript’ Category

Typical Workflow

Monday, August 1st, 2011

1. Create awesome Javascript function.
2. Test in Browser X; function works as desired.
3. Test in Browser Y; function does diddly squat.
4. Call Browser Y names.
5. Question Browser Y’s parentage.
6. Start angry blog post about how Browser Y should be written onto thousands of usb drives and airbombed over enemy countries to destroy their ability to use the Internet.
7. Get distracted from completing blog post while searching Wikipedia for appropriate WWII bomber references to link into post, start WWILFing, and end up obsessing over Jack Churchill after learning about his habit of taking longbows and claymores into battle during WWII.
8. Create generic version of code to insert into blog post to show how Browser Y’s sole purpose for existing is ruining my day.
9. Notice slight issue with code that points to incorrect usage of a function on my part.
10. Fix problem.
11. Discover the code now works as desired on Browser Y just perfectly.
12. Quietly delete blog post while making mental note to reference Jack Churchill later.
13. Wonder how the hell Browser X was operating as desired with incorrect implementation of code.
14. Drink heavily.

Elsewhere: William Flake’s “Of Squirrels and Men”

Tuesday, December 8th, 2009

Last Friday in response to a question by Tyrun I posted a little micro-tutorial about how I achieve the parallax scrolling header for the site, walking through the steps on setting up images, CSS, HTML and JavaScript (in particular, I use jQuery). I also learned a thing or two about how annoying WordPress can be with code snippets in posts (Use <pre>. Really. I don’t know why I didn’t.)

Everything in the tutorial is exactly as it was on my site at the time of writing. However, this is no longer the case. Over the weekend I got a tweet from William Flake indicating a modification he made to the code to prevent a “jump” that occurred when you first moved the mouse into the header. I liked his alterations so much that I’ve made use of them in my code.

This week William wrote about his code alterations over at his site Unfinished Thoughts in a post entitled Of Squirrels and Men. If you enjoyed my parallax code, please take a look at what changes he made. They’re definitely worth a gander.

The Parallax Header: How I Do It

Friday, December 4th, 2009

This morning I was asked by Tyrun on Twitter (sorry, I couldn’t find your actual name, sir) about something that I’ve been asked a few times: I LOVE your header background, how on earth did you do that?

The very short answer is: with JavaScript and CSS.

Of course, that’s not a very satisfying response, so I’ll go ahead and expound a bit more. I did it in three steps. First, creating the right group of images. Secondly, with some simple CSS and HTML. Lastly, with a surprisingly short JS script.

Step 1: The Images

The first step for parallax scrolling, in any application, is having multiple layers of images to scroll at different speeds, with each layer representing another part of the passing landscape. In the case of this site, I’ve got four: clouds, mountains, hills, and forest. By themselves, neither layer looks terribly interesting.

Layer 1: Clouds

clouds

Layer 2: Mountains

mountains

Layer 3: Hills

hills

Layer 4: Forest

forest

They’ll have to be stacked over each other, so in order to be seen through one another they need to have transparency. This is why I used PNGs (although depending on the type of art you use, GIFs are fine).

Step 2: The CSS and HTML

Next, the images will have to be stacked over each other. I made four empty divs which I put in the header/branding div as follows:

<div id="cloudLayer" > </div>
<div id="mountainLayer" > </div>
<div id="hillLayer" > </div>
<div id="forestLayer"> </div>

Although I’m not normally a fan of non-semantic divs, for this special effect I need something to hang the imagery upon. These four divs will be what we need for the CSS:

div#cloudLayer, div#mountainLayer, div#hillLayer, div#forestLayer {
 height:200px;
 position:absolute;
 text-indent:-9999em;
 width:100%;
}

div#cloudLayer {
background:transparent url(images/clouds.png) repeat-x scroll left top;
opacity:0.6;
}

div#mountainLayer {
background:transparent url(images/mountains.png) repeat-x scroll left top;
}

div#hillLayer {
background:transparent url(images/hills.png) repeat-x scroll left top;
}

div#forestLayer {
background:transparent url(images/forest.png) repeat-x scroll left top;
}

So each div is set at the same height, as wide as the parent element (the header), and absolutely positioned so they all overlap. Each background image is set appropriately to repeat horizontally along the layer it is within. If nothing further was done, this would be a complicated way to create a repeating landscape background. Only one small bit is left to make it scroll.

Step 3: The JavaScript (with jQuery!)

I love jQuery. It’s a convenient, compact JS library that makes cross-browser coding easy and compact. You could probably do this script without it, but by necessity it’d be a lot larger. Here’s the part of my script that controls the scrolling:

$('#branding').mousemove(function(e) {
mouseX = e.clientX;
$('#cloudLayer').css('background-position', Math.floor(mouseX / 4) + 'px 0');
$('#mountainLayer').css('background-position', Math.floor(mouseX / 3) + 'px 0');
$('#hillLayer').css('background-position', Math.floor(mouseX / 2) + 'px 0');
$('#forestLayer').css('background-position', mouseX + 'px 0');
});

I want the scrolling to only occur when the mouse is over the header, which is a div I call branding. So I’ve bound the .mousemove() event handling function to that div. I get the x-coordinate of the mouse when that even fires (anytime the mouse moves) and then adjust the background image positioning on the layer divs accordingly.

If I moved each layer’s background image by the same amount, the image would scroll all at once, and there’d be no parallax effect. Therefore, I instead divide the x-coordinate by a different amount for three of the four layers, moving each background image an increasingly smaller amount for the “far” layers.

The finished result is visible in the header above!

As always, if you have any comments or questions, feel free to share.

Javascript Looping Object Instance’s Method Problem

Wednesday, June 3rd, 2009

Time to expose some of my JavaScript weaknesses.

I’m working on a side-project that has multiple instances of the same object (or the equivalent in JS) that makes use of jQuery’s .animate function. At the end of the animate function I want to use .animate‘s callback function option to loop the function in each object (allowing each to loop through a frame-by-frame animation of its own, for example).

The problem is I’m running into an obstacle, which can be illustrated by this simplified looping example. In this particular case, when you click on the button, it creates an instance of the object, sets a value inside it, then calls an internal function which displays an alert box, then calls a (in this case pointless) jQuery .animate function which contains a callback function to loop the instance’s function. The idea would be that I can call multiple instances of the object, and have each assigned their own values and then they’ll loop happily on their own.

That’s not happening, of course.

If you examine the JS source code (linked here) you’ll see that I use function(){this:greet();} as my callback parameter. My understanding was that this would correctly relaunch the function of the instance. It does not, however, work as I desire (aka, at all).

I know that this is an odd thing, so I’m sure I’m hamfistedly trying to pound a square peg in a round hole. The trouble is that I have absolutely no clue what the round peg is.

What I really need is a Master Po to tell me where I’m going horribly wrong here. Can anyone be my blind kung fu mentor?

Correcting Overlay Issues with jQuery Lightbox and Fixed Body Width

Friday, April 24th, 2009

This is a quicky.

As plenty know, Lightbox is a convenient and quick solution to providing a slightly glossy gallery effect for a page of photos or artwork. I personally prefer jQuery Lightbox, mainly because I’m a jQuery addict, but there is a slight issue with it being used in sites that have a fixed width on the body element (which I try not to do myself, since who knows what the end-users monitor is going to be like, but for client sites  I don’t always have that freedom).

The issue is illustrated in this example here: the dark-background overlay that appears to cover the page doesn’t go past the margin of the body, leaving distracting bright gutters that ruin the desired effect.

In cases where you need (for whatever reason) a fixed body width, the solution here for jQuery Lightbox is fairly straightforward, but involves a wee bit of modification to the jquery.lightbox.js file’s code.

Inside the file, find the _set_interface() function and look for this segment of code:

            $('#jquery-overlay').css({
                backgroundColor:    settings.overlayBgColor,
                opacity:            settings.overlayOpacity,
                width:                arrPageSizes[0],
                height:                arrPageSizes[1]
            }).fadeIn();

We need to change it to the following:

            $('#jquery-overlay').css({
                backgroundColor: settings.overlayBgColor,
                opacity: settings.overlayOpacity,
                width: $(window).width(),
                height: arrPageSizes[1],
                left: -(($(window).width() - $('body').width()) / 2)
            }).fadeIn();

Why is this? Let’s focus on the changes.

The width has been changed to $(window).width() so it actually gets the width of the browser window, and not just the body element, across all browsers (the provided value only provides the body element width in IE, Webkit, and Opera). Without this, the overlay won’t get wide enough to cover everything up.

The new value, left, gives the css style that will position the overleft to the left side of the screen by subtracting the difference of the browser’s width and the body’s width. This will allow it to work for all browser sizes.

Lastly, we need to put overflow: visible on the body element in our CSS. With this, we can see the overlay when it goes outside the body’s borders.

With these tiny changes in effect, check out the new result here. Much better, isn’t it?