Jump to content


  • Posts

  • Joined

  • Last visited

Everything posted by Hadien

  1. Try and understand the design concept of MVC, or (Model-View-Controller). its a design pattern used in many software applications but is a very solid choice for most website applications. Model - Stores all the internal data that the application uses. e.g. the database for websites. View - What the end-user sees, experiences, and interacts with. e.g. the webpage in their browser. Controller - The internal software application that "controls" the information flow between the model and View. e.g. the server This mindset helps define the responsibilities of each section of the application: The View is responsible in making a nice and friendly interface for the user and translating the inputs the user sends into actual requests the Controller can understand. The Controller is the Brain of the application, it takes the requests from the user and considers what requests can or should be fulfilled and communicates to the Model. The Model is simply raw data (database) full of information who's entire job is to grab or store massive amounts of data as efficiently as possible return any responses back to the controller. The Controller then filters the data returned and passes it back as a smaller chunk of information to the view Finally the View takes this chunk of information and arranges it in a way that makes it easier for the end-user to understand. notice that the Model and the View do not talk directly to each other, they must go through the controller. the view shouldn't reach the model for security reasons. like-wise the model shouldn't reach to the view because its not supposed to worry about the context of the information its generating. The controller is the proxy, translator, operator, or ambassador, whichever makes best sense to you. So how does this apply to your question? Javascript is pretty laid back and lightweight and uses an interpreter to run the code. This enables it the flexibility desired to run on most platforms and remain stable, but is usually slower than its counterparts. as such Javascript is usually best used in the View section of the web application (the user's browsers) since the end user will be running on a huge array of operating systems, from PC to Phone, or even console, where its flexibility can be taken advantage of, and speed isn't an issue. PHP is a little more strict but faster than Javascript. It has a lot of control (not as much as C++, but then again you don't need as much as C++) and is strong enough to process a decent amount of logic effectively. So you typically see either it or Java used as a server-side language for servers that may need to process thousands of requests a minute. SQL or Oracle are all about grabbing and storing data FAST, and less about figuring out what to do with the data which would greatly slow them down. so these languages are not designed to have the same level of flexibility as the other languages because it needs to search billions of rows of data, gather it, and return it as fast as possible. and so make great choices for Model sections of applications. My advice is that it would benefit you to learn both, it would only help your resume, and simply understand the roles that each language works best in. Your priority depends on which section of the MVC pattern you feel is most important to your current project (they're not always weighted the same for all websites).
  2. this line is the problem: orangeCost = (5); in your example orangeCost was assigned to an anonymous function (Its attached to the orangeCost variable, but the function itself is unnamed). That offending line is actually overwriting the function you wrote, thus deleting it. So the orangeCost variable is no longer pointing to a function, but to a plain 'ol number 5. To call it correctly this should be the valid syntax: orangeCost(5); Javascript will see that and think "oh, so you want me to run a function that's stored in the 'orangeCost' variable and give that function the number 5".
  3. var rect = one.getBoundingClientRect();var DeltaX = e.offsetX - (rect.left+rect.width/2);var DeltaY = e.offsety - (rect.top+rect.height/2);var Magnitude = (DeltaX^2 + DeltaY^2)^Delta^0.5;//should provide a degree range of -89 to 270var degree = (DeltaY>0)?Math.arcsin(DeltaX/Magnitude) :180 - Math.arcsin(DeltaX/Magnitude); When I have some time I'll come back and provide some polished code, but now I have some work to do. hopefully you can use what I gave you. EDIT: So here is the fully updated code after I had the time to actually sit down and work with it http://jsfiddle.net/afo7ky03/21/
  4. its "simple" math really, run a google search on "graph arctan2" and choose images, you should see what going on from that. basically when the y input into Math.arctan2() approaches 0 the number becomes undefined and returns a NAN. use ArcSin instead. you'll need the X delta (which you already have and pathagorean therom to find the distance (the hypotenuse or magnitude) which the mouse is from the origin. then... Math.arcsin(deltaX/magnitude); you'll never want to use arctan (DeltaX/DeltaY) in this case as you'll have the risk of DeltaY nearing zero and giving you a div/0 error
  5. well its inside an elseif so you don't even need to test if the number of apples is less than 4,just if it greater than 1. inside the first "if" expression you test to see if the value is greater than or equal to 4. so if that didn't evaluate to true the value would already automatically be less than 4, checking again in the elseif would just be redundant
  6. you are using vanilla jQuery, for this to work as expected on touch screens use jQuery Mobile. For mobile screens you want to use jQuery Mobile's .on("tap",[function]) as the event handler. The beauty of this is that jQuery Mobile will adapt some functionality to PC. If someone loads the screen onto a PC the tap handler will behave like a click handler, preserving functionality. Also if you only want it to activate in the bottom corner then you'll need to move the handler from that <div class="panel"> to a small div inside the panel <div class="panel"> <div class="front"> <!-- Stuff for the front side--> </div> <div class="back"> <!-- Stuff for the back side--> </div> <!-- Add this element --> <div class="dog-ear"></div> </div> then apply css for this new dog-ear class: .dog-ear{position: relative;bottom: 0;left: 0;width: 20px;height: 20px;} $(document).on('pagecreate',function(){ function flip(){ $(this).parent(".panel").toggleClass("flip"); } $('.dog-ear').on('tap',flip);}); If you're developing for mobile using jQuery try and read up on jQuery Mobile. the framework is written in a way to try and encourage you to follow the best practices when building for mobile applications, so it should be a fruitful read.
  7. Hadien


    the reason I didn't run into that problem in my code was because of how I wrote my event handlers that link to the methods. in your script you use add event listener window.addEventListener('load',mynamespace.init); here you have addEventListener reference the init function to window directly. addEventListener forces the this reference to point to the window object when it runs init in my script I wrapped the object methods inside a custom tailored callback function... /*.....*/ele.button.onclick = function(){ if(flipflop = !flipflop){ ele.button.innerHTML = ele.button.value = "Encode"; ele.demo.innerHTML = encoder.encrypt(ele.demo.innerHTML); }else{ ele.button.innerHTML = ele.button.value = "Decode"; ele.demo.innerHTML = encoder.decrypt(ele.demo.innerHTML); } };/*.....*/ inside the onclick handler the "this" reference is pointing to the button which triggered the handler. but that doesn't matter because I call the encrypt/decrypt functions without passing on the this reference. The "this" that points to the button remains in this scope, while the "this" thats used in both crypt functions point to encoder since thats the object holding them and I'm not using any form of call or apply (this includes addEventListener). If you still want to use addEventListener then wrap the function reference inside another function window.addEventListener('load', function(){ //in this scope "this" will still point to the window object cause addEventListener forces it to. // but inside the init() "this" will point to mynamespace. it'll be preserved. mynamespace.init() }; or simply use bind to ensure this is using the right pointer window.addEventListener('load',mynamespace.init.bind(mynamespace));
  8. Glad to help! If you have any questions feel free to ask.
  9. Hadien


    I'm not sure how you're having problems with the onerror scheme not showing you were a bug is happening, what browser are you using? Works just fine in chrome, when I add a simple throw in my functions, tells me exactly the line where the error happens and everything. Personally I use Chrome's developer tools to help me locate my bugs. simply open up the console and click on the error log and it zips you to the bug. There are two types of functions in OOP, "smart" functions and "dumb" functions. "dumber" functions tries to think as little as possible and only focus on one or two things. they have their own little world and the smaller it is the less likely it will fall apart."smarter" functions work by juggling multiple responsibilities at once. the smarter a function, the more it can do, the more responsibilities it has, and the more likely that things can break in it. An effective application tries to have many, many dumb functions and very few smart functions, ideally just one smart function (though we can't always get what we want). now I could have merged my functions in the encoder into one and have them flipflop functionality instead of delegating that to the function inside the onclick handler. but my code would be less flexible as I could only work on a single group of text per page. I kept encrypt and decrypt relatively dumb so that other code blocks would have more control over it. The functions run perfectly and as expected with the given encryptKeys and as long as things stay that way its not their fault if things break. when they do break (like you add in a "!" which is not stored in the encryptKey), the fix to that problem lies outside the function. Any instance where my functions fails silently is the intention. If the string the user inputs into encrypt/decrypt is invalid then the function simply returns an empty string and it lets a smarter function worry about it. If I was actually getting an error bounced back at me from inside those functions, which can still happen if I tried, then I would have to worry about fixing the code. My encrypt/decrypt could be dumber if I really wanted to break it out even more, but I really don't need the extra control it would afford. if it mattered and I wanted to create an entire framework for encryption then sure I would be breaking down functions left and right. Not sure how this argument is against using Objects. Thats true even when your not using objects. With the right coding habits this should almost never happen anyways. This is javascript so pretty much every object in exsistence will have a namespace of any size its just the nature of the language. you can dig deep into the Object functions and exert more control on your new objects, but you usually don't need to waste the time. Beside its far better encapsulating related data into single object namespaces than having it all in the global space where its more likely to collide with another variable using the same name.
  10. Hadien


    remember the four basic qualities of Object-oriented programming: Inheritance, Composition, Encapsulation, and Polymorphism. Inheritance: Theres no true Inheritance in Javascript, you can only fake it through prototypes, but If you're not planning to extend the functionality then its not worth the effort in messing with prototypes. Composition: As a general rule in any language always favor using Composition over Inheritance. though you'll end up with an explosion of classes/objects to work with compared to inheritance, your code will be a lot more flexible. Javascript lacks an <<interface>> structure and <<abstract>> reserved terms so like with inheritance you can't achieve true composition. the insensitive type-casting can let you fake it, but it doesn't place the same limitations that other languages do, so its not as stable. Encapsulation: Make sure the least amount of objects know about your object's properties and methods. the less an object knows about another object and what it has or does, the less it relys on it. if your objects/classes lack proper encapsulation a single change in one object will force you to go back and update all other objects that depend on it. and if one piece of code breaks it's likely breaking somewhere else too. Javascript makes this hard to do as well since they want to make virtually every object transparent, but you can use closures to great effect in giving your object encapsulation. Polymorphism: one great thing about Javascript is how easy it is to change the object from one to the other without much worry to datatypes, so its simply making all objects which you plan to swapping with each other to have the same function names and similar behaviors to make them polymorphic Encapsulation is the easiest one to code for as it takes the least amount of pre-planning and most javascript scripts won't need for you to apply the other basic qualities. the very first thing I would do is group all those functions with encryptKey and make them properties of an object. this is the first step to encapsulation as now the rest of your code will only directly see an encryption object and what ever that object wants to show they they dig into it. take a look at my code for the encoder{}, specifically the two functions encrypt and decrypt. nearly all the data that those functions need can be found inside the encoder object. only needed a couple properties from the string object (length, split, and substr) and array (shift). So those two functions are well encapsulated inside the object, you could change all the code outside the encoder and so long as the specifications for javascripts string and array stays the same, encoder will purr along, and I won't have to come back and change it until I want a different encoder/decoder. encryptKey, code, and decode all need to wrapped into one object. You see, these functions work under the assumptions of whats in the encryptkey, it depends on them. say for example you make a new encryptKey where the each character translated to a 3 charater word instead of 5. Suddenly the decode function won't work cause its based on the assumption that its character translations will ALWAYS have five characters. decode depends on this specific encryptKey so you should encapsulate it into the encoder (you can because its not encapsulated to something else) its also a pet peeve of mine that if I only plan to use a variable only once inside a scope, I shouldn't allocate it to its own variable. you don't really need a var length = words.length; since its only used once in your code. so you could have gotten away with using it directly inside the for loop. your code will have less lines of code, use up less memory (even though thats not much of an argument here, it really does add up for specific data structures and larger applications) and you're less likely to have bugs in it (less code, less room for there to be mistakes).
  11. Could you post a link to the webpage with the problem so that we can see the entire issue you are having and thus provide the best solution tailored to you? Off the bat I can see you are using table tags to format your page, which could cause for some of the difficulties you have. but how serious depends on how you've set up the rest of the page and the CSS styles you're using. also this is not so much a Javascript problem as it sounds mostly like a CSS/HTML problem. catching the mouse via javascript can be done, but I'm not sure if you can map it to the playback speed of the player as every video player can be very different. A lot of questions can be answered and even more potential problems can be discovered if we can have a link to the page.
  12. Hadien

    Array problem

    Javascript uses references for non-primitive datatypes. when you had B1=A and B2 =A they both "point" to the same memory location of A. Javascript wants to save memory any chance it can so it uses direct references to avoid eating up memory for identical memory values. In order to copy the entire array to a new variable you'll need to manually walk through all its elements and assign them on by one, as dsonesuk demonstrates.
  13. Ingolme beat me to it. Its better to get more acquainted with object-oriented programming in general and not stay specific to any one language. That said, C++/C# and Java are the dominant languages when it comes to game dev. and much of the fundamentals that you would learn in C++ you can take to many many other languages, including javascript. the other way around is risky as javascript can lull you into a complacent style of programming by relying too much on letting Javascript handle the things you would worry about in other languages. and you may end up having to relearn some fundamentals when you move to something like C++. When you get more familiar with the basics of a language start using frameworks. frameworks save you a lot of work by preventing you from trying to re-invent the wheel and all the bugs that would come with it. Also after you got the basics down, grab books on design patterns so that you can better plan how you'll need to code your games before you even start the coding process, and a better plan makes for faster, more effective coding. Knowing the right design patterns can guide you to making compact, efficient, stable, and flexible programs as well as getting you into the habit of thinking in OOP, and not procedural programming. plus knowing design patterns is essential if you plan on making your own game engine, but that's a long, long way down the road.
  14. Hadien


    oh got the dreaded else if chain, just a tip that if you find yourself making a chain like this there is usually a far more efficient way of doing this... by the way did you know that you have an encryption for "Z" in there three times? also what is the purpose the hey and lol variables? they're not used...here is a rewrite... var encoder={ encryptKey:{"a":"86832", "b":"11111", "c":"10101", "d":"13364", "e":"54272", "f":"48382", "g":"94702", "h":"47029","i":"74302", "j":"10111", "k":"13831", "l":"12434", "m":"13338", "n":"14352", "o":"15356", "p":"55316", "q":"37417", "r":"16478", "s":"99190", "t":"23374", "u":"23741", "v":"22473", "w":"26433", "x":"23454", "y":"57439", "z":"26143", " ":"00000", "A":"01111", "B":"00101", "C":"13304", "D":"50272", "E":"40382", "F":"9e702", "G":"47h29", "H":"7E302", "I":"10011", "J":"0a831", "K":"12034", "L":"00338", "M":"14052", "N":"15056", "O":"55016", "P":"30417", "Q":"16M78", "R":"921A9", "S":"G3542", "T":"230W1", "U":"2A473", "V":"26Aa3", "W":"23D54", "X":"57A39", "Y":"QB143", "Z":"KKFD3", ",":"mac00", ".":"B4[](", "+":"+1+2*", "-":"-----", "*":"*****", "/":"/////", "1":"1234q", "2":"ddh21", "3":"bbdjz", "4":"K1113", "5":"53FD3", "6":"11111", "7":"94932", "8":"W4322", "9":"E42SD", "0":"-000-"}, decryptKey:null, encrypt:function(inWord){ var output = ""; if(typeof inWord === "string"){ var explode = inWord.split("") while(explode.length>0){ output += this.encryptKey[explode.shift()]; } } return output; }, decrypt:function(inWord){ var output = ""; if(!this.decryptKey){ // if the decrypt key not built yet, build it now // we wait to do it here and not hardcoded it in to save on maintainence this.decryptKey = {}; for( var key in this.encryptKey){ //swap the key and value from encryptkey for decryptkey this.decryptKey[this.encryptKey[key]] = key; } } if(typeof inWord === "string"&&inWord.length%5==0){ while(inWord){ output += this.decryptKey[inWord.substr(0,5)]; inWord = inWord.substr(5) } } return output; }}// now the code to link the encoder to elementsvar ele = {};window.onload= function(){ var flipflop = false; ele.demo = document.getElementById("demo") ele.button = document.getElementById("but") ele.button.onclick = function(){ if(flipflop = !flipflop){ ele.button.innerHTML = ele.button.value = "Encode"; ele.demo.innerHTML = encoder.encrypt(ele.demo.innerHTML); }else{ ele.button.innerHTML = ele.button.value = "Decode"; ele.demo.innerHTML = encoder.decrypt(ele.demo.innerHTML); } };}; <p id="demo">I am full of really cool text.</p><button id="but">Encode</button> good thing here is that all that code is contained inside the encoder object, theres no huge elseif chain, and both encryption functions are super fast to run back and forth. plus I created that key only once, massively reducing the risk of having a typo, while making it really easy to change both the encryption and decryption keys at the same time.
  15. sounds like just css alone solves 90% of your problems. <div class="container"><textarea class="overlay"></textarea><img src="" class="underlay"></div> .container{ position: absolute;} img.underlay{ position: absolute; z-index:0; background-color: red;// or whatever color or background-image you want... width:100%; height:100%; top:0;} textarea.overlay{ position: relative; opacity: 0.5; z-index:1;} then use what ever code you already have to resize the textarea.if you want them to stick the window without scrolling away simply switch contiainer's position to fixed and play with top and left styles to put it were you want it to be on the screen regardless of scrolling.
  16. Updated the code based on what your describing. should mostly behave like you want, though I made no effort to make it cross-browser friendly. I'm currently still in class and since I finished an in-class assignment early I decided to update this code.html: <!DOCTYPE html><html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Test page</title> <link rel="stylesheet" type="text/css" href="StylingTests.css"> <script src="backgroundUltra.js"></script> </head> <body> <div id="diamondContainer"> <div id="topLayer"></div> <div id="botLayer"></div> </div> </body> </html>backgroundUltra.js: var animator = function(L,freq,offset){ var instance = { layer:L, DeltaT:offset*1 || 0, frequency:freq*1.0 || 1.0, swap:false, prime:true, runner:function(){ this.DeltaT = (this.DeltaT+0.125*this.frequency)%(Math.PI*2); var op = (Math.sin(this.DeltaT)+1)/2 if((op < 0.05)&&this.prime){ this.prime = false; this.layer.className = (this.swap = !this.swap) ?"swap" :""; }else if( op>0.5 && !this.prime){ this.prime = true; } this.layer.style.opacity = op; } } return instance; }; window.onload = function(){ var speed = 0.25; var isRunning=false; var container = document.getElementById("diamondContainer"); var list = container.children; var diamonds = []; var IntervalID = null; var delegator = function(){ for(var i in diamonds){ diamonds[i].runner(); } } for (var i=0;i<list.length;i++){ var layer =animator(list[i],speed,Math.PI*i) diamonds.push(layer); } container.onclick = function(){ if(isRunning = !isRunning){ IntervalID = setInterval(delegator,20); }else{ clearInterval(IntervalID); } } container.onclick(); } StylingTests.css:html, body { margin:0; padding:0; height:100%; width:100%; font-size:0.625em; background-color:#E6FDFF;}#diamondContainer div{ position:absolute; background-image:url('http://lucygreenwood.net/images/bg/diam-01.png'); background-repeat:no-repeat; background-position:fixed; background-attachment:fixed; content:''; position:fixed; left: 0px; top: 0px; width: 800px; height: 1200px;}#diamondContainer #topLayer{ background-image:url('http://lucygreenwood.net/images/bg/diam-01.png'); z-index: 0; /*background-position: 0px 0px;/**/}#diamondContainer #botLayer{ background-image:url('http://lucygreenwood.net/images/bg/diam-02.png'); z-index: 1; /*background-position: 8px 12px;/**/}#diamondContainer #topLayer.swap{ background-image:url('http://lucygreenwood.net/images/bg/diam-03.png'); /*background-position: 0px 24px;/**/}#diamondContainer #botLayer.swap{ background-image:url('http://lucygreenwood.net/images/bg/diam-04.png'); /*background-position: -8px 12px;/**/}
  17. if you think it looks simple or that you can follow it then it shouldn't be out of your level, for some tricks I use in the code I give some comments about them so you can read up on those if they catch your interest. I expanded the code I gave based on what I see in here, though I don't have the time to test it before class. and I'm not sure how you intend "Find Closest" to work //tell javascript that we plan to have an object exsist in the global space.// we won't tell what gonna be inside it yet cause the page needs to load firstvar optionForm={},Items = [];//Item doesn't mess with the document so we can define it right away and// we'll treat it as a classvar Item=function(ID, NAME, COST, WEIGHT, RATING){ //private variables var id=null,name=null,cost=null, weight=null,rating=null; //public variables and methods var this = { setId:function(x){if(typeof x === "number"){id = x;}}, id:function(){return id}, setName:function(x){if(typeof x === "string"){name = x;}, name:function(){return name}, setCost:function(x){if(typeof x === "number"){cost = x;}}, cost:function(){return cost}, setWeight:function(x){if(typeof x === "number"){weight = x;}}, weight:function(){return weight}, setRating:function(x){if(typeof x === "number"){rating = x;}}, rating:function(){return rating} }; this.setId(ID); this.setName(NAME); this.setCost(COST); this.setWeight(WEIGHT); this.setRating(RATING); return this;}window.onload = function(){ //after page is loaded you can now access the document.stuff // so lets construct optionForm optionForm = { input:{ id:null, // no element to set the ID name:document.getElementById("inName"), cost:document.getElementById("inCost"), weight:document.getElementById("inWeight"), rating:document.getElementById("inRating") }, select:{ id:document.getElementById("outId"), name:document.getElementById("outName"), cost:document.getElementById("outCost"), weight:document.getElementById("outWeight"), rating:document.getElementById("outRating") }, sortButton:{ id:document.getElementById("sortId"), name:document.getElementById("sortName"), cost:document.getElementById("sortCost"), weight:document.getElementById("sortWeight"), rating:document.getElementById("sortRating") } //this is the ONLY function you need add:function(item){ if (typeof item !== "object"){ item = new Item( Items.length, this.input.name.value, this.input.cost.value+0, this.input.weight.value+0, this.input.rating.value+0 ); Items.push(item); } for (var index in this.input){ //create a new option element var op = document.createElement("option"); // set the option's innerHTML to the current item's input type value op.innerHTML = item[index](); //now place the option element inside the document, at the end inside the select element this.select[index].appendChild(op); //to keep the code pretty clean and so I can still take advantage of closures I use an anonymous function // call to preserve the closure scope. notice that I wrap the original function inside another function and // then wrap THAT in parenthesis and run it using that last pair of parenthesis. op.onClick = (function(){ var self = this, i = index, v = this.input[index].value; return function(){this.input[i].value = v;}; })(); } }, edit:function(){ //see if you can write this function }, remove:function(){ //see if you can write this function }, clearDisplay:function(){ for (var sel in this.select){ //empty out the input text boxes if (this.input[i]) this.input[i].value = ""; //empty out everything in the select while (this.select[sel].firstChild) { this.select[sel].removeChild(this.select[sel].firstChild); } } for (var i in this.input){ } }, sortBy:function(select,asc){ var newSort = []; var oldItems =Items; for(var index = 0;oldItems.length>0;index = 0){ for (var oldinx in oldItems){ if( asc&&(oldItems[oldinx][select]<oldItems[index][select]) || !asc&&(oldItems[oldinx][select]>oldItems[index][select])){ index = oldinx; } } newSort.push(oldItems.pop(index)); } Items = newSort;//overwrite Items this.clearDisplay();//clear the display // populate the selects for (var i in Items){ this.add(Items[i]); } }, save:function(){ localStorage.Items = Items; }, load:function(){ Items = localStorage.Items; // populate the selects for (var i in Items){ this.add(Items[i]); } } }; for (var header in optionForm.sortButton){ optionForm.sortButton[header].onclick = (function(){ var up = false; return function(){ optionForm.sortBy(header,up!= up); } })(); } // now see if you can put all the other onclick handlers in your application here // **** // **** // hint: except for clearDisplay, each function in optionForm should link to a event handler}
  18. the first problem I'm seeing here is that inside that forloop on the 1st post is that you're not tying a function to the onClick hander for the option tag, but RUNNING the function and putting the result (null) as the onclick handler for each option tag. next is that if you trying to create actual elements with behaviors its best not to use things like innerHTML or document.write() but things like document.createElement() and appendchild()This is my personal preference as doing so avoids so many bugs stemming from string concatenation confusion, like what you have here. finally your not showing us why your doing the things your doing...like why are you trying to wipe all the properties of an object via obj_item()? here is my implementation using OOP and also reducing overhead //tell javascript that we plan to have an object exist in the global space. // we won't tell whats gonna be inside it yet cause the page needs to load firstvar optionForm={};window.onload = function(){ //after page is loaded you can now access the document.stuff // so lets construct optionForm optionForm = { //lets set the elements that we plan to refer to as properties of the optionForm // object so that we don't need to re-find them again and again every time we call add(). // plus it encapsulates this data so nothing else in the global space needs to know or // confuse these variable with something else. input:document.getElementById("inName"), select:document.getElementById("outName"), //for now, this is the ONLY function you need add:function(){ //create a new option element var op = document.createElement("option"); // set both the val variable and the option's innerHTML to the current input's value var val = op.innerHTML = input.value; //now place the option element inside the document, at the end inside the select element select.appendChild(op); op.onClick = function(){ //using closures, whenever the option is clicked on it should be able to grab the same //name from this closure scope. no need to grab the innerhtml or use an array to store names input.value = val; } } };}now change the button html's onclich handler...<input type="button" class="bt" onmousedown="optionForm.add()" value="Add" /> See how much string manipulation I used? zero, zip, nada and I was still able to perform the same functionalities which I assume you're after, yet making it easier to expand upon, avoiding a number of potential bugs.now it shouldn't be hard if you continue this work and implement your own remove function.
  19. As it would so happen I'm halfway through college getting my masters in Game Design.Which is why I haven't been around recently I've been hella busy. Making games is a highly involved field, so much to the point that if you want to make a great game you need to understand your limits, and never expect that people will turn you down to help. I know that people here, nor your peers in the industry won't have a "don't quit your dayjob" attitude, as most will be more than willing to help. Your bosses however will want to be convinced that you have both the potential and personality to contribute to a team, (that said every game company is unique in certain mindsets). Since you already have a game concept in mind, there are a few typical things you need to have a firm grasp on before you even touch any code, the pre-pro(duction) phase. What do you want in the game, and what skills does the team have (in this case that's just you)? You wanted to do this in javascript and html (since thats what you can use) then its important to know what you can and can't do in javascript; and how this will likely affect what features your game will end up having. Simply using javascript on its own has several limitations as any player with knowledge in javascript can mess with the game state and cheat if they were so inclined. This may not bother you at all but its still a risk you have to understand if you still want to use javascript. Next is make yourself a physical prototype of the game to play as if it were a board game. of course there will be some aspects that a physical prototype can't clarify like the challenge of the game should come from the use of the mouse, but prototyping and play-testing is a tried and true technique to help both you and others in understanding what should happen in the game in certain situations and what else you'll need in the game. Plus, it can give the sense on whether the game might have elements which will be fun to play. from this you can now plan out everything you need to code far before you even code anything. All in the pre-pro stage. now walk through each feature you want in the game and ask yourself how long you think it will take to complete the feature. add up all the hours and divide that by the hours youll spend per week to give you a loose estimate of how long it'll take to complete this game. since you are the only one working on the game and you already have another job, completing even a small game like this during your spare time can take several months. The main reason I'm telling you this is so that you understand that, through these numbers alone and the level of work that goes into any game, that you shouldn't be afraid to ask for any help. Even if you are turned down every now and then. It WILL happen, people will drop out. Two developers just dropped out of our capstone for a game we were planning to release August. and so we compensate by looking for more developers on the campus (due to the workload our school gives we typically expect to only have each game developer for a month or two). TLDR; The game industry is no place for people afraid to ask for help. It is not an environment where you are expected work alone. You will not survive in the industry with a mindset like that. with rant A out of the way.... you are already in the production phase using javascript. just continue using javascript but be sure to undertake from training when you can to help you better understand it. No one becomes an expert in any field overnight, but after roughly 10000 hours of learning. so for example, going back to your job as a police officer if you worked 40 hours a week with no vacation it'll take roughly 5 years to reach this expert status. in reality you'll likely have days off or you work more than 40 a week, or you have some talent that shaves off like 1000 hours, but 5 years remains a good estimate for the average person. In any case the people here won't mind helping you train. or with any questions which they would know the answer to.
  20. I looked at what you made and created my own version:html: <!DOCTYPE html><html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Test page</title> <link rel="stylesheet" type="text/css" href="StylingTests.css"> <script src="backgroundUltra.js"></script> </head> <body> <div id="diamondContainer"> <div></div> <div></div> <div></div> <div></div> </div> </body> </html> backgroundUltra.js: var animator = function(L,freq,offset){ var instance = { layer:L, DeltaT:offset*1 || 0, frequency:freq*1.0 || 1.0, runner:function(){ this.DeltaT = (this.DeltaT+0.125*this.frequency)%(Math.PI*2); this.layer.style.opacity = (Math.sin(this.DeltaT)+1)/2; } } return instance; }; window.onload = function(){ var speed = 0.25; var isRunning=false; var container = document.getElementById("diamondContainer"); var list = container.children; var diamonds = []; var IntervalID = null; var delegator = function(){ for(var i in diamonds){ diamonds[i].runner(); } } for (var i=0;i<list.length;i++){ var layer =animator(list[i],speed,Math.PI*(i)/2) diamonds.push(layer); } container.onclick = function(){ if(isRunning = !isRunning){ IntervalID = setInterval(delegator,20); }else{ clearInterval(IntervalID); } } container.onclick(); } StylingTests.css: html, body { margin:0; padding:0; height:100%; width:100%; font-size:0.625em; background-color:#E6FDFF;}#diamondContainer div{ position:absolute; background-image:url('images/bg/diam-01.png'); background-repeat:no-repeat; background-position:fixed; background-attachment:fixed; content:''; position:fixed; left: 0px; top: 0px; width: 800px; height: 1200px;}#diamondContainer div:nth-child(1){ background-image:url('http://lucygreenwood.net/images/bg/diam-01.png'); z-index: 0; /**/background-position: 0px 0px;/**/}#diamondContainer div:nth-child(2){ background-image:url('http://lucygreenwood.net/images/bg/diam-02.png'); z-index: 1; /**/background-position: 8px 12px;/**/}#diamondContainer div:nth-child(3){ background-image:url('http://lucygreenwood.net/images/bg/diam-03.png'); z-index: 2; /**/background-position: 0px 24px;/**/}#diamondContainer div:nth-child(4){ background-image:url('http://lucygreenwood.net/images/bg/diam-04.png'); z-index: 3; /**/background-position: -8px 12px;/**/} This example should help with some insight on applying this fading effect. I'm actually using a sinewave to control the opacity here so that the fade remains smooth even if you get a tiny overflow. I also placed in a background-position on each div in the CSS so that its easier to see whats going on on each layer, but you don't need them at all. Plus I'm using FOUR layers not just two to how extra layers would stack up. I'm not saying that this is an answer to your problem as i'm not sure exactly what you want to do overall. You've told the problem you are facing (the flickering), but not what your intentions are to do here.
  21. 1st off, Approach #1 appears to work because you have nothing new happening in the SubPerson constructor if SubPerson had its own constructor it would never be called, and SubPerson would never initialize correctly. Plus Approach #2 can not only setup inheritance, but also enables you to create some fancy getter/setter functions that you simply can't do otherwise in the javascript language. Approach #2 grants you far more control in defining a subclass than Approach 1 ever can. in response to your 2nd post, You can always directly reference the prototype chain, the problem is in practice more often than not you shouldn't as doing so cause more work down the road. The way prototyping works is by levels of specificity, in a chain of Prototypes. Here is what I mean. subPersonInstance | {/*nothing defined outside the SubPerson subclass that is attached to this instance*/} v SubPerson | {/* no other variables defined in this chain*/ | prototype:Person v } Person | { | sayHi:function(){return "hi"} | prototype:Function v } Function | { /*All of the Function prototype variables*/ | prototype:Object v } Object { /*All of the Object prototype variables*/ prototype:null } now Person has the function "sayHi", but you don't re-define that function in the instance or SubPerson, so as you said its shared info. when you have subPersonInstance run "sayHi" first javascript will look in subPersonInstance to see if its defined there, its not so it looks at the next object in the prototype chain, SubPerson, to find the defined function, not deifned there either, which it continues on the prototype chain to Person where it is defined. it stops there and runs the function it found as expected if say you want a Supertype.call effect then you would write another sayHi function (for the sake of example) inside the SubPerson prototype then you would have written it like this... SubPerson.prototype = Object.create(Person.prototype,{ sayHi:{ value:function(){ return Person.prototype.sayHi.apply(this,arguments)+" there!"; //technically you don't need to use "apply" since the super function doesn't use arguments, but //this code isn't that complex in the 1st place and is universal no matter how many arguments //the super function has }, enumerable:true, configurable:true, writable:true } }); now SubPersonInstance will say "hi there!" instead of simply "hi". I should empathize that its far more important understand and use Polymorphism and Composition than simple inheritance when you want to build any OOP application of merit.
  22. Everything in Javascript are objects...objects with properties. even the functions are simple objects To get purely technical, Javascript doesn't have classes just objects that can "fake" the behavior of classes, at least enough to get by. instanceof is really just finding if one instance points to the prototype object its requested to compare to, its not making any real type-based comparison as in other languages. Over the years the javascript language itself has been slightly motified and upgraded and there is more power to making "classes", but at its roots you still don't make any "true" class.
  23. Personally, I loathe cookies. They're cumbersome, inefficient, limiting, and were mostly never intended to be used as they were. The cookie is technology from 20 years ago and has not aged well with the current-day demands of web applications. The only reason you would use cookies is like Ingolme said, for older IE versions. However, that is not even a valid excuse anymore. I don't think it is worth wrapping your head around how to create, parse, and cleanup cookies just because a couple employees were too lazy to spend 2 minutes to update their IE. If they can't be bothered, I'd say make them see the pop up on every load until they do update. You can code a check for the browser to know what webstorage is and if it doesn't you can include in the popup that updating your browser will solve the constant popups.
  24. Basically, it sounds to me you want to implement the same technologies used in Chat rooms. When people connect to a web page with an imbedded Chat plugin, it "subscribes" with server so that the server knows who is currently online at the time. eventually the subscription will expire on its own, disconnecting the user, unless the plug-in renews the subscription with the server (which they do automatically as long as the program remains open). In a chat room when someone inputs text, the text is transferred to the server and the server then announces the text to all other users currently subscribed to the server. Those that left the page have technically unsubscribed so the server won't send any data to them. What you want is something similar, but without the user input. What you want is for when users view a page they automatically subscribe to the server for a minute or so, renewing the subscription every minute they remain on the site. and when you type out a file to send, the server then publishes the file and sends it to everyone currently registered. You then have javascript or whatever plugin your running to capture the announcement and process it so that it can be displayed. This Observer pattern should pose the least overhead to the system, each user simply sends notification that they are still there, not requesting any data. and when some news does arrive the server knows exactly who is able to see it. another method is to use an RSS feed which requires the user to reload the page. Otherwise it fully meets the criteria you want. yet another option is to have an invisible iframe that periodically (once per minute is likely ideal) requests the news feed. by abusing the last-modified attribute and sessionstorage, each user will know if they have seen the news before. If so, then last-modified ensures the server isn't wasting bytes on sending them old news while client side the onload event is suppressed since last-modified matches what is in the session storage. If the info IS new to them, the server sends the new page to them, session storage updates to the current last-modified date, and the page's onload event runs creates a popup. Just like the RSS choice the update isn't instant as each client has to proactively request the news themselves, and since each client is not aware of each other they won't have synchronized updates.
  25. #bannerCache{//a containing element to store all possible images// its simply here for caching (for faster loading and less overhead) and should never be visible.display:none;}.randImg1 {background-image:url('v/vspfiles/assets/images/homepage/img_1.jpg')}.randImg2 {background-image:url('v/vspfiles/assets/images/homepage/img_2.jpg')}.randImg3 {background-image:url('v/vspfiles/assets/images/homepage/img_3.jpg')}.randImg4 {background-image:url('v/vspfiles/assets/images/homepage/img_4.jpg')}.randImg5 {background-image:url('v/vspfiles/assets/images/homepage/img_5.jpg')}#banner{width: 600px;height: 200px;background-repeat: no-repeat;} <div class="bannerCache"> <div class="randimg1"></div> <div class="randimg2"></div> <div class="randimg3"></div> <div class="randimg4"></div> <div class="randimg5"></div></div><div id="banner"></div><button onclick="randBanner()">BUTTON!</button> <script type="text/javascript">//You never need to pass arguments these are merely available in case you //might want another element to do the same as wellfunction randBanner(c,{ var cache = c||document.getElementById('bannerCache'); var banner= b||document.getElementById('banner'); try{ var index = Math.floor(Math.random()*cache.childNodes.length); banner.className = cache.childNodes[index].classname; } catch(e){ //if an exception is thrown its likely due to invalid arguments or empty cache // log to console and close quietly return console.error(e)===false; }}window.onload = randBanner;</script> This is a relatively simple approach to your problem. Its expandable, allowing you to add more images in the future. It's faster, using caching so that images don't have to be re-downloaded every page visit. The JavaScript should be relatively easy for you to read, study, and thus learn what is happening. If you don't understand something you can google it or ask here.Personallly, I'm against using a hidden bannerCache element like this since if I wanted to change the image list I'd have to update 2 files (the HTML and CSS). However this approach is pretty straightforward and its likely that periodically updating the banners shouldn't be tedious to the point that better methods would be preferred.Also you might to change soe of the CSS for #banner, I don't know the specifics of your images so the values I have likely need to be tweaked. also I added a button for you to play with.
  • Create New...