JavaScript

How to Retrieve a Zipcode Using JavaScript

Posted in JSON, JavaScript on February 25th, 2010 by Navarr – View Comments
// Retrieve user’s Zipcode
// Demo at http://sandbox.gtaero.net/zipcode.html
function retrieve_zip(callback)
{
	try { if(!google) { google = 0; } } catch(err) { google = 0; } // Stupid Exceptions
	if(navigator.geolocation) // FireFox/HTML5 GeoLocation
	{
		navigator.geolocation.getCurrentPosition(function(position)
		{
			zip_from_latlng(position.coords.latitude,position.coords.longitude,callback);
		});
	}
	else if(google && google.gears) // Google Gears GeoLocation
	{
		var geloc = google.gears.factory.create('beta.geolocation');
		geloc.getPermission();
		geloc.getCurrentPosition(function(position)
		{
			zip_from_latlng(position.latitude,position.longitude,callback);
		},function(err){});
	}
}
function zip_from_latlng(latitude,longitude,callback)
{
	// Setup the Script using Geonames.org's WebService
		var script = document.createElement("script");
		script.src = "http://ws.geonames.org/findNearbyPostalCodesJSON?lat=" + latitude + "&lng=" + longitude + "&callback=" + callback;
	// Run the Script
		document.getElementsByTagName("head")[0].appendChild(script);
}
function example_callback(json)
{
	// Now we have the data!  If you want to just assume it's the 'closest' zipcode, we have that below:
	zip = json.postalCodes[0].postalCode;
	country = json.postalCodes[0].countryCode;
	state = json.postalCodes[0].adminName1;
	county = json.postalCodes[0].adminName2;
	place = json.postalCodes[0].placeName;
	alert(zip);
}
retrieve_zip("example_callback"); // Alert the User's Zipcode

A Quick Update to Simple Twitter

Posted in SimpleTwitter on January 26th, 2010 by Navarr – View Comments

A lot of people use my Simple Twitter Feed written in JavaScript (for some reason).  Well, today I pushed out a quick update that should fix all the woes users have given me in the past.

The code should now be valid XHTML strict, and I know longer use innerHTML for each list element.  Instead, I’ve moved from adding the list elements via innerHTML to DOM Manipulation (appendChild).  I’m not sure exactly what the benefits of this are, but I’m sure they exist.

As the previous HTML code seems to have been broken, this may cause some rendering errors for a few websites, but all in all it should work better than it has previously.

I’m not writing out a whole changelog, I’m just going ahead and saying that some changes were made – and hopefully Simple Twitter should work a lot easier for everyone using it.

Webkit JavaScript Notifications API

Posted in Google Chrome, JavaScript on January 25th, 2010 by Navarr – View Comments

Something I learned about recently by following the updates being issued to Chrome, is that with today’s release they also pushed out the Webkit Notifications API to Chrome Stable (v4).  Surprisingly, this is actually the first I’ve heard of it’s existence.  I took a look and played around with it a bit, and it is qué cool.

Visit my Sandbox to see the code in action, or continue reading for some code excerpts.

read more »

Never Again (External JavaScript in the Body)

Posted in JavaScript on January 12th, 2010 by Navarr – View Comments

This is probably simply a personal taste, but I hate putting External JavaScript tags in the body of a web page.  It feels and looks very unsightly to me.  But as I learn more and more JavaScript, and really start to get a feel for the small language, I’ve realized that I don’t have to.  That it’d be just as easy to place them directly into the header after the page is ready, by manipulating the DOM.  Here is an excerpt from the beta turled website.

$(document).ready(function() {
	// Google Analytics
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	var script = document.createElement("script");
	script.src = gaJsHost + "google-analytics.com/ga.js";
	script.type = "text/javascript";
	document.getElementsByTagName("head")[0].appendChild(script);
	try
	{
		var pageTracker = _gat._getTracker("CENSORED");
		pageTracker._trackPageview();
	} catch(err) { /* Do Nothing. */ }
 
	// Facebook Share
	var script = document.createElement("script");
	script.src = "http://static.ak.fbcdn.net/connect.php/js/FB.Share";
	script.type = "text/javascript";
	document.getElementsByTagName("head")[0].appendChild(script);
});

As you can see, I wait until the document is loaded using jQuery’s ready method, and then create elements for both Google Analytics and Facebook Share, before appending them directly to the <head> of the website.  Keeping the code clean, reducing bandwidth usage for non-JavaScript users, and even making Google’s code cleaner.  (By changing Google Analytic’s default code from document.write to DOM Manipulation.

So, Never again will I feel the need to insert external script tags at the bottom of the <body> just so that the rest of the page loads before them.

Note: If you’re not using jQuery, document.onload = function() { /* Code */ } works just as well, I promise.

Hunting Down the Bugs – TwCLI on Chrome for Linux Beta

Posted in Google Chrome, Hunting Down the Bugs, JavaScript, TwCLI on December 15th, 2009 by Navarr – View Comments

This is the first post of a new series, looking at some of the odder bugs encountered while developing for the expanding Web, no matter how basic a bug it may be.

Thanks to twitter user @paperfairy, a bug was discovered on my Command Line Twitter Client, TwCLI.

For some reason, when submitting a command in Chrome for Linux, the page would simply refresh, and the command would never be sent.  At first, I had no possible way to track down this bug.  I didn’t have a linux box (with a GUI, anyway) so I simply told him that it was unfortunate, but it’d have to stay a bug.  Until a recent post on lifehacker brought my attention to Portable Ubuntu. I immediately installed it, opened up the Chrome website in Firiefox, installed Chrome Beta, and headed over to TwCLI to see what was amiss.

Of course, it was a single line in a detection script to send Geo-Data to Twitter (as long as the user approved it, of course):

else if(google.gears) {

This single line was throwing an exception I hadn’t encountered in other browsers – Google wasn’t defined.  Oddly, I thought it would handle that properly, since google wasn’t defined, it would just skip over it, but instead it threw an error and halted all further javascript code.

The fix was simpler than tracking down the bug, I simply had to add this to the start of the javascript code:

try{ if(!google) { google = 0; } } catch(err) { google = 0; }

And voila, I had both a check for google, and a catch if it decided to throw errors while checking for it.

Whether this is a Chrome bug or not, I don’t know – I simply don’t know enough about JavaScript in order to say so either way.  But, are undefined variables supposed to throw errors, or are they simply supposed to return false?

JavaScript & CSS3 Lightbox

Posted in CSS3 Lightbox on December 11th, 2009 by Navarr – View Comments

Usage:

  • Call createLightbox(); to create the actual lightbox element (does not display anything).
  • Call fillLightbox(string content) to fill the lightbox with RAW HTMLor

    Call appendLightbox(element childElement) to append a DOM Node directly into the lightbox.

  • Call setLightboxSize(int width, int height, null, string unit) to set the width and height of the lightbox.  Unit will default to pixels “px” if not specified.
  • Call showLightbox() to actually display the lightbox to the user.
  • Call boolean lightboxVisible() to determine if the lightbox is still visible or not.
  • Call hideLightbox() to remove the lightbox from view.
  • Call cleanLightbox() to delete all content inside the lightbox container.

Another Quick YouTube Audio Player Update

Posted in YouTube Audio Player on November 3rd, 2009 by Navarr – View Comments

The generator now also supports a Progress Bar and Time Code in three different sizes.

Read More.

YouTube Audio Player Updates

Posted in YouTube Audio Player on November 3rd, 2009 by Navarr – View Comments

The YouTube Audio Player has gotten three much-needed updates.

  • Autoplay
  • Loop
  • Playlist Support

The first two, Autoplay and loop – which is self-explanatory, are checkboxes that allow you to enable them.  (You’ll need to click Make to update the embeddable code).

The third, Playlist Support is fairly self-explanatory.  This allows you to embed not just a single video, but an entire playlist using the audio player.  There are two ways to use this feature.  Either enter the URL of a playlist URL, or the URL of a video in a playlist and check the “Entire Playlist” option.

Play

Of course, with these updates comes an update (hopefully the last) to the bookmarklet, which can be added to your browser bar by dragging this link: Generate Audio Player.

Enjoy!

SimpleTwitter Update

Posted in SimpleTwitter, Twitter on October 30th, 2009 by Navarr – View Comments

I’ve pushed a simple update to the SimpleTwitter JavaScript.  Change log (if its even needed) below.

  • Support for Twitter Lists
    • Uses the same format as twitter, for example @navarr/shogi
  • Support for Turled Profiles
    • Using the variable &turl=true will link @replies to turled beta-profiles instead of twitter profiles.
    • Surprisingly, this doesn’t break in co-ordination with lists.  It just doesn’t display the list.
  • Uses Search API
    • We moved to the search API for retrieving tweets, as well as pulling a JSON file instead of XML.  This MAY BREAK your current implementation (though it should not).  If it does, you can use the older script by pulling old.php from the server instead of index.php

Yeah, that’s it.  Was thinking about making the default for &turl being true instead of false, but figured that’d probably annoy more people than it was worth (at least until I get turled to be of more use as a twitter replacement).

YouTube Mini Audio Player

Posted in YouTube, YouTube Audio Player on October 27th, 2009 by Navarr – View Comments

If you read my personal blog (which a lot of you probably don’t even know exists) you’ll commonly see music embedded as mini-YouTube embeds.  It turns out, the magic height is 25 pixels, and the magic width (for play/pause and mute) is 62 pixels.

However, it is kind of a burden to do this every time you want to embed a mini player (you have to edit at four fields in the HTML!)  So to simplify this process, I, like any programmer before me, created a generator.  Just type in the URL to the YouTube video and press make, and you’ll get a preview as well as the cross-browser HTML-esque mess of a code to embed.

Of course, if you’re truly lazy, just drag the bookmarklet below to your bookmark bar in your web browser, and click it on any YouTube video and you’ll be taken to the page with the code already generated.

Generate Mini-Player

Source code is available via link at the bottom of the page.

80x15[1]

class::Scrobbler by Navarr T. Barnier is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
Based on a work at gtaero.net.
Permissions beyond the scope of this license may be available at mailto:navarr@koneko-chan.net.