• Lucid Dreaming - Dream Views




    Results 1 to 17 of 17
    Like Tree3Likes
    • 2 Post By khh
    • 1 Post By khh

    Thread: JavaScript Object Test... What is Wrong?

    1. #1
      Christian youssarian's Avatar
      Join Date
      Dec 2007
      Gender
      Location
      Independence, Kansas
      Posts
      441
      Likes
      41

      JavaScript Object Test... What is Wrong?

      The JavaScript library, project-1.js:

      Code:
      function Starship(Name,Length,Count,List){
        // Create the Starship class.
        this.name=Name;
        this.length=Length;
        this.numberConstructed=Count;
        this.nameOfConstructedShips=List;
        this.addConstructedShip=function(){
          this.numberConstructed++;
        }
        this.getRandomName=function(){
          alert(this.nameOfConstructedShips[Math.round(Math.random()*this.nameOfConstructedShips.length)]);
        }
      }
      
      // Now let's make them.
      gal_list=new array("Enterprise","Yamato","Venture","Galaxy","Odyssey","Challenger");
      int_list=new array("Intrepid","Voyager");
      
      enterprise=new Starship("Galaxy",641,6,gal_list);
      voyager=new Starship("Intrepid",334,2,int_list);
      The XHTML document:
      Code:
      <?xml version="1.0" encoding="utf-8"?>
      <!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">
      <!-- This website is designed to conform with standards for XHTML 1.0 Strict. -->
      
      <head>
      <title>Objects</title>
      
      <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
      
      <script type="text/javascript" src="project-1.js">
      </script>
      
      <style type="text/css">
      </style>
      
      </head>
      <body>
      
      <script type="text/javascript">
      document.write(enterprise.length);
      </script>
      
      </body>
      </html>
      Can someone tell me the problem? It should work... but no browser I use appears to like objects. I get an error saying that "enterprise is undefined"
      Learn the art of lucid dreaming in a whole new way!
      LD Count: 37 (35 DILD, 2 DEILD)

      Hey Newbies! Did you read the main pages and the tutorials? It will help you immensely.

      Zenventive: art, health, philosophy
      You are dreaming!

    2. #2
      khh
      khh is offline
      Remember Achievements:
      1000 Hall Points Veteran First Class
      khh's Avatar
      Join Date
      Jun 2009
      Gender
      Location
      Norway
      Posts
      2,482
      Likes
      1309
      On line 16 and 17, it's supposed to be "new Array", not "new array". Javascript is case sensitive.

      So this should work
      Code:
      function Starship(Name, Length, Count, List) {
      	// Create the Starship class
      	this.name = Name;
      	this.length = Length;
      	this.numberConstructed = Count;
      	this.nameOfConstructedShips = List;
      	this.addConstructedShip = function() {
      		this.numberConstructed++;
      	}
      	this.getRandomName = function() {
      		alert(this.nameOfConstructedShips[Math.round(Math.random()*this.nameOfConstructedShips.length)]);
      	}
      }
      
      // Now let's make them.
      gal_list = new Array("Enterprise", "Yamato", "Venture", "Galaxy", "Odyssey", "Challenger");
      int_list = new Array("Intrepid", "Voyager");
      
      enterprise = new Starship("Galaxy", 641, 6, gal_list);
      voyager = new Starship("Intrepid", 334, 2, int_list);
      youssarian and LRT like this.
      April Ryan is my friend,
      Every sorrow she can mend.
      When i visit her dark realm,
      Does it simply overwhelm.

    3. #3
      Christian youssarian's Avatar
      Join Date
      Dec 2007
      Gender
      Location
      Independence, Kansas
      Posts
      441
      Likes
      41
      You, good sir, have fixed a problem that has plagued me for quite a while. Now if I can only get object methods to work...
      Learn the art of lucid dreaming in a whole new way!
      LD Count: 37 (35 DILD, 2 DEILD)

      Hey Newbies! Did you read the main pages and the tutorials? It will help you immensely.

      Zenventive: art, health, philosophy
      You are dreaming!

    4. #4
      Christian youssarian's Avatar
      Join Date
      Dec 2007
      Gender
      Location
      Independence, Kansas
      Posts
      441
      Likes
      41
      Another similar problem that I've been bumping into quite often.

      The JavaScript library, project-1.js:
      Code:
      // -------- Constructor --------
      function Racer(Which){
        // Create the Racer class, each of which is an opponent.
        this.name=Which;
        this.position=0;
        this.metal=0;
        this.energy=0;
      }
      
      // -------- Functions and Subroutines --------
      function testMove(){
        playerMove=Math.round(Math.random()*20);
        player.position+=playerMove;
        playerIcon.style.pixelLeft+=playerMove;
      }
      
      // -------- Useful Variables --------
      player=new Racer("player");
      
      playerIcon=document.getElementsByTagName("img")[0];
      And the XHTML document:

      Code:
      <?xml version="1.0" encoding="utf-8"?>
      <!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">
      <!-- This website is designed to conform with standards for XHTML 1.0 Strict. -->
      
      <head>
      <title>Project 1: RACE!</title>
      
      <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
      
      <script type="text/javascript" src="project-1.js">
      </script>
      
      <style type="text/css">
        h1{
          text-align:center;
        }
        #player{
          background-color:red;
          width:500px;
          height:50px;
        }
        #player-icon{
          position:relative;
        }
      </style>
      
      </head>
      <body>
      <h1>Project 1: RACE!</h1>
      <p>In this game, you attempt to reach the end of the track before the computer does. There are two resources (Metal and Energy) collected each turn which can be used to either speed you up or slow down the opponent.</p>
      <div id="player">
        <img src="player.bmp" alt="" name="player-icon"/><br />
      </div>
      <input type="button" name="start" value="Start!" onclick="testMove()" />
      </body>
      </html>
      The picture is supposed to advance upto 20 pixels every time I click the Start! button but it doesn't move, and playerIcon is undefined inside function testMove(). I tried making it a parameter for testMove() but that did no good.
      Learn the art of lucid dreaming in a whole new way!
      LD Count: 37 (35 DILD, 2 DEILD)

      Hey Newbies! Did you read the main pages and the tutorials? It will help you immensely.

      Zenventive: art, health, philosophy
      You are dreaming!

    5. #5
      khh
      khh is offline
      Remember Achievements:
      1000 Hall Points Veteran First Class
      khh's Avatar
      Join Date
      Jun 2009
      Gender
      Location
      Norway
      Posts
      2,482
      Likes
      1309
      This happens because the HTML site in not finised loading by the time your script is run, therefore when you use getElementByTagName() on the last line of the JS, the image tag hasn't been created yet, and therefore it doesn't return an object.

      There are two simple ways to resolve this. The first is making sure the script is run after the image tag has been loaded, which you can get by putting the <script> tag below the image tag.

      The other, much more elegant way is to place the getElementByTagName() in a function, and have that function load when the script is loaded. Javascript enabled browsers accept the "onload" argument on tags, so you could write this in the html
      Code:
      <img src="player1.bmp" alt="blah" onload="setPlayerObject(this)" />
      and add this in the js
      Code:
      function setPlayerObject(obj) {
      	playerIcon = obj;
      }
      and when the browser loaded the img element, playerIcon would be defined.

      However, it is bothersome to have to set the onload in the HTML, therefore you can just do this
      Code:
      window.onload = function () {
      	playerIcon=document.getElementsByTagName("img")[0];
      }
      The above function will run then the entire page is loaded. So if you have a large picture or something, it won't run until that's been loaded.

      Also, you shouldn't use bmp for images. It's not supported in all browsers on all operating systems. If you want lossless images, use png.
      April Ryan is my friend,
      Every sorrow she can mend.
      When i visit her dark realm,
      Does it simply overwhelm.

    6. #6
      Christian youssarian's Avatar
      Join Date
      Dec 2007
      Gender
      Location
      Independence, Kansas
      Posts
      441
      Likes
      41
      There are two simple ways to resolve this. The first is making sure the script is run after the image tag has been loaded, which you can get by putting the <script> tag below the image tag.
      Tried that. I could even see the pixelLeft property increase but the image itself wouldn't move.

      The other, much more elegant way is to place the getElementByTagName() in a function, and have that function load when the script is loaded. Javascript enabled browsers accept the "onload" argument on tags, so you could write this in the html
      Tried that, and again the pixelLeft property would increase but the image itself didn't move.

      However, it is bothersome to have to set the onload in the HTML, therefore you can just do this
      Ditto for the first two.

      Also, you shouldn't use bmp for images. It's not supported in all browsers on all operating systems. If you want lossless images, use png.
      I use AvancePaint instead of Microsoft Paint because, well, Microsoft Paint has somehow disappeared from my computer, and AvancePaint only allows files to be saved/loaded in BMP, JPG and GIF formats.
      Learn the art of lucid dreaming in a whole new way!
      LD Count: 37 (35 DILD, 2 DEILD)

      Hey Newbies! Did you read the main pages and the tutorials? It will help you immensely.

      Zenventive: art, health, philosophy
      You are dreaming!

    7. #7
      khh
      khh is offline
      Remember Achievements:
      1000 Hall Points Veteran First Class
      khh's Avatar
      Join Date
      Jun 2009
      Gender
      Location
      Norway
      Posts
      2,482
      Likes
      1309
      Quote Originally Posted by youssarian View Post
      Tried that. I could even see the pixelLeft property increase but the image itself wouldn't move.
      Well, that's because "pixelLeft" is your property. It doesn't mean anything to the browser, and therefore the browser doesn't act upon it. When I am looking for the right property, I use w3schools' css reference.

      If you want to manipulate how it's shown in the browser, you must use the correct properties. In this case I think I'd have used something like
      Code:
      playerIcon.style.left = player.position+"px";
      In order for that to work, you must have set position to relative, or something. So the whole JS:
      Code:
      // -------- Constructor --------
      function Racer(Which){
      	// Create the Racer class, each of which is an opponent.
      	this.name=Which;
      	this.position=0;
      	this.metal=0;
      	this.energy=0;
      }
      
      // -------- Functions and Subroutines --------
      function testMove(){
      	player.position+=Math.round(Math.random()*20);
      	playerIcon.style.left=player.position+"px";
      }
      
      // -------- Useful Variables --------
      player=new Racer("player");
      
      window.onload = function () {
      	playerIcon=document.getElementsByTagName("img")[0];
      	playerIcon.style.position = "relative";
      }
      Also, why are you using the "name" attribute on the image? In xhtml it's only valid to use "id", except on form elements.
      Also, if you want to write correct xhtml, w3's validator comes in handy. If you're using opera, just push Alt+Ctrl+Shift+U and it'll upload it automatically.

      Quote Originally Posted by youssarian View Post
      I use AvancePaint instead of Microsoft Paint because, well, Microsoft Paint has somehow disappeared from my computer, and AvancePaint only allows files to be saved/loaded in BMP, JPG and GIF formats.
      Then use a program to convert it. Which you should anyway, paint produces crappy png images. At least do that when/if you release it.
      Last edited by khh; 02-17-2010 at 12:42 AM.
      April Ryan is my friend,
      Every sorrow she can mend.
      When i visit her dark realm,
      Does it simply overwhelm.

    8. #8
      Christian youssarian's Avatar
      Join Date
      Dec 2007
      Gender
      Location
      Independence, Kansas
      Posts
      441
      Likes
      41
      I use w3schools' css reference.
      So do I, actually. Although upon glancing, posLeft and pixelLeft don't appear to be covered...

      Code:
      playerIcon.style.left = player.position+"px";
      Tried that... still won't move! It's odd, I forget how, but I managed to do something like this in school. Of course, that involved a setInterval() or setTimeout().

      why are you using the "name" attribute on the image? In xhtml it's only valid to use "id", except on form elements.
      Mental mix-up, caused by using getElementsByTagName.

      if you want to write correct xhtml, w3's validator comes in handy.
      Ah yes, I've had that bookmarked for a while. I've not done the validation because the document, which I want to upload to my website eventually, hasn't been made ready for uploading.

      By the way,
      Thank you for helping! Much more useful than Google!
      Learn the art of lucid dreaming in a whole new way!
      LD Count: 37 (35 DILD, 2 DEILD)

      Hey Newbies! Did you read the main pages and the tutorials? It will help you immensely.

      Zenventive: art, health, philosophy
      You are dreaming!

    9. #9
      khh
      khh is offline
      Remember Achievements:
      1000 Hall Points Veteran First Class
      khh's Avatar
      Join Date
      Jun 2009
      Gender
      Location
      Norway
      Posts
      2,482
      Likes
      1309
      Quote Originally Posted by youssarian View Post
      So do I, actually. Although upon glancing, posLeft and pixelLeft don't appear to be covered...
      That's because posLeft and pixelLeft aren't valid atributes at all. At least I've never heard of it.

      Quote Originally Posted by youssarian View Post
      Tried that... still won't move! It's odd, I forget how, but I managed to do something like this in school. Of course, that involved a setInterval() or setTimeout().
      My code worked, but I'm guessing you omitted the playerIcon.style.position = "relative" because you thought "that's defined in the embed CSS anyway. But you see, since you used the "name" tag instead of the "id" tag in your HTML, the browser doesn't know that you want it to have the position: relative style on it. Therefore the .style.left property doesn't do anything. So if you change it from "name" to "id", it should work.

      Quote Originally Posted by youssarian View Post
      Ah yes, I've had that bookmarked for a while. I've not done the validation because the document, which I want to upload to my website eventually, hasn't been made ready for uploading.
      I just validate as I write the page. It's so easy on Opera :p

      edit: Also, you know that you can use document.getElementById("player-icon") instead of document.getElementByTagName("img")[0]? (Well, after you've changed it from "name" to "id", anyway).
      Last edited by khh; 02-17-2010 at 04:11 AM.
      April Ryan is my friend,
      Every sorrow she can mend.
      When i visit her dark realm,
      Does it simply overwhelm.

    10. #10
      Christian youssarian's Avatar
      Join Date
      Dec 2007
      Gender
      Location
      Independence, Kansas
      Posts
      441
      Likes
      41
      posLeft and pixelLeft do indeed exist, but they're not well liked evidently.

      I switched name to id. I'm really uptight about keeping myself in compliance with standards.

      My history with using getElementById() has been a rocky one. Especially considering IE seems to have trouble with it.

      It's telling me that playerIcon is undefined.
      Learn the art of lucid dreaming in a whole new way!
      LD Count: 37 (35 DILD, 2 DEILD)

      Hey Newbies! Did you read the main pages and the tutorials? It will help you immensely.

      Zenventive: art, health, philosophy
      You are dreaming!

    11. #11
      khh
      khh is offline
      Remember Achievements:
      1000 Hall Points Veteran First Class
      khh's Avatar
      Join Date
      Jun 2009
      Gender
      Location
      Norway
      Posts
      2,482
      Likes
      1309
      Quote Originally Posted by youssarian View Post
      posLeft and pixelLeft do indeed exist, but they're not well liked evidently.
      Well, as long as they're supported, that's what counts.

      Quote Originally Posted by youssarian View Post
      I switched name to id. I'm really uptight about keeping myself in compliance with standards.
      Good

      Quote Originally Posted by youssarian View Post
      My history with using getElementById() has been a rocky one. Especially considering IE seems to have trouble with it.
      I don't think I've ever had any problems with using the getElementById(), and I've made pages that works with IE6.

      Quote Originally Posted by youssarian View Post
      It's telling me that playerIcon is undefined.
      Well, then either your browser is faulty or you're not doing what I'm suggesting. I see no other options. Try Copy-pasting the complete JS I posted earlier and see if it works. If it does, try finding out what the key difference between that and your JS if, if it doesn't try another browser (if you're on IE).
      April Ryan is my friend,
      Every sorrow she can mend.
      When i visit her dark realm,
      Does it simply overwhelm.

    12. #12
      Christian youssarian's Avatar
      Join Date
      Dec 2007
      Gender
      Location
      Independence, Kansas
      Posts
      441
      Likes
      41
      OK, so you can check to see if it does or doesn't work. Maybe I forgot to implement one of your solutions. I have it online here for you to check the source code and test it. (Only the Start! button will work, BTW.)
      Learn the art of lucid dreaming in a whole new way!
      LD Count: 37 (35 DILD, 2 DEILD)

      Hey Newbies! Did you read the main pages and the tutorials? It will help you immensely.

      Zenventive: art, health, philosophy
      You are dreaming!

    13. #13
      khh
      khh is offline
      Remember Achievements:
      1000 Hall Points Veteran First Class
      khh's Avatar
      Join Date
      Jun 2009
      Gender
      Location
      Norway
      Posts
      2,482
      Likes
      1309
      The problem is that you have body call setup() via the onload argument. Since setup doesn't exist, this holts the execution of the javascript.
      youssarian likes this.
      April Ryan is my friend,
      Every sorrow she can mend.
      When i visit her dark realm,
      Does it simply overwhelm.

    14. #14
      Christian youssarian's Avatar
      Join Date
      Dec 2007
      Gender
      Location
      Independence, Kansas
      Posts
      441
      Likes
      41


      I clearly do not deserve the computer technology credits I got from high school. Or I just need to be more observant.
      Learn the art of lucid dreaming in a whole new way!
      LD Count: 37 (35 DILD, 2 DEILD)

      Hey Newbies! Did you read the main pages and the tutorials? It will help you immensely.

      Zenventive: art, health, philosophy
      You are dreaming!

    15. #15
      khh
      khh is offline
      Remember Achievements:
      1000 Hall Points Veteran First Class
      khh's Avatar
      Join Date
      Jun 2009
      Gender
      Location
      Norway
      Posts
      2,482
      Likes
      1309
      Quote Originally Posted by youssarian View Post


      I clearly do not deserve the computer technology credits I got from high school. Or I just need to be more observant.
      You just need to learn how to use your browsers debug console.
      In Opera it's Tools -> Advanced -> Error console (or something like that)
      In Firefox it's Tools -> Error messages

      It's usually very helpful in finding the problem.
      April Ryan is my friend,
      Every sorrow she can mend.
      When i visit her dark realm,
      Does it simply overwhelm.

    16. #16
      Christian youssarian's Avatar
      Join Date
      Dec 2007
      Gender
      Location
      Independence, Kansas
      Posts
      441
      Likes
      41
      I have been using that. I just failed to notice the little onload attribute in the <body> tag... I swear some browsers are so anally sensitive.
      Learn the art of lucid dreaming in a whole new way!
      LD Count: 37 (35 DILD, 2 DEILD)

      Hey Newbies! Did you read the main pages and the tutorials? It will help you immensely.

      Zenventive: art, health, philosophy
      You are dreaming!

    17. #17
      khh
      khh is offline
      Remember Achievements:
      1000 Hall Points Veteran First Class
      khh's Avatar
      Join Date
      Jun 2009
      Gender
      Location
      Norway
      Posts
      2,482
      Likes
      1309
      Quote Originally Posted by youssarian View Post
      I swear some browsers are so anally sensitive.
      Pretty much all the browsers are like that.
      April Ryan is my friend,
      Every sorrow she can mend.
      When i visit her dark realm,
      Does it simply overwhelm.

    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
    •