JavaScript - Trouble Working With Custom Properties
> 1. The fifth cell contains a drop-down selection list for the quantity of items ordered as the first child node of the table cell.
> Store the reference to this selection list in the variable > `qtySelect`. > 2. Store the value of the selected option in the `qtySelect` object in the `newItem`'s `qty` property. > 3. Associate each selection list with a particular store item (you must do this because the table contains 13 different selection lists; > one for each store item) by adding a custom property to `qtySelect` > named `currentItem`, and set it equal to the `newItem` variable. > 4. Add an `onchange` event handler to `qtySelect` that sets the `qty` property value of the `currentItem` property to the value of the > selected option in the `qtySelect` selection list. ---------- I need help setting up the currentItem property so that newItem.qty updates properly when a different selection is made. function storeItem() { this.pid; this.descr; this.price; this.qty = 1; } function startShopping() { var tbody = document.getElementById("saltItems").tBodies[0]; var rows = tbody.rows; for (var i = 0; i < rows.length; i++) { var newItem = new storeItem(); var cells = rows[i].cells; newItem.pid = cells[0].innerHTML; newItem.prod = cells[1].innerHTML; newItem.desc = cells[2].innerHTML; newItem.price = cells[3].innerHTML; var selID = newItem.pid+"Qty"; var qtySelect = document.getElementById(selID); var index = qtySelect.selectedIndex; newItem.qty = qtySelect.options[index].value; } } example of one of the table rows: <tr> <td>FSSPJ11</td> <td>Fine Sea Salt</td> <td>Plastic Shaker Jar (11 oz.)</td> <td class="price">$4.15</td> <td><select id="FSSPJ11Qty"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> </td> <td class="cartAdd"><input type="checkbox" id="FSSPJ11" /></td> </tr> Similar TutorialsI am having trouble implementing this script. I am not a coder so please give exact, idiot proof advise. :-) Thank You. <script> (function() { var cx = 'user_id:field_id1'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); // This basically takes the value of the radio button (requires jQuery) $("input:radio[name='GCSField']").change(function() { cx = $(this).val(); }); })(); </script> <label for="user1"> <input name=GCSField id="user1" type="radio" value="user_id:field_id1" checked >User Field 1 </label> <label for="user2"> <input name=GCSField id="user2" type="radio" value="user_id:field_id2">User Field 2 </label> <gcse:search></gcse:search> Here is my html. <!DOCTYPE html> <html> <head><meta charset="UTF-8"> <!--[if lt IE 9]><script src=http://html5shiv.googlecode.com/svn/trunk/html5.js></script><![endif]--> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <title>TEST</title> <meta name="robots" content="noindex, nofollow"> <meta name="viewport" content=" width=device-width, initial-scale=1"><meta name="HandheldFriendly" content="true"><meta name="MobileOptimized" content="320"> <style>body{width:100%;max-width:25em;margin-left:auto;margin-right:auto;font-family:Verdana,'Palatino Linotype',Palatino,'Book Antiqua',Arial,Helvetica,sans-serif;text-align:justify;font-size:105%;background-color:#000;background:#000;}p{margin-bottom:1%;}strong{font-size:115%;font-weight:bold;}a{line-height:200%;text-decoration:underline;color:#0007C6;}article{margin: 0 0 1% 0; color:#000;background:#FEE800;background-color:#FEE800; text-align: center;}</style> </head><body> <article> <div><script> (function() { var cx = 'user_id:field_id1'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); // This basically takes the value of the radio button (requires jQuery) $("input:radio[name='GCSField']").change(function() { cx = $(this).val(); }); })(); </script> <label for="user1"> <input name=GCSField id="user1" type="radio" value="011565775292567206849:xkh-s7ljiug" checked >User Field 1 </label> <label for="user2"> <input name=GCSField id="user2" type="radio" value="partner-pub-4173665486685435:n2tml3-z5vf">User Field 2 </label> <gcse:search></gcse:search></div> <div><gcse:searchresults></gcse:searchresults></div> </article> </body></html> Here is the above page off a server TEST Thanks again. Hi Experts here, Pls help. I have written the html code like this: <a href="http://mypage.com/docfiles" target="_blank"> Click </a> But the problem is when ever the user click the click option complete url is displaying in two ways 1)on the buttom of the status bar 2)Right click on the option open the properties than also we are getting the complete url. But we don't want to see the complete url,How to hide the Url. Please give me solution I am struggling alot. Thanks and Regards, Srinivas yadav. http://becompleteamerica.com/index.p...tact&Itemid=80 It works awesome in all browsers but IE 7 & 8. The custom "alert" is actually a dialog box, with a background fader underneath it, kind of like lightbox. Any ideas why IE doesn't play nice? Thx I HAVE BEEN TRYING TO FIGURE OUT THE PARAMETERS IN THE FUNCTIONS, INCLUDING THE ARRAYS [i], [p], ["get_" + i], ["set_" + i] AND HOW THE METHODS ARE BEING CALLED IN RELATION TO i, p and val, so that I can make sense of this code. If possible can you explain the code also What I will like to know are the properties and methods of the objects generated in the following code? Also I want to know how I can use those methods to show and change the name and age for the emp2 object. this is the code: function Employee(properties) { for (var i in properties) { if (properties.hasOwnProperty(i) && typeof properties[i] != 'function') { this["get_"+i] = (function(p) { return function() { return properties[p]; }; })(i); this["set_"+i] = (function(p) { return function(val) { properties[p] = val; }; })(i); } } } var emp1 = new Employee({ name: "Bob", age: 35, foo: function() {} }); var emp2 = new Employee({ name: "Gary", age: 54 }); i have two scripts using jquery 1) custom scrollbar content 2) fade in out slideshow. they both work individually well. but when i put them together on one page the customscrollbar doesnt work. here are sample scripts 1) http://jsfiddle.net/3PaNV/ 2) http://jsfiddle.net/BM3S3/1/ 3) http://jsfiddle.net/MP6Lt/ Thanks for any suggestions or help in advance 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! Hi, I've done control in asp.net/javascript and it works on some pages of mine and as it often happens doesn't work on customer's pages . All pages are run in IE 6.0. After I run debugger I've found out that on my page offsetLeft/Top clientHeight properties have some non-zero values. I have <span id="listCLient" style="width:200px;">..</span> and on my test page elListClient.clientHeight = 200, but on customer's app's page it is 0x0 ? Same with other offsetXXX properties etc. But elListClient.style.height bears correct value. I use those properties everywhere. I think it is some settings somewhere ? or CSS styles ? Can anyone help ? Thanks a lot Vladislav Hi, I want to a javascript function like showModalDialog(<page_name>,'','<options>') here in the option I need to have overlay property where I can set opacity values. Is there any solution? Please letme know 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 Is there a way to circle trough the native properties (constructor, prototype, length) of an Array object? Obviously, a simple for(a in array) won't do the trick.
I'm not sure I phrased the question properly and it's probably easiest to show what I'm trying to get. Basically, I want to find all the properties(?) available for a single track object in iTunes. For example, this is how I access what's stored as the Album and Artist for a track: Code: var myTracks = myPlaylists(1).Tracks; alert(myTracks(1).Album); alert(myTracks(1).Artist); There are a ton of properties (like Album and Artist), but I don't know what they all are, so I was trying to list them like this, but it doesn't work: Code: for(var key in myTracks(1)) alert(key); It's probably obvious why this doesn't work, but does anyone know how to get this list? Thanks for any help! I have developped a script in order to resize the height of a div on a web page in order to display it at least up to the size of the window. Here is the code: function resize(){ var frame = document.getElementById("content"); var padding_top = parseInt(window.getComputedStyle(frame,null).getPropertyValue("padding-top")); var padding_bottom = parseInt(window.getComputedStyle(frame,null).getPropertyValue("padding-bottom")); var padding = padding_top + padding_bottom; var bodyheight = document.body.scrollHeight; var windowheight = window.innerHeight; if (bodyheight < windowheight){ frame.style.height = windowheight - padding + "px"; } } It works well, but I was wondering why I am not able to get the padding-top and -bottom using these two instructions: var padding_top = frame.style.paddingTop; var padding_bottom = frame.style.paddingBottom; The script runs but Firebug shows empty strings for both values. How come? Is there a bug in Firefox? Thanks inadvance for your time and help. Do many programmers remember most of the object properties and methods or do they use IDE or references to find those specific objects. I'm starting to learn Javascript and seeing all the different type of objects available can be depressing. I have something like this var oneTest = new CustomObj({ prop1 : 'value1', prop2 : 'value2', prop3 : 'value3' }) var twoText = Object.clone(oneTest) twoText.prop2 = "newvalue2" And when I console log twoText I see something like +Data prop2 Inside Data is a prop2 that has the value of "value2". THAT is the one I want to change/override... yet the console shows me that the prop2 is outside of the data structure so when I am acting on the cloned obj I am not getting the results i need. I tried obj.extend etc.... and that didn't work, perhaps my syntax was wrong. Any advice? Hi all! I'm pretty new to JavaScript and completely new to this forum. I'm James. Well uh, I'm not sure how to... I wanted to make something like this using javascript... Code: myObject.someMethod('something').anotherProperty much like the Code: document.getElementById('someId').style.morestuff But the thing is, I've been around every DOM whatnot I can find, I just can't seem to make it work. I kinda need it to make my own DOM for some API i'm writing. So I can write like... Code: function someGreatAPI(){ this.property1=''; this.property2=''; //... this.method1 = function(var1){ //this should make my firstMethod this.nestedProperty = 0; this.nestedMethod = someFunction; //firstMethods nested method } } //so I can use it like... var obj = new someGreatAPI(); obj.method1(10).nestedMethod(); It has to be possible, it's possible with document.getelementbyid, right? it has to be. Thanks in advance. I'm still learning js core using Flanagan's 5th ed. so please bear with me; is the if ("ignore" in arguments.callee) return; below valid or a typeo? Thanks J. Code: function inspect(inspector, title) { var expression, result; // You can use a breakpoint to turn off subsequent breakpoints by // creating a property named "ignore" on this function. if ("ignore" in arguments.callee) return; ....... Not sure if I even ask correctly. Excuse the poor PHP man for not knowing javascript. I need to add a check to this code. It picks up an image when you click on it, then puts it down when you click again. What it needs is another check WHERE (on what) have you clicked to put it down. If it's a particular DIV then OK. If not (if elsewhere) don't put it down and don't change the click counter. Code: <html> <head> <style type="text/css"> .drag { position: relative; height:56px; width:56px; background-color:#FF0000; color:White; } </style> <script type="text/javascript"> var _startX = 0; // mouse starting positions var _startY = 0; var _offsetX = 0; // current element offset var _offsetY = 0; var _dragElement; var _oldZIndex = 0; // we temporarily increase the z-index during drag var _debug; var _countClick = 0; InitDragDrop(); function InitDragDrop() { document.onclick = OnMouseClick; document.onMouseClick = OnMouseClick; } function OnMouseClick(e) { debugger; _debug = $('debug'); // if first click this is zero if (_countClick == 0) { // IE if (e == null) e = window.event; // IE uses srcElement, others use target var target = e.target != null ? e.target : e.srcElement; _debug.innerHTML = target.className == 'drag' ? 'draggable element clicked' : 'NON-draggable element clicked'; // for IE, left click == 1 // for Firefox, left click == 0 if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') { // grab the mouse position _startX = e.clientX; _startY = e.clientY; // grab the clicked element's position _offsetX = ExtractNumber(target.style.left); _offsetY = ExtractNumber(target.style.top); // bring the clicked element to the front while it is being dragged _oldZIndex = target.style.zIndex; target.style.zIndex = 10000; // set _dragElement for next click _dragElement = target; // tell our code to start moving the element with the mouse document.onmousemove = OnMouseMove; // cancel out any text selections document.body.focus(); // prevent text selection in IE document.onselectstart = function() { return false; }; // prevent IE from trying to drag an image target.ondragstart = function() { return false; }; //set click count to 1 so we know next click is to release _countClick = 1; // prevent text selection (except IE) return false; } } if (_countClick == 1) { if (_dragElement != null) { _dragElement.style.zIndex = _oldZIndex; // we're done with these events until the next OnMouseDown document.onmousemove = null; document.onselectstart = null; _dragElement.ondragstart = null; // this is how we know we're not dragging _dragElement = null; _debug.innerHTML = 'mouse up'; } //set click count back to 0 so next we know it's first click again _countClick = 0; } } function OnMouseMove(e) { if (e == null) var e = window.event; // this is the actual "drag code" _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px'; _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px'; _debug.innerHTML = '(' + _dragElement.style.left + ', ' + _dragElement.style.top + ')'; } function ExtractNumber(value) { var n = parseInt(value); return n == null || isNaN(n) ? 0 : n; } // this is simply a shortcut for the eyes and fingers function $(id) { return document.getElementById(id); } function OnMouseUp(e) { } </script> </head> <body> <div id="thediv" class="drag" style='background: url(shield.gif) no-repeat center top;'></div> <pre id="debug"> </pre> <div id="slot1" class="dropon" style='position: absolute; height:28px; width:28px; top: 200px; left: 200px; background-color:#FF0000; color:White;'></div> <div id="slot2" class="dropon" style='position: absolute; height:28px; width:28px; top: 200px; left: 230px; background-color:#FF0000; color:White;'></div> </body> </html> Hello everyone, I am fairly familiar with the concept of Objects and their properties and methods, but javascript being object based as opposed to object oriented has me stumped on how to access an object's properties from an onclick event handler created for another object created within the original object. In the example below, I have a constructor function called anyObj. to which I pass an object reference to an element. anyObj has 3 properties and one function increaseWidth() increaseWidth() creates a new button with an onclick event handler and this is where I have a problem. The onclick function needs to increase the value of anyObj's this.width property. I originally had a line this.width += 10; in the onclick but quickly realised why this wasn't working because the this in the onclick function refers to the new button object and not the this.width property of anyObj. The workaround I have used, and it works, is to make a copy of all the this.xxxxx properties. eg. width = this.width; and use the width variable in the onclick as you can see below. This "workaround" works fine but doesn't feel ideal to me. So, what I am asking advice on is, is there a better way to access the anyObj()'s properties from within the onclick function than the way I have done it? Obviously I would prefer to not have to make copies of all the anyObj() properties like I have to make them accessible to the onclick function. Code: function anyObj(divObj){ this.elem = divObj; this.width = 50; this.height = 50; this.increaseWidth=function(){ width = this.width; height = this.height; //create a button for this object to be appended to an element later on var newButton = document.createElement('button'); newButton.onclick=function(){ width += 10; //... //... } //... //... } } |