JavaScript - Question On Custom Javascript Objects
Similar TutorialsLet's say I would want to create a custom object with properties. The properties would get their values from text input fields. The only thing that I can't get is how to assign variables to the new instances of the object.Here's my go at it: //First create object prototype function Obj(prop1,prop2,prop3) { this.prop1=prop1; this.prop2=prop2; this.prop3=prop3; this.showProps=showProps; //This method will show all props } //Array for storing each object instance var Objects=new Array(),i=-1; //---Now the HTML code <form name="myform" onSubmit="Objects[i++]=new Obj(text1.value,text2.value,text3.value)"> <b>Age:</b><input name="text1"> <b>Sex:</b><input name="text2"> <b>Location:</b><input name="text3"> <input type="submit"> </form> Ok,so knowing that each array element can store anything,including another object I used an Array to store each object instance.But is there any other way of storing objects? like in variables. 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> hi. i know a little php, but new to javascript. much of the syntax is identical. i'm reading the new rhino book (flanagan 6th). in it, where he introduces METHODS, he says "When we combine FUNCTIONS with OBJECTS we get METHODS". Then he creates an empty ARRAY: Code: var a = []; then he uses the "push() method" to add elements to the array. Code: a.push(1,2,3); uh, methods are for *objects* right? Yet he is using them on an ARRAY. Can somebody help me see the light on how an array can magically becomes an object that is manipulated by a "method"? I mean, the array is still an array, no? It never actually becomes an object, right? Yet we still use a *method* to manipulate it. See my conceptual quandry? Hi Everyone I am trying to write some code to create an object in JS that contains the x,y coords for a shape i wish to draw. I create the shape, and then in a draw function I draw the shape to the screen from the object I created erlier. Trouble it is does not seem to work :S have anyone got and ideas? Code: var myShape = new newShape(200,200); function init() { canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); return setInterval(draw, 50); } // init function newShape(x,y){ this.un_X=x this.un_Y=y function drawAll() { ctx.beginPath(); ctx.arc(un_X,un_Y,30,0,Math.PI*2,true); ctx.closePath(); ctx.stroke(); } // drawAll } // newShape function draw() { ctx.clearRect(0, 0, WIDTH, HEIGHT); myShape.drawAll(); } // draw init(); Thanks in advance 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 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? Ok, I have what I think is a javascript question (correct me if Im wrong). I designed a custom form in DreamWeaver but can't get it to work. Im thinking I need to add some javascript to work. Heres my form code at the moment: Code: <form id="search-form" action="" method="post" enctype="multipart/form-data"> <fieldset> <div class="search-form"> <input type="text" name="search" value="Type Keyword Here" onBlur="if(this.value=='') this.value='Type Keyword Here'" onFocus="if(this.value =='Type Keyword Here' ) this.value=''" /> <a href="#" onClick="document.getElementById('search-form').submit()">Search</a> </div> </fieldset> </form> What I want to do is have the user type in something, click on search, and then show up the results on another page named results. What do I need to do? Hello, Here is my situation. I have a java array generated from a JSP on the server side, and saved in the session. This array consists of objects (of say class X). How can I load this array into a javascript array so I can search for a this array based on attributes of the object? Thanks Hi, one of my js file is receiving a variable which is of type object. This object has some html texts. How can get the content of this object (something like value) in javascript? Thanks, Pavan This is a bit of a strange one. I have been trying to call a function in a child object from the parent object but the child seems to be going out of scope in onbeforeunload function. These function calls work outside of a onbeforeunload, so it only fails when called in onbeforeunload. I can fix it by making the child object a global but I was trying to avoid that. Anyone know why my childobject is out of scope when called in onbeforeunload? Notice I call that same function in windows onload event and it works fine. Here is the code (I have simplified as much as possible to just show the error): Code: <html> <head> <title>Broken Page</title> <script language="javascript" type="text/javascript"> var myparent; function windowLaunch() { myparent = new parent(); myparent.getchildvalue(); window.onbeforeunload = myparent.getchildvalue; } function parent() { this.mychild = new childobject("myinput"); this.getchildvalue = function() { var tmpval = this.mychild.returnvalue(); }; } function childobject(thename) { this.myprop = thename; this.returnvalue = function() { return (document.getElementById(this.myprop).value); }; } </script> </head> <body id="thebody" onload="windowLaunch();"> <div id="outerdiv"> <span title="This Input Box">My Input:</span><br /> <input id="myinput" style="width: 290px"/> </div> </body> </html> Hi, Can i sort an array of objects in javascript?. I am having the value as Code: var myVarr = [{"name":"xyz","age":21}, {"name":"cde","age":25}]. The above array has two objects. I need to sort by age using javascript. Please help. Regards, anas Hi, I am a begginer in javascript, please help on below I want to create an object with nested objects array like following: var country{ var states=new array(); } var state { city,pincode } this should be called like var city= country[0].state[0].city; any idea will be appreciated I 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.
I wrote a log function that took note of various function calls. Thinking that functions are first class objects, and objects have properties, I made the name of each logged function a property of that function, e.g., brightenInnerPara.name = "brightenInnerPara"; Every browser I tried (Firefox, MSIE, Opera, Chrome, Safari) accepted the assignment, no problem. In Firefox and MSIE, the result was what I wanted: brightenInnerPara.name == "brightenInnerPara" But in the others, the result was: brightenInnerPara.name == null Question 1. Which Javascript is correct here? I favor Firefox and MSIE, not merely because they were willing to give me what I wanted, but also because it makes no sense to accept an assignment statement without throwing an error and then give it a null semantics, like Chrome, Opera, and Safari did. I found a workaround, using assignments like this: brightenInnerPara.prototype.name = "brightenInnerPara"; To my surprise, that worked in every browser. But I don't know why. It seems that such assignments are enough to cause each function to have its own distinct prototype. Question 2. Just how inefficient is my workaround, and why does it work? Hi all, The question is hopefully relatively simple. if I have an object say Code: [ var SampleObject = function(id){ SampleObject.id = id; SampleObject.age= 22; } Is there a way to create an event that triggers every time the age member value changes? Thanks Ollie. Hi, I want to build a custom calendar using javascript. On load of page for which date schedule are there, it should show dark black dot at left-top corner of particular date for current month. There are 3 button below the calendar as prev mnth,create schedule,next mnth. when prev is clicked it should works same as on load for previous month, similarly for next mnth. Pls help its urgent. Thanks I am working on a custom accordion. A type 2 accordion works but type 1 and 3 don't work. Does anyone know how to correct this syntax? Also, if you see any ways to make this code better, please post your fixes in this post Code: /* To use these, insert your content between a div tag. For example: <div id="2011" style="display: none"> This is the content in the accordion </div> You can have as many of these on the page as you wish but they all must have a different div tag. You will be creating a different button for each div tag. To make an item display on page load, change that div tag display from "none" to "inline". For the button that toggles the accordion: <a href="javascript:accordion('2011', '2', eventyear)">2011</a> Here is what all of these variables do: 1. Id of the div tag you want to toggle 2. The type of accordion you want 3. Only needed if it is a type 1 or 2 accordion, this refers to an array of all of the other div id's in the accordion. If you are using a type 1 or 2 array, create a array under the arrays comment of all of the div id's in your accordion. Types: 1 = One open at a time. Open and close 2 = One open at a time. Open no close 3 = No limit. Open and close. 3 doesn't use an array */ //Arrays; var eventyear=new Array("2011","2010","2009"); var months=new Array("January","February","March","April","May","June","July","August","September","October","November","December"); function accordion(click,type,array) { var click = document.getElementById(click); if ((click.style.display = "inline") && ((type == "1") || (type == "3"))) { click.style.display = "none"; } else if ((click.style.display = "none") && ((type == "1") || (type == "2"))) { var c; for(c in array) { document.getElementById(array[c]).style.display = "none"; } click.style.display = "inline"; } else if ((click.style.display = "none") && (type == "3")) { click.style.display = "inline"; }} I'm using custom javascript tooltips to show information about designs in a t-shirt shop, such as design name and artist. I downloaded the code and CSS for the tooltips and am attempting to assign the tooltip to each design using a javascript array and a for-in loop. Only problem is that the tooltips aren't showing at all, no matter what I do. I think the problem is related to the onmouseover event that I'm using, but the only thing that seems to work even partway is changing the visibility to "show" in the CSS. From that I can see that the text is being assigned to the tooltips properly and that they are being positioned within the window, but the onmouseover event is having no effect either way when I revert the visibility back to "hidden." Help! Here is the code for the "toolTip.js" file: Code: // Extended Tooltip Javascript // copyright 9th August 2002, 3rd July 2005, 24th August 2008 // by Stephen Chapman, Felgall Pty Ltd // permission is granted to use this javascript provided that the below code is not altered function pw() {return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth}; function mouseX(evt) {return evt.clientX ? evt.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) : evt.pageX;} function mouseY(evt) {return evt.clientY ? evt.clientY + (document.documentElement.scrollTop || document.body.scrollTop) : evt.pageY} function popUp(evt,oi) {if (document.getElementById) {var wp = pw(); dm = document.getElementById(oi); ds = dm.style; st = ds.visibility; if (dm.offsetWidth) ew = dm.offsetWidth; else if (dm.clip.width) ew = dm.clip.width; if (st == "visible" || st == "show") { ds.visibility = "hidden"; } else { tv = mouseY(evt) + 20; lv = mouseX(evt) - (ew/4); if (lv < 2) lv = 2; else if (lv + ew > wp) lv -= ew/2; lv += 'px';tv += 'px'; ds.left = lv; ds.top = tv; ds.visibility = "visible"; } } } Here is the relevant code where I attempt to assign the event to the tooltip visibility change. Note the syntax in SetLinks() function, where the onclick behavior is set. This syntax is working perfectly here. I modelled the 'controlPopUp() syntax similarly, but no go. Code: window.onload = function() { creationCompleteHandler(); } function creationCompleteHandler() { calcNumDesigns(); setLinks(); controlToolTip(); } function calcNumDesigns() { var numDesignBoxes = designImages.length; var numGalleryRows = Math.ceil( numDesignBoxes / 3 ); for ( n = 0 ; n <= numGalleryRows - 1 ; n++ ) { var newGalleryBox = document.createElement('div'); var newGalleryBoxID = ("galleryRow" + n); newGalleryBox.setAttribute('id',newGalleryBoxID); newGalleryBox.setAttribute('class',"galleryBox"); document.getElementById('content').appendChild(newGalleryBox); squareOff(newGalleryBox); var rowBoxes; if ( ( numDesignBoxes - ( n * 3 ) ) < 3 ) { rowBoxes = ( numDesignBoxes - ( n * 3 ) - 1 ) } else rowBoxes = 2; for ( m = 0 ; m <= rowBoxes ; m++ ) { var boxNum = ( n * 3 ) + m; var newDesignBox = document.createElement('div'); var newDesignBoxID = "design" + boxNum; newGalleryBox.appendChild(newDesignBox); newDesignBox.setAttribute('id',newDesignBoxID); newDesignBox.setAttribute('class',"designBox"); var newDesignImg = document.createElement('img'); var newDesignImgID = "designImg" + boxNum; newDesignImg.setAttribute('id',newDesignImgID); newDesignImg.setAttribute('class',"designImage"); newDesignImg.src = designImages[boxNum][0]; newDesignBox.appendChild(newDesignImg); var newDesignTip = document.createElement('div'); var newDesignTipID = "tt-design" + boxNum; newDesignTip.setAttribute('class',"tip"); newDesignTip.textContent = designImages[boxNum][2] + " Artist: " + designImages[boxNum][3]; newDesignTip.innerText = designImages[boxNum][2] + " Artist: " + designImages[boxNum][3]; newDesignBox.appendChild(newDesignTip); } } } function squareOff(frame) { document.getElementById(frame.id).style.height = ((document.getElementById(frame.id).offsetWidth) * .33) + 'px'; } function setLinks() { for (var x in designImages) { document.getElementById("design"+x).onclick = new Function( "sendToURL(" + x + ")" ); } } function sendToURL(x) { var url = designImages[x][1] MM_goToURL('self',url); return document.MM_returnValue; } function MM_goToURL() { //v3.0 var i, args=MM_goToURL.arguments; document.MM_returnValue = false; for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'"); } function controlToolTip() { for (var x in designImages) { var currTip = "tt-design" + x; document.getElementById( "design" + x ).onmouseover = "controlPopUp( event , " + x + ")"; } } function controlPopUp( evt , x ) { var e = evt; var currTip = "tt-design" + x; popUp( e , currTip ); } Here is the CSS: Code: .tip { font:10px/12px Arial,Helvetica,sans-serif; border:solid 1px #666666; width:270px; padding:1px; position:absolute; z-index:100; visibility:hidden; color:#333333; top:20px; left:90px; background-color:#ffffcc; layer-background-color:#ffffcc; } Thanks in advance for your help! Hi All, Wondering if someone could help me out. i am developing a simple javascript calculator at the problem is this: When I use the input type = button or submit, then the calculator works fine BUT I need to use a custom button and now the calculator just shows the results for a split second and then disappears and the form reloads I have made the button line in bold. All help appreciated!! Many thanks Here is my code: <html> <head> <script language="JavaScript"> function Framesize(BikeSizer) { var a = parseFloat(BikeSizer.Insleg.value); b = (a * 0.572); c = Math.round(b); BikeSizer.FramesizeCM.value = c; d = (a * 0.226); e = Math.round(d); BikeSizer.FramesizeInch.value = e; } </script> </head> <body> <Form name="BikeSizer"> <!--The visuals for the graphic--> <table cellpadding="0" cellspacing="0" align="center" border="0" width="370"> <tr> <td align="center" valign="top"><img src="images/Calculator_bg_top.gif" border="0"></td> </tr> </table> <table cellpadding="0" border="0" cellspacing="0" align="center" width="370" style="background:url(images/Calculator_bg_mid.gif) repeat-y top center; font-family:Verdana, Arial, Tahoma;"> <tr> <td colspan="2" valign="middle" align="left"> <div style="padding:2px 5px 5px 12px;"> <font style="font-weight: bold; color:#cc6600; font-size:14px">Berechnung der richtigen Rahmenhöhe</font> <br /><a href="#" style="font-size:10px">Wie messe ich die Schrittlänge richtig?</a></div> </td> </tr> <tr> <td align="left" valign="middle"><div style="font-size:11px; padding:7px 0 7px 12px;">Fahrradart:</div></td> <td><select name="Biketype" style="font-size:11px;"> <option>Mountainbike</option> <option>Trekking-, Reise- oder Cityrad</option> <option>Rennrad</option> </select></td> </tr> <tr> <td align="left" valign="middle"><div style="font-size:11px; padding:7px 0 7px 12px;">Schritthöe:</div></td> <td><input name="Insleg"></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td> </td> <td><div style="padding:6px 0 8px 0;"> <input type="image" NAME="calc" VALUE="Calculate" src="images/berechnen_btn.gif" onClick=Framesize(BikeSizer)> </div></td> </tr> <tr> <td align="left" valign="top"><div style="font-size:13px; padding:0px 0 7px 12px;"><strong>Rahmenhöe:</strong></div></td> <td align="left" valign="top" style="font-size:13px;"><input name = "FramesizeCM"> <strong>CM</strong> <br /><br /><input name = "FramesizeInch"> <strong>Zoll</strong> </td> </tr> </table> <table cellpadding="0" cellspacing="0" align="center" border="0" width="370"> <tr> <td align="center" valign="top"><img src="images/Calculator_bg_end.gif" border="0"></td> </tr> </table> </FORM> I am working on a website that features a custom javascript enabled audio player with an animated playhead to follow along with the provided spectrogram. An example of this is included below. http://cetus.ucsd.edu/voicesinthesea.../humpback.html I am having difficulty figuring out why the audio/spectrogram player does not work on an iPad. This component was built by a developer who I am not longer in contact with, thus I am in urgent need of some advice/wisdom. Thank you! |