Posts Tagged ‘javascript’

How clean is your window (object)?

I recently wanted to see how polluted the global namespace of our web application was. By that, I mean I wanted to see how many unnecessary objects we were assigning to the window object.

To do this, I wanted to compare against a clean window object. A quick look on Google and I found this article: Getting a clean document or window Object in JavaScript. The basic idea is that you create a new iframe element, and you can use the contentWindow property of that to give you a nice clean window object. As the author states, you might want to do this to prevent the remapping of native methods but I just want it for a quick (i.e. hacky) way to see what objects have being put into my own ‘clean’ window.

What I do is create the iframe to get my clean window. Set up an object to copy across the objects from the main window object, then remove any that appear in the clean window.

Here it is in glorious, unminified code:

(function(window){
	var keys = {},
	cleanWindow,
	iframe = document.createElement("iframe");

	iframe.style.display ="none";
	iframe = document.body.appendChild(iframe);

	cleanWindow = iframe.contentWindow;
	document.body.removeChild(iframe);

	for(var keyName in window){
		keys[keyName] = window[keyName];
	}

	for(var keyName in cleanWindow) {
		delete keys[keyName]
	}

	return keys;
}(window))

And here’s a version that I’ve minified down:

(function($){var k={},w,d=document,b=d.body,i=d.createElement("iframe");i.style.display="none";i=b.appendChild(i);w=i.contentWindow;b.removeChild(i);for(var s in $){k[s]=$[s]}for(var s in w){delete k[s]}return k}(window))

This is written as self executing JavaScript and will return an object containing the objects that we worked out were added to the window.

Note: This is a very quick and dirty piece of code. Mostly it was an experiment for myself, to use the ‘clean window’ object. It won’t tell you if a native window property was changed or anything, it only compares the keys. Just remember that.

Looking at the animations on Google’s Jim Henson doodle

On opening Google today, I’m shown a couple of muppets I can control (well, I can open their mouths and spin their heads around). This is to celebrate Jim Henson’s 75th birthday, but I’m interested in what makes it tick since there are a few little animations in there and I want to see what Google does.

Google Doodle for Jim Henson's 75th Birthday

Looking at the images that are loaded, they seem to be PNG sprite images. So then I went on a little (short lived) mission on how to recreate the animations myself. Honestly, there are muppet animations you can play with soon.

There is a handy little jQuery plugin called Spritely. This will take a jQuery selector object and manipulate the background image position to generate the animation. Nicely, all you have to do is supply the number of frames and it will do the rest for you.

So I open up a new jsFiddle, fill in my HTML and CSS with the containers and background images I want and then put in this little beauty:

$('div').click(function() {
    var $this = $(this);
    $this.sprite({
        fps: 9,
        no_of_frames: $this.data("num"),
        on_last_frame: function(obj) {
            obj.destroy();
        }
    });
});

Now, what I’ve done here is make it so that every div object will generate a sprite animation on click. This probably isn’t the prettiest way to do it, but I have *only* just discovered Spritely so I’ll look at the docs and improve. If you want to let me know in the comments, that’d be appreciated.

(Also, for the eagle eyed of you, I’m using a data attribute to store the number of frames in the animation. This was painstakingly done by opening the PNG files and counting the muppet heads. I bet I will find Spritely would do it for me after reviewing the documentation).

You’ve waited long enough. Go to the jsFiddle to play with the Muppet animations.

Alternatively, here are links to the sprite images I’ve seen. Haven’t found anything for the blue guy on the left though! If you have, let me know and I’ll add it.

JavaScript – e.preventDefault() is NOT return false

I’ve seen a lot of people use return false in place of e.preventDefault. This is usually when dealing with setting the click event on a hyperlink. I can only think that this comes from the original JavaScript snippets of running code on a click by setting onclick="alert('hi'); return false".

This is wrong

Well – it might be wrong. It all depends on your application. As long as you know the differences in them, you should be fine:

  • e.preventDefault: this (aptly) prevents the default event from happening. In the case of a hyperlink that you want to assign JavaScript to, this will stop the link from going to the location of the link
  • e.stopPropagation: this stops the event from bubbling up. If you click on something that had a click event then using this will stop the event bubbling up and any click event that the parent containers might have.
  • return false: this is the same as calling both of the methods above.

I’ve done two examples for this:

  1. Showing the difference in e.preventDefault() and return false: This example works on the click event and shows that preventDefault and return false are actually different.
  2. Example of e.stopPropagation: This example shows a practical example of when you’d want to stop an event bubbling up. It uses event handlers on the mouseover event to show this.

Preventing accidental double clicks on links using jQuery

I recently answered this question on StackOverflow asking how to prevent someone from clicking a link multiple times.

This is the solution I came up with:

$("a").click(function(e) {
    e.preventDefault();

    if (!$(this).data('isClicked')) {
        var link = $(this);

        // Your code on successful click

        // Set the isClicked value and set a timer to reset in 3s
        link.data('isClicked', true);
        setTimeout(function() {
            link.removeData('isClicked')
        }, 3000);
    } else {
        // Anything you want to say 'Bad user!'
    }
});

You can use jQuery’s data storage methods to assign arbitrary bits of data to specific DOM elements. In this case, when the user clicks a link I assign a property to the element as well as setting a timer to remove it 3 seconds later. This lets me know if the specific element has already been clicked by just calling the data method.

It’s not a bullet proof solution since it’s incredibly easy to get around if you’re determined enough. However, it is a simple example of how you can use those methods.

Shortcut for JavaScript timestamp

JavaScript’s Date object provides a function for getting the milliseconds from the UNIX epoch – getTime():

var timeStamp = new Date().getTime();

However, there is a handy shortcut that gets the same thing:

var timeStamp = +new Date();

It makes me wonder if the +new shortcut can work for any other JavaScript object but I haven’t had a chance to look yet.

Update: Apparently it’s just the unary operator (http://xkr.us/articles/javascript/unary-add/). From the article:

The unary + operator, when used on types other than string, will internally attempt to call valueOf() or toString() (in that order) and then attempt to convert the result to a number. Thusly, the unary + operator can successfully convert many of the native JS types with certain restrictions.