My Blog

contains PHP and other web related content. (Sometimes there are some off topic things - don't freak out!)

document.URL vs document.location.href

December 18th, 2009

When reviewing some javascript security ideas, I came across the document.URL property. Turns out that my normal way of retrieving the location (document.location.href) is both a getter and a setter. The document.URL is just a getter.

Check it out with this code:

?View Code JAVASCRIPT
1
2
3
4
alert(document.URL);
alert(document.location.href);
document.URL = 'http://google.com';
document.location.href = 'http://yahoo.com';

The results are simple: you will get the current location twice – and then an error. If you comment out the document.URL line, it will redirect to yahoo.

Protect Your Image from Download

December 16th, 2009

I came across a great idea dealing with protecting image downloads from the site. Now, this is not fool-proof. There are lots of other ways to download the image, but this may stop the casual downloader. Nope, its not disabling the right click or using java. It requires one single transparent gif. Let’s see how.

Read the rest of this entry »

Javascript Snow Fall with buildup

December 6th, 2009

Mr. Skowron (his business) was working on a flash animation for a client that had a snow fall. What really irked me about the end result, was two things.
a) it was in flash
b) the snow didn’t build up

The client was happy. So that’s all good. But, I like a challenge… So I decided to make my own version.

The Snowfall Script

I didn’t want to reinvent the wheel – so I grabbed a pre-made script (by Scott Schiller). It simply adds the snowfall to the body.

Creating a snow line

The next thing I wanted to do was make a snow line that would slowly creep up. My first thought was just to have a standard white swoosh move up. This wouldn’t work because I wanted to have it scale the entire size of the monitor. Plus it wouldn’t look that natural.

I decided to make three images with various swoosh type marks about 500px wide. Then, I used photoshop to offset them by half. (Filter -> Other ->offset -> set horizontal to 1/2 the width of the image). This made the image tile-able. (It may be necessary to smooth out the new overlap you just created). All three were created, 500px wide and 50px tall.

Creating the HTML

The HTML would be pretty simple. I had to have three snow lines – oh and I wanted a tree. Let’s take a look:

1
2
3
4
5
6
7
8
9
10
11
12
<!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" lang="en">
    <head>
        <title>Snow!</title>
    </head>
    <body>
        <div id="tree"></div>
        <div id="snow1" class="snowblock"><div></div></div>
        <div id="snow2" class="snowblock"><div></div></div>
        <div id="snow3" class="snowblock"><div></div></div>
    </body>
</html>

We’ll be referring to these elements a little bit later.

Use CSS to Position Everything

The next thing to do was to give my div’s some dimension and some background images. I thought I’d start out each snow line 50px from the bottom and tile the image. Since they have transparent edges, you should be able to see varying lines of ‘horizon’ on the snow. I also placed the tree image near the right edge to give it that look I was looking for.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
            body {
                height: 100%;
                padding: 0px;
                margin: 0px;
                background: #000;
            }
            #tree {
                background: url('treeback.jpg') no-repeat;
                position: absolute;
                bottom: 10px;
                right: 20px;
                height: 396px;
                width: 530px;
            }
            .snowblock {
                position: absolute;
                bottom: 0px;
                width: 100%;
                background-repeat: repeat-x;
                height: 40px;
            }
            .snowblock div {
                background-color: #fff;
                margin-top: 40px;
                height: 0px;
            }            
            #snow1 {
                background-image: url('snow1.png');
            }
            #snow2 {
                background-image: url('snow2.png');
            }
            #snow3 {
                background-image: url('snow3.png');
            }

First, give the body some background color, get rid of paddings and set a height of 100%. The next section is the tree placement. This is pretty simple.

For each class of snowblock, they are absolutely positioned at the bottom with 100% width. I gave them each 40px height. Each image is 50px tall, but I wanted an acceptable gutter just in case.

As each image moves up, they will start to reveal the background color again. To solve this, the interior divs are given a background color of white. Their top margin is 40px – to offset them enough from the image (so as to not bleed their own background color upwards into the transparent snowline). They start out with no height.

Finally, each image div is given a background image of snow.

The magical javascript

First off, I put the following javascript include tags in the HTML

1
2
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript" src="snowstorm.js"></script>

After loading jquery and the premade script, the following javascript is executed:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        function upSnow()
        {
            var id = 'snow' + (Math.floor(Math.random()*3) + 1);
            var snow = $("#"+id);
            var filler = $("#" + id + " div");
            snow.height(snow.height() + 1);
            filler.height(filler.height() + 1);
        }
 
        $(function(){
            snowStorm.flakesMax = 250;
            snowStorm.flakesMaxActive = 100;
            snowStorm.animationInterval = 33;
            snowStorm.snowStick = false;
            setTimeout(function(){setInterval('upSnow()', 2000)}, 5000);
        });

First, the upSnow() function is generated. This will randomly pick an ID between snow1 and snow3 and inch it up 1px. The child div’s height is also increased by 1 pixel.

When the javascript fires, a few options are set for the snowStorm js library.

Finally, a timeout and an interval are set. The first timeout is used to set the interval. I don’t want the interval to start until the first flakes start hitting the ground. this takes approximately 5 seconds, so that delay is set.

After 5 seconds, the anonymous function fires off the setInterval request to run the upSnow() function every two seconds.

See it in Action

Seems to me, people like to SEE this stuff in action. Weird. Anyway, here ya go:
http://demo.aaronsaray.com/demo/snow/

Auto Failover for CDN based Javascript

November 30th, 2009

Using my javascript error reporter code helps me get a better understanding of what my clients are experiencing when visiting my website. One thing I did notice was the failures from time to time of Google’s CDN based Jquery.

To solve this issue, I decided to keep a local copy as well. For the most part, Google’s version is going to be faster and have a better cache method. However, I’d rather have an uncached version of it loaded into the user’s browser than nothing at all! So, in the very rare case that the user’s browser fails to load the Google javascript, I load a local copy of it.

First Step: Load JQuery From Google

The very first thing I do is to include jQuery from google’s code base using the following tag:

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

This will retrieve the latest version (1.3.2) from Google with the proper compression and cache response I like.

However, this sometimes was failing – well according to my error reporting script. What to do?

Test for a successful load of jQuery

Since the SCRIPT tag does not have an ‘onerror’ standard notifier like our image, the next best thing to do is test for the jQuery object right after the page loads. Since we’re using inline javascript, the first request to the external javascript will block while loading. When it completes, this small snippet will then execute.

I’ll jump ahead one more step though before code.

If no jQuery found, load it dynamically

If the jQuery object is not found, a new script element is created dynamically. The source is pointed to my local version of the script. Finally, it is appended to the head. Hopefully this will load the jquery. If it fails here, well then – the client has some issues!

This is the full inline javascript after the external javascript reference:

?View Code JAVASCRIPT
1
2
3
4
5
6
if (typeof jQuery == 'undefined') {
	var e = document.createElement('script');
	e.src = '/js/noncdn-jquery-1.3.2.js';
	e.type='text/javascript';
	document.getElementsByTagName("head")[0].appendChild(e);
}

In this case, the path http://mydomain.com/js/noncdn-jquery-1.3.2.js contains my local javascript.

The results?

Before this fix, I saw a failed jQuery load about once a day. I have not seen a single one yet. I have yet to see this error reported. If anyone finds a better way to do this, please let me know!

Block and Allow IP with iptables – simple script

November 25th, 2009

As most developers are lazy, I’m a huge fan of scripts. I’ve found myself lately having to add entries to iptables to block a single IP or a small subnet, so I made a quick script to make the job easier on myself.

Usage for both of these is of course really simple. Say 123.1.2.3 is the IP in question:

sudo ./blockip.sh 123.1.2.3
sudo ./allowip.sh 123.1.2.3

blockip.sh
Blocks the IP using iptables

1
2
3
4
5
6
7
#!/bin/bash
 
#blocking iptables
/sbin/iptables -A INPUT -s $1 -j DROP
 
#saving iptables
/sbin/iptables-save > /etc/sysconfig/iptables

allowip.sh
Removes the entry from iptables

1
2
3
4
5
6
7
#!/bin/bash
 
#allowing iptables
/sbin/iptables -D INPUT -s $1 -j DROP
 
#saving iptables
/sbin/iptables-save > /etc/sysconfig/iptables

Printing a small segment of the page using JQuery

November 23rd, 2009

Using Yahoo’s Grid Tools, I created a pretty decent page layout. After all this was complete, I needed to generate a printable version of only a portion of the site. This was a particular set of instructions. I decided to tackle this with JQuery.

The Setup

The page was created with Yahoo’s Grids.
There were 4 sets of instructions on the site.
Each instruction had its own box containing the content – as well as a ‘print this’ link.
Users were liable to click the wrong link – and have to do it again.

The Code

The following is the JQuery I wrote to solve my problem:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
	$(".printinstructions").click(function(){
		$('.instructionalli').remove();
		var box = $(this).parent();
		$("<style type='text/css' media='print'>#bd,#ft,#nav,#hd{display: none}a.printinstructions{display:none}.instructionalli{display:block}</style>").appendTo($('head'));
		$(box).clone().insertAfter($('body')).addClass('instructionalli');
		window.print();
		return false;
	});

This is what the content may have looked like:

1
2
3
4
5
6
7
8
<div>
<a href="#" class="printinstructions">Print These</a>
<ol>
<li>Do Step 1</li>
<li>Do Step 2</li>
</ol>
</div>
<!-- three more of these -->

The Explanation

First, any time a link with the class ‘printinstructions’ is clicked, the function launches. The first line in the function is responsible for undoing this process I’m about to describe. This is necessary just in case someone clicked the ‘print’ button earlier on the wrong element by accident.

The first step is to get the parent container. This is the content that we’re going to make our only printed content.

Next, create a new stylesheet that makes everything “display: none” except for the body itself. The media type is print. Finally, it does make the class “instructionalli” “display: block”. (Note: I could have just as easily attached the page in the source… but I needed to only have this activate if the print button was clicked).

The final step is to clone the box (that is inside of something that is ‘display: none’) and add that after the body content. Then, add the “display: block” class to it. Finally the window.print() method is invoked. For the most part, the user will have no idea any of this happened. The final result is a printed version of the instruction’s box content only.

How I fixed the Javascript error with wp-codebox

November 16th, 2009

I’ve been using the wp-codebox plugin for a while… and an upgrade came today!

Well, I applied the upgrade – and now every page that has a code box on it was causing my JS to crash. The first thing I did was disable the inclusion of the jquery.js file in the plugin by editing the main.php file’s codebox_header() function. Then, I deleted the jquery.js file from the /js folder in the plugin. Finally, I edited js/codebox.js to remove the reference to the old jquery’s noConflict() method. I removed the $jcodebox variable and replaced it with the $ only. Now, all is well.

JfbConsole – chainable Firebug Console jQuery plugin

November 12th, 2009

I find myself wanting to document various different attributes mid development on my jquery code. I have created the following function to help use FireBug’s console access code effectively in the jQuery fashion.

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
 /**
  * JConsoleFB 0.1
  *
  * Jquery plugin for FireBug console integration.  Uses chainable method.  
  * See: http://getfirebug.com/console.html for options
  * @author Aaron Saray (http://aaronsaray.com)
  */
 $(document).ready(function () {
	 if (typeof window.console != 'undefined') {
		 jQuery.fn.log = function(msg) {
			 window.console.log("%s: %o", msg, this);
			 return this;
		 };
		 jQuery.fn.debug = function(msg) {
			 window.console.debug("%s: %o", msg, this);
			 return this;
		 };
		 jQuery.fn.info = function(msg) {
			 window.console.info("%s: %o", msg, this);
			 return this;
		 };
		 jQuery.fn.warn = function(msg) {
			 window.console.warn("%s: %o", msg, this);
			 return this;
		 };
		 jQuery.fn.error = function(msg) {
			 window.console.error("%s: %o", msg, this);
			 return this;
		 };
		 jQuery.fn.assert = function(expression) {
			 window.console.assert(expression, this);
			 return this;
		 };
		 jQuery.fn.dir = function() {
			 window.console.dir(this);
			 return this;
		 };
		 jQuery.fn.dirxml = function() {
			 window.console.dirxml(this);
			 return this;
		 };
		 jQuery.fn.trace = function() {
			 window.console.trace();
			 return this;
		 };
		 jQuery.fn.time = function(name) {
			 window.console.time(name);
			 return this;
		 };
		 jQuery.fn.timeEnd = function(name) {
			 window.console.timeEnd(name);
			 return this;
		 };
		 jQuery.fn.profile = function(title) {
			 window.console.profile(title);
			 return this;
		 };
		 jQuery.fn.profileEnd = function() {
			 window.console.profileEnd();
			 return this;
		 };
	 }
 });

Usage is pretty simple. For example, say I wanted to log something about the current element I’m going to clone. I may do this:

?View Code JAVASCRIPT
1
var newClone = $("#cloneable").log('Cloning this').clone();

This will display a reference to this object as well as the message ‘Cloning this’ in the Firebug console as a log type.

Twitter live search updates page

November 9th, 2009

I decided it would be kind of cool to make a page that combined a bunch of twitter hash tags or just tweets in general. Here are the details…

Read the rest of this entry »

mod_unique_id error after installing mod_security

November 5th, 2009

After installing my mod_security module for apache, I could not restart my apache server. I kept getting the following error:

[alert] (EAI 2)Name or service not known: mod_unique_id: unable to find IPv4 address of "mn-ws"

In this case, mn-ws was the host name of my computer.

This is a pretty simple fix, but I’ll document it anyway. The issue was that my host name was not looking up to my server.

First, I executed the hostname command. This reported back ‘mn-ws’ properly. Then, I tried to ping mn-ws with no reply. I finally put an entry in the /etc/hosts file with the following content:

127.0.0.1 mn-ws

This solved the issue and mod_security would now allow the server to start. Pretty simple.

  • twitter loader

Follow me on twitter: @aaronsaray

The views on this website are my own and do not reflect the opinions of my employer or clients.
Creative Commons License Home | Open Source | Book | Music | Art | Bio | Resume | Contact
My Baby