JavaScript - Extending Objects Ie6-8
Good day,
I have the following code: Code: var img = new Image(); img.myProperty = 'something'; I've tried Image.prototype.myProperty and a few other things. It seems IE just doesn't want me extending the Image object. Is there a known work-around? Thanks Similar TutorialsI was wondering if there are any sites dedicated to ending javascript objects using the prototype property to give them features like trimming string, removing elements of arrays by name, removing duplicates in arrays, etc. Granted I have functions to do this but there's probably a ton of other good ones out there. Most things I've seen are frameworks like JQuery (which is awesome) but it doesn't extend these objects.
How to extend the constructor for the date object of the javasccript so that whenever a call is made to the constructor, I want to perform a particular action? Basically how to define wrappers for default javascript methods or objects like Date() so that I can perform some action and then invoke the original method? So basically if I have something like var a = new Date(); I want it to (say) alert the value of the date everything Date() is called and then execute the default date constructor. TIA In the spirit of the season, I wanted to make it snow on my website. So I began digging. Eventually I ended up with a script that moved an image element down the page in a snowflake-like manner. The problem with it was it was dependant on an img element for every flake - simply no poor programming when using an Object Oriented programming language. So I decided I wanted to extend (in Java-speak; most of my programming background is in Java) the in-built Image object. The new object's src variable will lead to an image of the type of flake it is. (I want to be able to have more variance in images than a simple dot.) The new object will have a function that will allow it to move. A separate, unrelated function will control when each flakes move. I did some more research and read about prototyping on JavaScript Kit and here, but I still cant seem to get this to work. JS Lint says it's bug-free, but Firefox says "move()" is an invalid function. I am presuming the problem lies in my inability to fully grasp how to extend objects in JavaScript. Code: <html> <head> <script type="text/javascript"> Image.prototype.dFlake=dotFlake; function dotFlake(xLocation,yLocation){ this.src = "simpleDotFlake.png"; this.x = xLocation; this.y = yLocation; } dotFlake.prototype.move = fall; function fall(){ // ^^ Belongs to dotFlake class. this.style.position="absolute"; this.style.top = this.y; this.style.left = this.x; this.y= this.y + 1; // Falling is constant. if (Math.random() > 0.5){ // Random direction, though. this.x = this.x + 1; } else{ this.x = this.x - 1; } } function snow(flakes){ // Allows addition of different flakes later. for (i in flakes){ i.move(); } timer = setTimeout("snow()",1); } function startSnow(){ basicFlakes = new Array(new dotFlake(0,0)); snow(basicFlakes); } </script> </head> <body onload="startSnow()"> <h1>This is test text.</h1> <img id="basicFlake" src="./simpleDotFlake.png" width="10" height="10" /> </body> </html> Any and all input is much appreciated. Thank you! function($) { $.fn.superfish = function(op){ var sf = $.fn.superfish, c = sf.c, } So I see the '.superfish' method being added to the object '$.fn'. I find it interesting that the first order of business is to declare 'sf' and stuff in to it some value '$.fn.superfish' which I do not fully understand. Also the statement c=sf.c How can 'c' be set to equal 'sf.c' when no 'sf.c' has been declared yet? Thanks! I am able to do the following; Code: alert(myObject.Income.EESA.Name); However I'm looking at Code: alert(myObject.Income[0].Name); Or even better, not the full name, just "EESA". I need to loop through as you can see at the end of this script what I'm working on. Code: <script type="text/javascript"> var EESARate = 289.3; var DLARate = 111.20; var CARate = 61.35; var SkyCost = 54.75; var PerfectHomeCost = 28.17; var CreditExpertCost = 14.99; var UnitedUtilitiesCost = 8.13; var BTCost = 57.18; var AdobeCCCost = 46.88; var TVLicenceCost = 6.06; var GasCost = 10.00; var ElectricCost = 20.0; var ServerPackageCost = 9.99; var USDValue = 123; //Fetch the value var myObject = { "Income": { "EESA": { "Name": "Enhanced Employment and Support Allowance", "Amount": { "GBP": EESARate, "USD": EESARate * USDValue }, "Frequency": { "When": "14", "Next": "30/10/2014" }, "Description": "", }, "DLA": { "Name": "Disibility Living Allowance", "Amount": { "GBP": DLARate, "USD": DLARate * USDValue }, "Frequency": { "When": "7", "Next": "Wednesday" }, "Description": "", }, "CA": { "Name": "Carers Allowance", "Amount": { "GBP": CARate, "USD": CARate * USDValue }, "Frequency": { "When": "7", "Next": "Saturday" }, "Description": "", }, }, "Bills": { "Sky": { "Name": "Sky", "Amount": { "GBP": SkyCost, "USD": SkyCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, "PerfectHome": { "Name": "Sky", "Amount": { "GBP": PerfectHomeCost, "USD": PerfectHomeCost * USDValue }, "Frequency": { "When": "7", "Next": "Wednesday" }, "Description": "", }, "CreditExpert": { "Name": "Experian Credit Expert", "Amount": { "GBP": CreditExpertCost, "USD": CreditExpertCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, "UnitedUtilities": { "Name": "United utilities", "Amount": { "GBP": UnitedUtilitiesCost, "USD": UnitedUtilitiesCost * USDValue }, "Frequency": { "When": "7", "Next": "Wednesday" }, "Description": "", }, "BT": { "Name": "British Telecomunications", "Amount": { "GBP": BTCost, "USD": BTCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, "AdobeCC": { "Name": "Adobe Creative Cloud Suite", "Amount": { "GBP": AdobeCCCost, "USD": AdobeCCCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, "TVLicence": { "Name": "Television Licence", "Amount": { "GBP": TVLicenceCost, "USD": TVLicenceCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, "Gas": { "Name": "Eon Gas", "Amount": { "GBP": GasCost, "USD": GasCost * USDValue }, "Frequency": { "When": "7", "Next": "Wednesday" }, "Description": "", }, "Electric": { "Name": "Eon Electric", "Amount": { "GBP": ElectricCost, "USD": ElectricCost * USDValue }, "Frequency": { "When": "7", "Next": "Wednesday" }, "Description": "", }, "ServerPackage": { "Name": "1&1 Unlimited Plus (12 mo. term)", "Amount": { "GBP": ServerPackageCost, "USD": ServerPackageCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, }, }; var IncomeTotal = 0; for (var k in myObject.Income) { if (myObject.Income.hasOwnProperty(k)) { ++IncomeTotal; } } alert(myObject.Income.EESA.Name); document.write('<table>') for(i = 0; i < IncomeTotal; i++){ document.write('<tr>') document.write('<td>row ' + (i+1) + ', column 0</td>') document.write('</tr>') } document.write('</table>') var TotalBills = 0; for (var k in myObject.Bills) { if (myObject.Bills.hasOwnProperty(k)) { ++TotalBills; } } //alert(TotalBills); </script> Greetings! This is actually a two part question from the html source I attached as a .txt document (too big for the post). 1) How can I get the name of an object. I took my failed attempt in the function named disableJobStream: Code: function disableJobStream(obj) { if((obj.value == "completed") && (getRadioCheckedValue("shift") == "2")) { if(obj.name == "artprogs") { document.shiftreport.artprogs.disabled = true; } } <select style="100px;" name="artprog_stat" OnChange="disableJobStream(this)"><option style='background-color:white;' value='none'selected='selected'>None</option> <option style='background-color:red;' value='stopped'>Stopped</option> <option style='background-color:yellow;' value='running'>Running</option> <option style='background-color:green;' value='completed'>Completed</option> </select> 2) Once I put my form through validation any of the fields that I disabled become enabled again. How would I go about keeping that from happening? Page is too large to post and too large to put up as an attachment! Thanks for your help! Hello there folks, First time poster, so please be gentle I am ok with using objects creating classes if someone else defines, but when it comes to defining my own, I hit a nasty brick wall... I am using an XML/XSLT wrapper called Sarissa to help with programming a utility to transform XML into HTML in different views. For this to happen, I have created a Loader class which loads in XML required. I am aware of prototyping for binding methods to objects (as opposed to replicating the same method every time an instance is created)... The aim being I want to create a progress bar for the essential files that need to be loaded in. Presently I have them load in Synchronous mode just to get the utility working, which I know is poor, so would like to address it. So can someone answer me this: I understand why this works: Code: var SWMU = new Object(); SWMU.stylesheets = new Object; SWMU.joblot = null; SWMU.cache = new Object; SWMU.filtering = new Object; SWMU.locns = null; function Loader(sXml, sTitle) { this.doc = Sarissa.getDomDocument(); this.doc.load(sXml); this.doc.summary = sTitle; this.doc.onreadystatechange = function() {if(this.readyState) {alert(this.summary + " state change to..." + this.readyState);} else {alert(this.summary + " state change to..." + this.doc.readyState);} } } function async() { SWMU.stylesheets[0] = new Loader("swmu_test/swmu_berthing.xsl", "Main SWMU Stylesheet"); SWMU.stylesheets[1] = new Loader("assets/xsl/controls.xsl", "Drop down boxes"); } function _init() { async(); } as it recreates the "this.doc.onreadystatechange" anonymous function everytime an instance is created (which is yuck). However, when I do this (using prototype)... Code: var SWMU = new Object(); SWMU.stylesheets = new Array; SWMU.joblot = null; SWMU.cache = new Object; SWMU.filtering = new Object; // Now define the Loader object // Create the loader method for dealing with items loaded function Loader(sXml, sTitle) { this.doc = Sarissa.getDomDocument(); this.doc.load(sXml); this.doc.summary = sTitle; } function rHandler() {alert(this.summary + " State changed to... "+this.readyState);} // Create the request handler Loader.prototype.doc = {}; Loader.prototype.doc.onreadystatechange = rHandler; function async() { SWMU.stylesheets[0] = new Loader("swmu_test/swmu_berthing.xsl", "Main SWMU Stylesheet"); SWMU.stylesheets[1] = new Loader("assets/xsl/controls.xsl", "Drop down boxes"); } function _init() { async(); } Nothing happens and no errors are thrown, though there should be an alert box everytime there is state change to the progress of a file loading. Can someone help me with this? Apologies if this is on the basic side, but it has been causing me a headache all week, and I can not find any answers on this. Shaun I'm having a spot of trouble in making my functions work and my book seems to be pure rubbish. I'm sure that the error is purely syntax, although it may be something more. Code: <script type="text/javascript" src="flowers.js"></script> <script type="text/javascript"> function pageSetup() { var today = new Date(); // this creates a date object with today's date var banner = displayBanner(today); // *should* call the displayBanner function var days = calcDaysToSale(today); // *should* call the function using today's date document.sale.saleMessage.value = days; // *should* set the value to days. // Obviously none of it works. } </script> This is the code working with the script contained in the html file. I'll post the full page at the bottom. The following code is the JavaScript code. The first function isn't made to provide full functionality at the moment, I'm trying to get the rest of it working. Code: function displayBanner(currentDate) { if (currentDate.getMonth() == 2) imgSrc = "winterLogo"; return ("<img src='" + imgSrc + ".gif'>"); } function calcDaysToSale(currentDate) { var saleDay = new Date(); saleDay.setDate(15); // sets the sale date to the 15th of the current month // Subtracts the days remaining until the sale. // If the number is negative, the sale is over. var Days = saleDay.getDate()-currentDate.getDate(); if (Days < 0) { return "The sale has ended."; } else { return Days; } } I have tried to Google the problem and I have also tried to look it up in my book. I simply don't know the right terms to Google, and as I said the book is rubbish. I don't know why the Code: document.sale.saleMessage.value = days; doesn't work for this. Oh well, I'll learn quickly I suppose. Here is the full HTML code: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Carol's Flowers</title> <link href="flowers.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="flowers.js"></script> <script type="text/javascript"> function pageSetup() { var today = new Date(); // this creates a date object with today's date var banner = displayBanner(today); // *should* call the displayBanner function var days = calcDaysToSale(today); // *should* call the function using today's date document.sale.saleMessage.value = days; // *should* set the value to days. // Obviously none of it works. } </script> </head> <body class="oneColLiqCtrHdr"> <div id="container"> <div id="header"> <p><img name="myBanner" src="banner" id="myBanner" alt="Carol's Flowers" /> <!-- end #header --> </p> <div id="links"><a href="#">Home</a> | <a href="#">General Arrangements</a> | <a href="#">Seasonal Designs</a> | <a href="#">Custom Orders</a> | <a href="#">Location</a></div> </div> <div id="mainContent"> <table id="mainTable"> <tr> <td width="201"><h1><img src="Flowers.JPG" alt="Random Flowers" width="200" height="255" /></h1></td> <td width="687"> <p>Here at Carol's Flowers, we believe that there is a perfect floral arrangment for every occasion! Take a look around and see if there is anything you like. If we don't already have it, then we will create it for you!</p></td> </script> </tr> </table> <!-- end #mainContent --></div> <div id="footer"> <p> <form name="sale" id="sale"> Days Until Mid Month Madness Sale : <input type="text" name="saleMessage" id="saleMessage" /></form></p> <!-- end #footer --></div> <!-- end #container --></div> <!-- I am trying to run the script here --> <script type="text/javascript"> pageSetup(); </script> </body> </html> Hello everybody am a JavaScript beginner. here is a code making rollovers //////////////////////////////////////////////// window.onload=rolloverInit; function rolloverInit() { for(var i=0; i<document.images.length; i++) { if(document.images.parentNode.tagName=="A") { setUpRollover(document.images); } } } function setUpRollover(currentImage) { currentImage.outImage = new Image(); currentImage.outImage.src = currentImage.src; currentImage.onmouseout = rollOut; currentImage.overImage = new Image(); var source = currentImage.src; var sourceText = source.toString(); if(sourceText.indexOf("png")>0) { currentImage.overImage.src ="images/"+currentImage.id+"_on.png"; } else { currentImage.overImage.src ="images/"+currentImage.id+"_on.gif"; } /*currentImage.overImage.src ="images/"+currentImage.id+"_on.gif";*/ /*currentImage.overImage.src ="images/"+currentImage.id+"_on.png";*/ currentImage.onmouseover = rollOver; currentImage.clickImage = new Image(); if(sourceText.indexOf("png")>0) { currentImage.clickImage.src ="images/"+currentImage.id+"_click.png"; } else { currentImage.clickImage.src ="images/"+currentImage.id+"_on.gif"; } /*currentImage.clickImage.src = "images/"+currentImage.id+"_on.gif";*/ /*currentImage.clickImage.src = "images/"+currentImage.id+"_on.png";*/ currentImage.onmousedown = rollClick; currentImage.parentNode.childImage = currentImage; currentImage.parentNode.onblur = rollOutParent; currentImage.parentNode.onfocus = rollOverParent; } function rollOut() { this.src = this.outImage.src; } function rollOver() { this.src = this.overImage.src; } function rollClick() { this.src = this.clickImage.src; } function rollOutParent() { this.childImage.src = this.childImage.outImage.src; } function rollOverParent() { this.childImage.src = this.childImage.overImage.src; } //////////////////////////////////////////////// 1-I do understand "if iam right, lol" that here ///currentImage.outImage = new Image();/// and here ///currentImage.overImage = new Image();/// and here ///currentImage.clickImage = new Image();/// we are creating an image object "overImage" on the fly which still a property of currentImage object, to keep track and store the current image and new image src. but here ///currentImage.parentNode.childImage = currentImage;/// I am unable to see the point behind creating the childImage object -same rule applied here??? is it really a brand new independent object "still a property of the parent" created on the fly like before? and if so -what is is purpose here?? how the cildImage object is interacting here, what is its purpose? and how it is able to modify "actually change" the <a> object child node Image object "currentImage". it seems stupid question but its quiet simple ---///currentImage.parentNode.childImage = currentImage;/// here I have an object on the fly, a new Image object "childImage", that is Fine until now. ---///this.childImage.src = this.childImage.outImage.src;/// now how the childImage became able to change my parent "<A>" child "currentImage" src ??? how it "childImage" became displayable at all is is because of the assignment here ///currentImage.parentNode.childImage = currentImage;/// ??? Yes i assigned currentImage to the childImage, but based on my java programing concepts background each still independent objects refrences representing two different objects ---->and so based on that here is these functions rollOutParent(), rollOverParent() am supposed to say something like ***this.currentImage.src = this.childImage.src*** or ***this.childImage.src = this.childImage.outImage.src;***or whatever "i know thats wrong coding here am just giving example". ------------ am confused, how with this simple line of code currentImage.parentNode.childImage = currentImage; childImage became able to define the currentImage ? and if so, how this was achieved, hoe the Objects is being represented and how they interact in the core memory? Hi, I am trying to detect a users browsers and output a different code based on browser. I found this code online that uses the object detection method and it works. When I document.write(BrowserDetect.browser) it outputs Chrome, (which is what I am using). The code can be found he http://www.quirksmode.org/js/detect.html So I can't understand why the following code does not work? It ouputs the "not" in the else statement. I believe that BrowserDetect is an object and the .browser at the end is a property of the object. Can one not make an object a variable? or make an object a string? oh and BTW there is a bunch of javascript that creates the browserdetect object that can be found on the site above, but I thought it would be too unwieldy to post here. Thanks. The following script outputs: Chrome Not Working <script type="text/javascript"> document.write(BrowserDetect.browser); var browser="BrowserDetect.browser"; if(browser=="Chrome") { document.write(" Working"); } else { document.write(" Not working"); } </script> Hi If i was using c# i would use a generic list and add all my people objects to the list collection but how do i do this in jquery/javascript eg //container object var allObj= { }; //people object var people= { name:"fred",: age:00; }; How do I add many people objects to allObj (the amount of people added in not always the same) eg the final result is something like this allObj -person1 -person2 -person3 -person4 thanks Is it possible to create an array of objects? I require a two dimensional array of objects. Thanks! Hi there, I have a very strange issue using dynamic scripting and iframe. It looks like when when iframe is loaded (i.e. onload method is triggered) all js objects that were sent to iframe before disappear? To clarify... I set iframe.scr from java script that caused it to connect to the server. After connection is established I start sending JS code to it (including some JS objects). At some point connection to iframe is closed (and onload method is called). Later on I reconnect (i.e. set src property again), and try to issue method calls on the JS objects that were sent in earlier session. None of these methods get triggered. Did anyone experienced similar problems? Is there a workaround? (I.e. is there any way I can send register JS Objects globally when sent through iframe?). Thanks for all your help, Ed I'm trying to reuse some code in a different context to do a different job. The code to be reused contains hundreds of lines similar to a = new b.c.d(e,f) with different value for e and f. I need to create a new user defined object with the structure b.c.d. I've made numerous attempts along the lines of: Code: function d (e, f) { this.e = e; this.f = f; } function c () { this.d = d (e, f); } function b () { this.c = c; } var a = new b.c.d("test", "message"); with various permuations of functional declarations. However I get error message "Object expected" or "b.c.d is null or not an object" at the final line of the example. It works with the test line var a = new d("test", "message") but not when I start to build up the expression. How should I define of b.c.d? Hi All I thought it was about time to actually learn Javascript rather than pretend I know it, so I'm new to Javascript. I've been reading Javascript 'The Good Parts' and have watched a few google videos on Youtube. So I came across prototyping which seems to be quite fundamental to JS but is quite awkward to use. I am trying to avoid the use of the 'new' keyword and limit my application to one Global variable, as this can improve the JS scripts performance, reliability and security. In essence I'm just trying to make a simple MsgBox object that has a method called 'alertMe', which in turn simply shows an alert box with 'Hello' If this is not very clear then say so as trying to explain something you don't fully understand is quite hard. Here's my code, doesn't alert when I called the object. Have a look Code: var MyLib = {}; MyLib.MsgBox = function(){ //Object methods MyLib.MsgBox.prototype.alertMe = function(){ alert('Hello'); }; }; MyLib.MsgBox.alertMe(); Any help and pointers will be very appreciated. Regards, Magnetica Hello. I'm Ansem717 and I've been honestly coding Javascript since August; however, I have learned and coded a few things a couple years ago. I'm not a master at Javascript, but I can follow along what most people say or code. I decided to test my skill in coding, by making a text-based RPG game via Javascript. Now that I've introduced my background information about JS coding, I'd like some of you to help me out with the following code: (It's fairly big, but skip it to see the actual content.) PHP Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Text Based</title> <link rel="stylesheet" href="ssgame.css" media="screen" /> <script type="text/javascript"> // JavaScript Document var d=document; //Easy shorthand var inventoryWeight=500; //Inventory cannot be heavier than 500 'units' var inventoryMaximum=30; //Inventory cannot have more than 30 items var n='\n'; //Line break for Game screen var nts=n+" "; //Line break for game screen plus three spaces for formating. I'm lazy like that XD var presentRoom=0; var player=null; var objectsInRoom=null; var allOptions="SELF INFO__LOOK AROUND__WALK NORTH__WALK SOUTH__WALK WEST__WALK EAST__ATTACK__TALK__PICKUP__DROP__INVENTORY"; function get(id) { return d.getElementById(id); } function gameSCRN(msg,overwrite,linebreak) { if (linebreak==1) var val = d.tb.gamescreen.value+n; if (linebreak==2) var val = d.tb.gamescreen.value+n+n; else var val = d.tb.gamescreen.value; d.tb.gamescreen.value = (overwrite!=1) ? val+msg : msg; d.tb.mymove.value=""; d.tb.myname.value=""; } //////////////////////////////// //SET ITEMS, NCPS, AND PLAYERS// //////////////////////////////// function Obj(name, health, strength, defense, speed, weight){ this.name = name; this.hp = health; this.str = strength; this.def = defense; this.spd = speed; this.wgh = weight; } var items=new Array(); items[0]=new Array();//ENEMY items[0][0]=new Obj('Kid Goblin', 5, 3, 2, 1) items[0][1]=new Obj('Adult Goblin', 15, 6, 4, 3) items[1]=new Array();//WEAPON items[1][0]=new Obj('Dagger', 0, 2, 0, -1, 5) items[1][1]=new Obj('Ax', 0, 7, 0, -2, 9) items[2]=new Array();//ARMOR items[2][0]=new Obj('Cloth Shirt', 0, 0, 3, 3, 1) items[2][1]=new Obj('Chainmail', 0, 0, 8, -1, 15) ///////////// //SET ROOMS// ///////////// function room(name,actions,objectsInRoom,defaultTxT) { this.name = name this.text = defaultTxT; this.actions = (actions&&actions!=0) ? actions.split("__") : "There are no actions present in this room"; this.objects = (objectsInRoom&&objectsInRoom!=0) ? objectsInRoom.split("__") : "There are no objects present in this room"; } var rooms=new Array(); rooms[0]=new room("clearing","SELF INFO__LOOK AROUND__WALK NORTH__WALK WEST__WALK EAST__WALK SOUTH__DROP",0,player.name+" is stranded in a clearing.") rooms[1]=new room("goblin hideout","SELF INFO__LOOK AROUND__WALK SOUTH__ATTACK__TALK__DROP",items[0][0]+"__"+items[0][1],player.name+" has approched a goblin hideout!") rooms[2]=new room("weaponry","SELF INFO__LOOK AROUND__WALK WEST__PICKUP__DROP",items[1][0]+"__"+items[1][1],player.name+" is inside a weaponry! Weapons increase "+player.name+"\'s strength, but may decrease his speed. Another thing to account for is "+player.name+"\'s inventory and weight. It's not like "+player.name+"\'s inventory has no end.") rooms[3]=new room("armory","SELF INFO__LOOK AROUND__WALK NORTH__PICKUP__DROP",items[2][0]+"__"+items[2][1],player.name+" is in an armory! Armor increases "+player.name+"\'s defence, but may decrease, or even increase, his speed. Another thing to account for is "+player.name+"\'s inventory and weight as well as the Armor's weight. It's not like "+player.name+"\'s inventory has no end.") rooms[4]=new room("empty room","SELF INFO__LOOK AROUND__WALK EAST__DROP",0,player.name+" has noticed a sign that says, \"No one may enter.\" Behind the sign, there is a large barbed fence that "+player.name+" cannot penetrate.") //////Actual Content function gameStart() { d.tb.gamescreen.value=" "; gameSCRN('First thing is first. Name yourself! At the bottom, there should be a small box you can type into. Type your name into that box.',1,1); } function nameSelf() { var name=d.tb.myname.value; player=new Obj(name, 100, 0, 0, 5); gameSCRN(n+"Hello there "+player.name+"!"+n+n+"In a couple of seconds, the game will begin."); get("name").style.display="none"; get("act").style.display="block"; setTimeout(function(){ActualGameStart();},5000) } function ActualGameStart() { presentRoom=0 visualizeRoom(); } function visualizeRoom() { gameSCRN(rooms[presentRoom].text,1,0); if (rooms[presentRoom].actions!="There are no actions present in this room") { for (i=0; i<rooms[presentRoom].actions.length; i++) { gameSCRN(rooms[presentRoom].actions[i],1,0); } } else { gameSCRN(rooms[presentRoom].actions,1,0); } } //The below functions have been commented out because I had an idea. I didn't want these to collide, and since that idea is almost complete, I'm keeping these incase I need to take some of the below and scatter them up top. /*function PreformAction() { var dsmv=d.tb.mymove.value.toUpperCase(); var cnotdsmv="You cannot "+dsmv+" at this moment."; if (dsmv==diffOptions[0]) { if (room==1) {gameSCRN(player.name+" "+dsmv+" but doesn't seem to find anything",0,2);} //Center room if (room==2) {gameSCRN("room==2",0,2);} //Northern Room if (room==3) {gameSCRN("room==3",0,2);} //Eastern if (room==4) {gameSCRN("room==4",0,2);} //Southern if (room==5) {gameSCRN("room==5",0,2);} //Western } else if (dsmv==diffOptions[1]) { if (room==1) {gameSCRN(player.name+" "+dsmv+" into room 2. Add extra functions and karp here.",0,2);} if (room==2) {gameSCRN(cnotdsmv,0,2);} if (room==3) {gameSCRN(cnotdsmv,0,2);} if (room==4) {gameSCRN(player.name+" "+dsmv+" into room 1.",0,2);} if (room==5) {gameSCRN(cnotdsmv,0,2);} } else if (dsmv==diffOptions[2]) { if (room==1) {gameSCRN(player.name+" "+dsmv+" into room 4. Add extra functions and karp here.",0,2);} if (room==2) {gameSCRN(player.name+" "+dsmv+" into room 1.",0,2);} if (room==3) {gameSCRN(cnotdsmv,0,2);} if (room==4) {gameSCRN(cnotdsmv,0,2);} if (room==5) {gameSCRN(cnotdsmv,0,2);} } else if (dsmv==diffOptions[3]) { if (room==1) {gameSCRN(player.name+" "+dsmv+" into room 5. Add extra functions and karp here.",0,2);} if (room==2) {gameSCRN(cnotdsmv,0,2);} if (room==3) {gameSCRN(player.name+" "+dsmv+" into room 1.",0,2);} if (room==4) {gameSCRN(cnotdsmv,0,2);} if (room==5) {gameSCRN(cnotdsmv,0,2);} } else if (dsmv==diffOptions[4]) { if (room==1) {gameSCRN(player.name+" "+dsmv+" into room 3. Add extra functions and karp here.",0,2);} if (room==2) {gameSCRN(cnotdsmv,0,2);} if (room==3) {gameSCRN(cnotdsmv,0,2);} if (room==4) {gameSCRN(cnotdsmv,0,2);} if (room==5) {gameSCRN(player.name+" "+dsmv+" into room 1.",0,2);} } }*/ /*function displayOptions(objects) { if (objects=="none") { gameSCRN(n+n+"OPTIONS:",0,1) gameSCRN(nts+diffOptions[0],0,0) gameSCRN(nts+diffOptions[1],0,0) gameSCRN(nts+diffOptions[2],0,0) gameSCRN(nts+diffOptions[3],0,0) gameSCRN(nts+diffOptions[4],0,0) } }*/ </script> </head> <body> <center> <h1>Text-Based Game Name Coming Soon</h1> <form name="tb" id="tb"> <textarea id="gamescreen" name="gamescreen" cols="67" rows="20" onfocus="blur()"></textarea><br /><br /> <div id="act"> What do you do?<br /> <input type="text" id="mymove" name="mymove" /><br /> <input type="button" id="wdyd" name="wdyd" value="Preform action!" onclick="PreformAction()" /> </div> <div id="name"> What do you do?<br /> <input type="text" id="myname" name="myname" /><br /> <input type="button" id="namebtn" name="namebtn" value="Preform action!" onclick="nameSelf()" /> </div> </form> </center> </body> <script type="text/javascript"> //Initiate functions gameStart(); </script> </html> Sorry It's so large. I'm have a major bug and it's getting in my way. It has to do with the rooms objects. As you can see I set a new array to have the ability to create rooms on the spot and each of the rooms contacted the function of creating an object. PHP Code: function room(name,actions,objectsInRoom,defaultTxT) { this.name = name this.text = defaultTxT; this.actions = (actions&&actions!=0) ? actions.split("__") : "There are no actions present in this room"; this.objects = (objectsInRoom&&objectsInRoom!=0) ? objectsInRoom.split("__") : "There are no objects present in this room"; } var rooms=new Array(); rooms[0]=new room("clearing","SELF INFO__LOOK AROUND__WALK NORTH__WALK WEST__WALK EAST__WALK SOUTH__DROP",0,player.name+" is stranded in a clearing.") rooms[1]=new room("goblin hideout","SELF INFO__LOOK AROUND__WALK SOUTH__ATTACK__TALK__DROP",items[0][0]+"__"+items[0][1],player.name+" has approched a goblin hideout!") rooms[2]=new room("weaponry","SELF INFO__LOOK AROUND__WALK WEST__PICKUP__DROP",items[1][0]+"__"+items[1][1],player.name+" is inside a weaponry! Weapons increase "+player.name+"\'s strength, but may decrease his speed. Another thing to account for is "+player.name+"\'s inventory and weight. It's not like "+player.name+"\'s inventory has no end.") rooms[3]=new room("armory","SELF INFO__LOOK AROUND__WALK NORTH__PICKUP__DROP",items[2][0]+"__"+items[2][1],player.name+" is in an armory! Armor increases "+player.name+"\'s defence, but may decrease, or even increase, his speed. Another thing to account for is "+player.name+"\'s inventory and weight as well as the Armor's weight. It's not like "+player.name+"\'s inventory has no end.") rooms[4]=new room("empty room","SELF INFO__LOOK AROUND__WALK EAST__DROP",0,player.name+" has noticed a sign that says, \"No one may enter.\" Behind the sign, there is a large barbed fence that "+player.name+" cannot penetrate.") In the above code, I'm creating various objects following under the variables rooms[0] to rooms[4], yea?. At the very beggining of the whole RPG game, it brings up some text saying name yourself in the input box below. After you do that, it adds more text to a textarea 'reminding' you of what your name was. The game then is supposed to start right after that, but thats when we run into these functions, on which counteract with the variabled rooms above: PHP Code: function gameStart() { d.tb.gamescreen.value=" "; gameSCRN('First thing is first. Name yourself! At the bottom, there should be a small box you can type into. Type your name into that box.',1,1); } function nameSelf() { var name=d.tb.myname.value; player=new Obj(name, 100, 0, 0, 5); gameSCRN(n+"Hello there "+player.name+"!"+n+n+"In a couple of seconds, the game will begin."); get("name").style.display="none"; get("act").style.display="block"; setTimeout(function(){ActualGameStart();},5000) } function ActualGameStart() { presentRoom=0 visualizeRoom(); } function visualizeRoom() { gameSCRN(rooms[presentRoom].text,1,0); if (rooms[presentRoom].actions!="There are no actions present in this room") { for (i=0; i<rooms[presentRoom].actions.length; i++) { gameSCRN(rooms[presentRoom].actions[i],1,0); } } else { gameSCRN(rooms[presentRoom].actions,1,0); } } As you can see, we have the starting function which is initiated after all of the HTML elements load, then we have the "nameSelf()" function which creates the player as well as sets the timeout for the actual game. The main error code is right he gameSCRN(rooms[presentRoom].text,1,0); and in both IE and Firefox, the script doesn't continue. It doesn't preform the "gameSCRN()" function. In IE, I'm able to click on something that shows me errors within the browser. The Error IE presented: 'rooms[...].text' is null or not an object. What does this mean? I remember setting 'rooms[0].text' to have a string value, and I did do some debugging, 'rooms[0].text' does return with the apropreate value, as well as, 'rooms[presentRoom].text' does too. They just won't work in the above function? I have searched your forums, very good codes out there, but I have not found something concrete that can fix this bug. I'd be really grateful for your help as well as some hints and tips on Javascript coding, since I would also like some help on cleaning up my javascript. And no, I am not taking any programming courses, however much I wish I am. Thanks in advanced! --Regards, --Ansem717 Could someone please explain the difference in these two methods of creating objects: //anonymous self invoking function providing private methods var a_module = (function() { var private_variable = "some value"; function private_function() { //some code } return { public_property: "something" //etc } }() ); //Can use a_module.public_property with this Is there any difference between the above and this: var A_module - new Object(); A_module(property1, property2) = { this.property1 = property1; this.property2 = property2; this.methodName = function(){//code} } A_module.prototype.property = "//property" A_module.newMethod = function() {//code} Are they both just different ways of creating objects with methods and properties? I have a javascript assignment I am having difficulties with. I have most of it complete but need some assistant with the last portion and that is to get my display function to work. I am sure that this is something I should know how to do but for the life of me can't seem to figure out and just need a little guidance. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Lab03</title> <h1> Person Information </h1> <script type= "text/javascript" charset= "utf-8"> function Person( ) { this.lastname = ' '; this.firstname= ' '; this.areacode= ' '; this.phone_number= ' '; this.show_person = ' '; } </script> <script type= "text/javascript" charset= "utf-8"> var per1 = new Person function getInput( ) { lastname= prompt("please enter your last name: "); firstname= prompt("please enter your first name: "); areacode= prompt("please enter your area code: "); phone_number= prompt ("Please enter your phone number (ex:888-8888): "); return per1; } per1= getInput( ); </script> </head> <body> <script type ="text/javascript" charset= "utf-8"> function show_person( ){ if( firstname == "" && lastname == "" ) { document.writeln( "Name: Unknown" + "<br/>" ); } else if( firstname == 'null' && lastname == 'null' ) { document.writeln( "Name: Unknown" + "<br/>" ); } else if ( firstname == "" || lastname == "") { document.writeln("Name: " + lastname); document.writeln(firstname + "<br/>"); } else if ( firstname == 'null' || lastname == 'null') { document.writeln("Name: " + lastname); document.writeln(firstname + "<br/>"); } else { document.writeln("Name: " + lastname + ", "); document.writeln(firstname + "<br/>"); } else if ( areacode == "" || phone_number == "" ) { document.writeln ("Phone: "); } else if ( areacode == 'null' || phone_number == 'null' ) { document.writeln ("Phone: "); } else { document.writeln('Phone: (' + areacode + ')'); document.writeln(phone_number); } return this.show; } </script> <noscript> <p>You must enable javascript to view all the features of this page.</p> </noscript> </body> </html> Can someone help me out and tell me what it is I need to do to make it work? I actually had it working when I was able to put all the code in the get function but was told I needed a separate display function so any input is greatly appreciated. Can someone please tell me why there is an error with my code (see in red below). I am told that 'process' is not an object or is null and I don't understand why or the implications with the click event which I am trying to capture and pass to my function: Javascript Code: Code: var USStates = new Array(50); USStates[0] = "Alabama"; USStates[1] = "Alaska"; USStates[2] = "Arizona"; USStates[3] = "Arkansas"; USStates[4] = "California"; USStates[5] = "Colorado"; USStates[6] = "Connecticut"; USStates[7] = "Delaware"; USStates[8] = "Florida"; USStates[9] = "Georgia"; USStates[10] = "Hawaii"; USStates[11] = "Idaho"; USStates[12] = "Illinois"; USStates[13] = "Indiana"; USStates[14] = "Iowa"; ... var stateEntered = new Array(50); stateEntered[0] = "1819"; stateEntered[1] = "1959"; stateEntered[2] = "1912"; stateEntered[3] = "1836"; stateEntered[4] = "1850"; stateEntered[5] = "1876"; stateEntered[6] = "1788"; stateEntered[7] = "1787"; stateEntered[8] = "1845"; stateEntered[9] = "1788"; ... var process = document.getElementById("search"); process.onclick = getStateDate; function getStateDate() { var selectedState = document.getElementById("entry").value; for (var i = 0; i < USStates.length; i++) { if (USStates[i] == selectedState) { break; } } if (i < USStates.length) { alert(selectedState + " entered the Union in " + stateEntered[i] + "."); } else { alert("Sorry, '" + selectedState + "' isn't a US State."); } } HTML Code ( in case you need it): Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Loops</title> <script type="text/javascript" src="loops.js"></script> </head> <body> <h2>Enter a US Sate in the field below and click the 'submit' button to get the date of entry in the union</h2> <form action="process.php"> <input type="text" id="entry" name="entry" /> <input type="button" id="search" name="search" value="submit" /> </form> </body> </html> Probably a noob question but I'm to the point where I need suggestions. I am trying to make an object that adds more objects to the page onclick. For example, I have an image (lets say its a plus sign) that I want users to click to add a new predesignated image (lets say its an image that the user can label with text) to the page. I want the user to be able to create a page/list full of user labeled images. Thanks. |