SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Thread: Stupid error

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2007
    Posts
    51
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Stupid error

    I'm getting this really stupid error that makes no sense because everything looks right. I know it's late and I may be missing something, but does anyone see something that's causing this error?

    test has no properties

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Promo</title>
    <script type="text/javascript">
    var test = document.getElementById('test');
    var link = test.getAttribute('href');
    
    link.onclick = window.close();
    </script>
    </head>
    
    <body>
    <a href="http://www.cnn.com" id="test"><img src="/i/promo.jpg" width="400" height="100" alt="" /></a>
    </body>
    </html>

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,718
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    When the script in the head runs, the body doesn't exist at that stage, so the "text" identifier isn't yet available.

    The best answer is to move the script to the bottom of the body.
    Next best is to place the code in a function and call that function when the page finished loading.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    Guru in training bronze trophy SoulScratch's Avatar
    Join Date
    Apr 2006
    Location
    Maryland
    Posts
    1,838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    <script type="text/javascript">
    window.onload = function() {
    var test = document.getElementById('test');
    test.onclick = window.close();
    }
    </script>
    As pmw57 said, the document isn't fully loaded and it runs in order, goes from HEAD to BODY. You need to set a function on the 'load' event of the 'window' object, and then when the window has fully loaded you can access elements. You are assigning the variable link to an attribute and then assigning a function to the onclick event of that attribute. That's not possible, because attributes don't have events. Elements do. If the test element is an element such as an anchor (<a id="test" href="#foo">test</a>) then you need to assign the function to the onclick event of the element (not attribute!!).


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •