SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
Thread: Checking if an object exists
-
Sep 16, 2006, 14:53 #1
- Join Date
- Jan 2002
- Location
- U.S.A. *Blue State*
- Posts
- 289
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Checking if an object exists
I am using the code from chapter 7 in the Javascript Anthology to do some popups. It works very nicely except for the fact that on pages where the object that it is looking for doesn't exist, I get error messages(I include the JavaScript on every page). Everything is ok with the page, but I would rather not get the error messages.
In IE6 I get:
Error: 'document.getElementById(...)' is null or not an object
In Firefox I get:
Error: document.getElementById("big") has no properties
Here is the Javascript I am using:
Code:addLoadListener(init); function init() { document.getElementById('big').onclick = function() { var biggie = makePopup(this.href, 600, 450, 'scroll'); return biggie.closed; }; return true; } function makePopup(url, width, height, overflow) { if (width > 640) { width = 640; } if (height > 480) { height = 480; } if (overflow == '' || !/^(scroll|resize|both)$/.test(overflow)) { overflow = 'both'; } var win = window.open(url, '', 'width=' + width + ',height=' + height + ',scrollbars=' + (/^(scroll|both)$/.test(overflow) ? 'yes' : 'no') + ',resizable=' + (/^(resize|both)$/.test(overflow) ? 'yes' : 'no') + ',status=yes,toolbar=no,menubar=no,location=no'); return win; } function addLoadListener(fn) { if (typeof window.addEventListener != 'undefined') { window.addEventListener('load', fn, false); } else if (typeof document.addEventListener != 'undefined') { document.addEventListener('load', fn, false); } else if (typeof window.attachEvent != 'undefined') { window.attachEvent('onload', fn); } else { var oldfn = window.onload; if (typeof window.onload != 'function') { window.onload = fn; } else { window.onload = function() { oldfn(); fn(); }; } } }
HTML Code:<a href="/images/small-image.jpg" id="big"> <img src="/images/big-image.jpg" /></a>
I tried putting all of the javascript inside of the following code, but then the popups no longer worked:
Code:if (document.getElementById('big')) { // popup code here }
-
Sep 16, 2006, 18:09 #2
var widget = document.getElementById(...);
if(widget != null)
{
//do stuff
}
-
Sep 16, 2006, 19:30 #3
- Join Date
- Jan 2002
- Location
- U.S.A. *Blue State*
- Posts
- 289
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Originally Posted by yacka
Any other suggestions?
-
Sep 16, 2006, 19:56 #4
If you're wrapping the popup code inside a null check and it's not doing anything, then obviously the element was not found at the time the code was executing. Put an else{alert("was null");} after to confirm. If it's null then either there is no element with the required Id or the code is running before the element has been parsed by the browser.
Bookmarks