Drop Shadow

JavaScript quirks

In all modern browsers, you should have a “console”, an “error console”, or some other means of looking at the errors on the current page. If your script isn’t working, or isn’t working how you expect it to work, look on the console to see if there are any errors or warnings.

Variables are global by default

In PHP, variables within a function do not affect variables of the same name outside the function. You have to specifically say that you need the variable to be global, in order for it to affect anything outside the function.

In JavaScript, variables are global by default, even within functions. It’s a good idea to get in the habit of making variables local unless you know you need them to be global, to avoid conflicts with JavaScript tools such as our rich text editor or our image slideshow.

Make variables local by putting the keyword “var” in front of them. For example:

function uniqueOption(chosenOption, otherOptions) { if (chosenOption.checked) { var myForm = chosenOption.form; if (var otherOption = document.getElementById(otherOptions)) { if (otherOption.checked) { otherOption.checked = false; } } } }

When you see errors that indicate a variable is not behaving the way you expect it to—such as an array index being undefined, or a string not having a method you know strings have—make sure that variable has the appropriate scope and isn’t conflicting with some other variable of the same name elsewhere.

Internet Explorer

Variables and unique HTML ids in Explorer

IE8 (and possibly earlier versions of IE) turns ids into global variables. This means that you can’t use global variables that are the same as an id that might appear on a page.

If you get the error “Object doesn't support this property or method” in IE when assigning a value to a global variable, check to see if that variable matches the id of an HTML element.

Getting relative HREF attributes in Explorer

IE7 and IE8 do not return relative HREF attributes, either in straight JavaScript or in jQuery. In all browsers but IE8 and earlier, the following code will produce the string “1”:

<a id="globalimage" href="1">Global Imaging</a> … var imageLink = document.getElementById('globalimage'); var imageNumber = imagelink.getAttribute('href'); window.alert(imageNumber);

However, in IE7 and IE8, it will produce a full URL based on the location of the current page. Depending on the values allowed in this set of HREFs, you might be able to get around it with lastIndexOf:

var currentSlide = parseInt(currentAnchor.getAttribute('href')); if (!currentSlide) { //probably IE, which doesn't do getAttribute the way everyone else does var anchorURL = currentAnchor.href; currentSlide = anchorURL.substring(anchorURL.lastIndexOf('/')+1); currentSlide = parseInt(currentSlide); }

How you get around it will vary depending on the expected values. You shouldn’t have to worry about this in IE9 or higher, or in any other browser.