Archive for the ‘Javascript’ Category

Proportional Scaling Calculator

Tuesday, May 13th, 2008

I’m sure this has been done before since it’s pretty simple - I just couldn’t find it quick enough when I needed it. And since it is so simple, it was easier to just create my own personal little calculator than dig around, find one, bookmark. (or worse yet, do the math on a little sticky note next to my computer) ;P

This calculator will let you enter in the original width and height of an image (or document, video or whatever). Then you enter the width (or height) of the size you need it scaled to (down or up). And it will tell you what the other side needs to be.

For example: I have an 800×600 image - I need it scaled down to fit in a 256 width area… what height will I need to make it? This tool will answer your question.

Proportional Scaler Calculator

Phone number validation with jquery

Saturday, May 3rd, 2008

One of the things I’ve been playing around with a lot recently is jquery. Why I didn’t jump on this bandwagon sooner, I’m not sure, but I am kicking myself for it. So I am still a bit of nub on the jquery front - but I like to think I pick things up quickly. :D

So one thing I am now using jquery regularly for is form validation. Previously, form validation used to mean a lot of script writing, not to mention a fair amount of dread.

Now it’s quite painless.

My current usage of that plugin is pretty basic until I get a better handle of it. But one thing that I have been requested a number of times, is to add validation for a phone number - which is not included in that plugin. I’m not sure this is the “right” or best way to do it - but it does work. :)

The functions are basically the same as those provided here with some minor modifications and altered to be used with the jquery plugin.

First of course you include the jquery javascript file:
<script language="javascript" type="text/javascript" src="/js/jquery.min.js"></script>

Then the validation plugin:
<script type="text/javascript" src="/js/jquery.validate.pack.js"></script>

Then you add the function to check the phone number:
<script type="text/javascript">
$.validator.addMethod("phone", function(strPhone) {
var digits = "0123456789";
var phoneNumberDelimiters = "()- ext.";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 10;
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}, "Please enter a valid phone number");

Some “helper” functions:
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}

Then the line that makes the jquery run:
$(document).ready(function() {
$("#myform").validate();
});
</script>

To use the jquery validation plugin - I was just adding “required” as a class to those fields that were required. Like this:
<input type="text" name="FirstName" class="required" />

You can check email structure by also adding the class “email”.
<input type="text" name="EmailAddress" class="required email" />

And now, using the code above, if you add the class “phone” - it will check a phone number.
<input type="text" name="PhoneNumber" class="required phone" />

(My code above allows for some additional characters beyond just numbers - so that it will accept parens around the area code - dashes or periods between the numbers and “e” “x” “t” characters as well - in case someone needs to include an extension.)

Typical disclaimer - like I said - I’m still a nub at jquery. There may be a better/easier way to do the above, so as always feel free to chime in if you know what that better/easier way is…

Updated 5/5/08 I do see a “phone” method in the “additional-methods.js” file… but I needed it do things a little differently… (like allowing extension numbers etc.)

Suckerfish Dropdown navigation going behind content

Saturday, May 3rd, 2008

Awhile back, I had a project where I created a nice clean (X)HTML page including navigation using UL and LI tags. A few months later the client decided they wanted to add a dropdown menu to the navigation. No problem, I thought. We just add the embedded lists to the navigation - style it with CSS - and use the Suckerfish dropdown menu technique. Easy Peasy.

Except when I implemented it, the drop down menus were showing up BEHIND the rest of the content instead of “above/over it”.

There was a lot of other things going on in the page, I have a simple example that demonstrates the issue.

I’m sure it makes sense somehow, if I had a better grasp of what “position: relative” does to the document - beyond that “position: relative” allows items INSIDE a relatively positioned block to be absolutely positioned WITHIN it (which is why I had done that). The side effect though is that it does that crazy thing with the menu.

Oh the HOURS and HOURS to figure that out…. /sigh.

Here is the same page - with just that one line (position: relative) removed.

I’ve now seen this problem crop up a few times. In one case, I was working with a design that I had not originally created and even though there were no “position: relative” in any of the css files - the only way to get the menu to be ABOVE the content was to explicitly declare “position: static” inside the div tag itself. (Even just declaring it in the css wouldn’t fix it - somewhere else it must have still been getting overridden)

While I’m at the point where I can’t even imagine designing a page using a table based layout anymore, I still get hit with some CSS sticking points that I just don’t get. So if you have more insight on this feel free to elaborate in the comments. I’m just so glad I was able to get the menu working!

Have button (input element) go to new page with onclick

Friday, January 25th, 2008

This is probably considered “Javascript 101″ - but I still had a bit of trouble finding just the right syntax to work. Simply needed a button to open a new page (in the same browser window):

<input type="button" value="THERE REALLY ARE OTHER SEARCH ENGINES!"
onclick="location.href='http://www.yahoo.com'; return false" />

Change class name assignment with javascript

Saturday, December 1st, 2007

Example:
<div id="mydiv" class="current">Content</div>

To change class assignment:
document.getElementById('mydiv').className = 'notcurrent';

To remove the class assignment:
document.getElementById('mydiv').className = '';

Warning: reference to undefined property

Tuesday, July 10th, 2007

The main reason I’ve seen that error come up in javascripts is because a form name or field name has been misspelled somewhere. Tonight, while I combed over every name until my vision was crossed - I discovered a new reason why you might get this error:

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

I was working with CubeCart - and that’s their default. I usually use:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Hope that saves someone else some pain…

Setting Form Elements (mini-cheatsheet)

Friday, March 23rd, 2007

Just some random stuff. This post was saved as a draft a long time ago because I needed to refer to one of these - but was waiting until I could find the original source to publish. It’s pretty generic/basic stuff, though, (and a really small snippet) so I’m finally posting it.

To set the value of a text element, the following syntax is used:
document.formName.elementName.value = elementValue;

To set a select element, the following syntax is used:
document.formName.elementName.selectedIndex = elementValue;(also see this post: Javascript Sect Selection in Select Element)

To set a radio element, the following syntax is used:
document.formName.elementName[elementValue].checked = true;

To set a checkbox element, the following syntax is used:
document.formName.elementName.checked = true

Simple Google Maps (for dummies)

Friday, March 23rd, 2007

I was recently asked to embed a map into a web site. Basically, the client wanted a map, with a marker, indicating where their business was, and an easy way for the user to get directions to where they were located.

The first thing you need to do is get a Google Map API key. Just a little warning - once you sign up for the API key - it will show up on the top of the page - and after you leave that page, I have yet to find where you can go to retrieve it again. So copy and paste that key in a safe place! LOL!

Here are a couple of resources that helped me out:
Of course there’s the Google Maps API documentation.
Also, this was a pretty good tutorial.

In order to place a marker on the map, you need to know the longitude and latitude of your location. Originally I found “Bud’s Blog, which linked to geocoder.us (US locations only) , but for some reason, it couldn’t find the address I wanted to mark. I also found this this site which will give you the longitude and latitude (and that one DID find the location). Another source is TerraServer. (US locations only) Here’s another one that seemed pretty good. Also, here’s another one that will let you click on the map to place a marker - and then if you click on the marker it will give you the lattitude and longitude. (This was particularly useful, because for some reason the address, Google, Mapquest, and Yahoo maps all don’t seem to know where the location of this particular client was). (Although you can also kind of do this with Yahoo maps by clicking on an area and then right click in the spot and selecting “drive to here” - on the left side it will give you the long./lat. location of the spot you clicked…)

You can also pull that information from the URL you get from Google Maps.
For example..
If you look up the Red Butte Gardens in Utah, (that place is GORGEOUS by the way!), and click the button to “link to this page”, it will give you this URL. If you break down the pieces of that URL, you will see that one part of it looks like this:
ll=40.771182,-111.809063 (not the “sll” value, the “ll” value) That is the longitude and latitude.

I should note that there is some variances/weirdnesses depending on the source you use. If I type in the address in Google Maps, the marker looks like it is where I want it, and if I grab that “ll” value longitude and latitude and use that value on my own map - it shows the marker quite a bit off the road. (Probably more accurate to where the main building is, after their long driveway, but I want to show the location of where their driveway entrance is.) TerraServer was more accurate in that regard.

UPDATE 6/9/07: Just got this link to Tech-recipes off Lifehacker: Once your location in in the center of the map, enter the following Javascript in the address bar. This will pop up a little “alert” type window with the coordinates:javascript:void(prompt('',gApplication.getMap().getCenter()));

(FYI - you can right click on an area of the map and select “center map here” from the little menu you get)

Moving along to creating the map…
When I first started working with the map, I was using one of the samples from “Buds Blog” - however, the sample you get when you first sign up for your API key includes some code that is necessary so that IE doesn’t choke. If you’ve already stripped that info out, and IE is choking, here is a post I found that will explain how to fix it.

Anyway, use the base-starter sample you get when you sign up for the API key and you’ll be fine. :)

Their example had one line for setting the point and setting the point at the center, but I needed to separate it into two statements. (As well, I needed to change the long. and lat. coordinates for my location.

So this:
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
Became this:
var gardenPoint = new GLatLng(40.7628,-111.8246);
map.setCenter(gardenPoint, 15)

This sets a point and puts it in the center of the map. The “15″ is the “zoom” level. (The higher the number the closer the zoom). Another trick with this is that if you play around with a map directly on Google Maps - do the “Link to this page” thing - look at the URL, and look for the value of “z”… that is the number of what your zoom is.

map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
This adds the typical controls to the map. If you would prefer smaller controls, use this:map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());

var gardenMarker = new GMarker(gardenPoint);
map.addOverlay(gardenMarker);
This creates a new marker at that point, and puts it on the map. (FYI “gardenPoint” and “gardenMarker” are just variable names I made. You can actually make then anything you want.)

var gardenHtml = '<b>Red Butte Botanical Garden</b>,<br /><a href="http://www.redbuttegarden.org/">They have beautiful flowers</a><br />300 Wakara Way<br />Salt Lake City, Utah 84108<br /><br /><a href="http://maps.google.com/maps?f=d&hl=en&daddr=300+Wakara+Way,+Salt+Lake+City,+UT+84108">Get Directions to here</a>';
That makes one of those little “bubbles” and you can pretty much put anything you want to in there. I even put a link to Google maps to get directions with this address as the ending destination.

gardenMarker.openInfoWindowHtml(gardenHtml);This connects that buttle to the marker and makes it so that it’s open when the map loads.

Here’s the complete example.

I know that’s pretty basic - but should I ever need to do that again, I wanted to save all the links and information I needed to create the same map. :)

Javascript set selection in select element

Tuesday, February 6th, 2007

I needed to set the selection of a drop down menu. As far as I can tell, if you don’t know the “index” value, then you just have to loop through to set the item as selected. If there’s an easier way to do this, please speak up in the comments. I spent WAY too long hunting for a better solution, but this was the only thing that worked:

for (var i=0; i < document.formname.dropdownboxname.length; i++) {
if (document.formname.dropdownboxname[i].value == “value”) {
document.formname.dropdownboxname[i].selected = true;
}
}

Two submit buttons send form to two different pages

Saturday, December 23rd, 2006

Somewhat along the same lines as this older post

I had a “purchase” page where I wanted to allow the user to either purchase items on the site via credit card, or they could choose to pay via paypal. So two buttons. One that says “Pay with Credit Card” another that says “Pay with Paypal”… the paypal button should submit the form to paypal. The pay with credit card should submit the form to the next step on the site itself.

So in this case the form tag looks like this (with nothing in the value for action) :

<form name="paymentform" action="" method="post">

And the submit buttons look something like this:

<input type="button" name="paypal" value="Pay by PayPal" onClick="document.paypalForm.action='https://www.paypal.com/cgi-bin/webscr'; document.paymentform.submit();" />

<input type=”button” name=”creditcard” value=”Pay by Credit Card” onClick=”document.paymentform.action=’paymentinfo.php’; document.paymentform.submit();” />

One thing to note - do NOT name any of the buttons “submit” otherwise it won’t work.