JavaScript - Problem Passing An Argument...
I started Javascript yesterday.
I am trying to make the function Captain Obvious simply say what button you are pressing in an alert box, but after I click the button, nothing happens at all, no error message or anything. I have tried it with no argument inside the script call, and then it sort-of works. The alert box comes up saying: "You have clicked on a button that says "undefined"." I am pretty sure that means that I am having a problem passing the argument when I call it, but to be honest I have no clue lol Code: <head> <script type="text/javascript"> function CaptainObvious('choice') { alert("Captain Obvious:You have clicked on a button that says ''"+choice+"''."); alert("Just fulfilling my public duties.") } </script> </head> <body> <form> <input type="button" value="Apple" onclick=CaptainObvious("apple")> </form> Any ideas? Similar TutorialsPHP Code: function $(x) { return document.getElementById(x); } function test(x) { alert(x.id); } function init() { var o = {}; o.id = "a"; $("one").addEventListener("click", function () {test(o);}); o.id = "b"; $("two").addEventListener("click", function () {test(o);}); o.id = "c"; $("three").addEventListener("click", function () {test(o);}); } window.onload = init; I have some code similar to this. When the HTML elements with id's "one", "two", or "three" are clicked, they all alert "c", but I want them to alert the respective values (a, b, and c). How can I pass the object by value and not by reference? I guess in this simple example you would just define two more objects, but my code is actually within a for-loop. The object properties are changed each iteration (ideally each iteration creates a new object) and then passed to the function. Hello, I am trying to execute a javascript function passed as argument. I am not sure of the exact way to do it. <html> <head> <script type="text/javascript"> var checkLink = function(linkId, enabledFunction){ var linkidObj = document.getElementById(linkId); if(linkidObj.className=="activelinktext" ) { enabledFunction(); return false; } else if(linkidObj.className=="inactivelinktext") { return false; } alert("*inside CheckLink*"+enabledFunction); }; </script> </head> <body> <a class="inactivelinktext" onclick="checklink(this,"javascript:goback();")"> </body> </html> Thanks, -Vijay Hi, I am facing a problem in passing replace() function as an argument in user defined java function, can any one help me how to resolve it? intention is to pass a file path to my user defined function, but before passing the path i want to replace the character '\' to '\\' I am posting my javascript function he <a href="#" onclick="OpenDocPreview('<%# Eval("PATH")%>'.replace(/\\/g,"\\\\"), '<%# Eval("Filename")%>')"><%# Eval("DocTitle") %></a> function OpenDocPreview(url, docname) { alert('message from search base : ' + url + ' ' + docname); } thank you, I'm used to java so I keep wanting to us something like someOtherObject.someMethod(this); function someOtherObject = function(){} someOtherObject.prototype.someMethod = function(object){ object.doSomething(); } I can't seem to get it to work I'm not trying to pass a DOM object, I'm trying to pass a custom function object. Any help would be greatly appreciated I have the following code: [CODE] rtn += "<div class='crowelem' style='width:100px;'>"+panel.genSendButton(current.readNode())+"</div>"; [CODE] This is in a loop that generates rows in a DIV. current.readNode() is returning an object from a linked list, the method genSendButton looks like this: [CODE] MatchRequest.prototype.genSendButton = function (obj) { var rtnstr = null; if(obj.msNotified == 0) { rtnstr = "<input type='button' value = 'Notify' onClick=\"javascriptanel.sendNotification("+obj+")\"/>"; } else { rtnstr = "<input type='button' value='Already Notified' disabled='true' onClick=\"javascriptanel.sendNotification('"+obj.msID+"')\"/>"; } return(rtnstr) ; } [CODE] If you step into this code in a debugger, obj is correctly passed into genSendButton as an object of the appropriate class. The code in the if(obj.msNotified == 0) clause generates an error. The var obj resolves to NPanlel: (this happens to be the class of the object). Regardless of how I try to pass obj into the method sendNotification it doesn't resolve to an object. Can anyone shed any light on where my omission of intelligence is occurring? Any help would be greatly appreciated. Mrbub i am getting a problem while passing parameter to another 'jsp' through hidden variables.I am getting null while requesting the parameter in 'mywindow.jsp' my code goes like this <form name="name" enctype="multipart/form-data"> <input type="hidden" name="flag" id="flag" value=""/> ........ </form> setting its value in javascript.. like this.. <script type="text/javascript"> function openNewWindow(){ var flag1="1"; document.getElementById("flag").value=flag1; document.tstForm.action = "Mywindow3.jsp"; document.tstForm.method = "POST"; document.tstForm.submit(); } </script> in mywindow.jsp:: <% String strFlag = request.getParameter("flag"); out.println("strFlag:"+strFlag); %> i am getting "null" as value of strFlag.I need to use enctype as "multipart/form-data" to submit form. I have two versions of this document. The first version uses only JavaScript and the standard PROMPT(). It works very well, but I would like to insert the name prompt into the page using the input command. For some reason the variable loaded in the HTML statement doesn't get passed to the JavaScript. Any ideas would be appreciated! This is only a small test page. Sorry I don't know about the [code] tag... <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)"> <meta name="created" content="Sat, 10 Sep 2011 19:40:31 GMT"> <meta name="description" content=""> <meta name="keywords" content=""> <title>Enter golfers name</title> <!--[if IE]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <SCRIPT LANGUAGE="JavaScript" type="text/javascript" src="script1.js"></SCRIPT> <SCRIPT LANGUAGE="JavaScript"> function GetPage(){ document.write("OK") var lab = ""; var result = fullname.toUpperCase(); var word=result.split(" "); fname = word[0] lname = word[1] alpha = lname.slice(0,1); lab = fname.concat("_") lab = lab.concat(lname) if(word[2]){ ext = word[2] lab = lab.concat("_") lab = lab.concat(ext) } var intro = "./Stats_"; page = intro.concat(alpha); page = page.concat("_golfers.html#"); page = page.concat(lab) document.write(page) <!-- window.location.pathname = page } </script> </head> <body> <center> <form action="form_action.asp" method="get"> You can enter the golfersname or select him from the above list.<br><br> <input type="text" name="fullname" /> <button type="submit" onclick="GetPage()">GO</button> </form> </center> <BR><BR><BR> This is the end </body> </html> Hi Everyone, I have the following problem that I have been trying to figure out for a few hours now and am hoping someone can give me a help out. I am opening a popup - this popup is solely to take an image url and as such has one field. On this 1st popup I have a 'button' which when clicked launches a 2nd popup window containing a file browser. The user selects the file by double clicking on the image they want, the url is passed back to the 1st popup, poulating the field and the 2nd popup is closed. Work perfectly in FF etc.. but in IE7 and IE8 it will not work. I am using the following function, linked to the button in the 1st popup, to open the 2nd popup window pass across the name of the field and the window object to the 2nd window. Code: function popupTwoInit(file_path, field_name, win) { var w = window.open(file_path, null, 'toolbar=yes,menubar=yes,width=900,height=600'); w.fileFileField = field_name; w.fileFileWin = win; } Where w is holding the window object created by the window.open, field_name is the name of the field on the popup that I wish to pass back a value to and win is the window object of the 1st popup. I am using this function as the callback to poulate the field in the 1st dialog after an image in the 2nd dialog has been selected: Code: filebrowser_callback(url) { window.fileFileWin.document.forms[0].elements[window.fileFileField].value = url; window.fileFileWin.focus(); window.close(); } So this function accesses the passed through window object and field name from the window.open function, populates the field, gives the 1st popup focus and closes the 2nd popup. I thought about using opener in the 2nd popup to access the window object and field in the 1st popup but opener seems to refer to the main page in the browser - perhaps because I am using 2 popups OR I have got that wrong. Like I say works perfectly in FF but IE is always undefined for both 'window.fileFileWin' & 'window.fileFileField' which seems to suggest that the object is not interpreted by IE in the first function? I am a PHP developer with limited Javascript knowledge so any help would be great. Thanks very much. Hello, i'm working on a 3 page survey. When hitting next, previous, or submit it passes the values of all the questions to the next page. I've got the whole thing working correcting except for one thing: When the box is "not" checked it passes no value. I'm needing it to have a value of "1" when checked and a value of "0" when not checked, and currently when its not checked and i pass the info it leaves it blank. I'd post the whole code to one of the pages but it's long , so i'll post the snipits of the code. Code: <script type="text/javascript"> /* <![CDATA[ */ function processQueryString() { var formData = location.search; formData = formData.substring(1, formData.length); while (formData.indexOf("+") != -1) { formData = formData.replace("+", " "); } formData = unescape(formData); var formArray = formData.split("&"); for (var i=0; i < formArray.length; ++i) { //document.writeln(formArray[i] + "<br />"); var sDataName = formArray[i].split("=") switch (sDataName[0]) { case ".lib_use": for (var j=0; j < document.getElementsByName(".lib_use").length; ++j) { if (document.getElementsByName(".lib_use").item(j).value == sDataName[1]) { document.getElementsByName(".lib_use").item(j).checked = true; //alert("lib_use set"); } } break; case ".lib_comp": if (sDataName[1] == 1) { document.getElementsByName(".lib_comp").checked = true; document.getElementsByName(".lib_comp").value= 1; } else { document.getElementsByName(".lib_comp").checked = false; document.getElementsByName(".lib_comp").value= 0; } break; default: alert("not caught = " + sDataName[0]); continue; } } } /* ]]> */ </script> <input type="checkbox" name=".lib_comp" id="lib_comp" value="1" /> The first case that i showed in my code is a radio button, and it passes correctly, i just wanted to show the "format" i was using in a working sense. The 2nd case is an example of the check boxes. Thanks for looking at this, and giving any suggestions you might have! Hi, I have what I assume started as a simple error and then trying to fix it I think I have made things so complicated I've become confused. I have two fields, a drop down list and a text field, when someone clicks on a value in a drop down list (I will show the results eventually but at the moment) I just want the result to echo in my getCategory.php and the same for the text field. Both php pages are currently being called. And at the moment contain $_REQUEST['category'] and $_REQUEST['ProductName'] respectively. Nothing is being echoed. I know the below code is wrong, but the more I try to correct it the worse it gets so I thought I would just leave it as is before I made it worse. Code: <script type="text/javascript"> function loadXMLDoc1(File,ID,Msg){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { try{ xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; } } var params=Msg; xmlhttp.open("POST",File,true); xmlhttp.setRequestHeader("Pragma", "Cache-Control:no-cache"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Content-length", params.length); xmlhttp.setRequestHeader("Connection", "close"); xmlhttp.send(params); } </script> </head> <body> <label>Search by Category: </label> <select name="category" id="category" onchange='loadXMLDoc1("getCategory.php","txtHint","category")' class="input"> <option value="please select" selected"selected">Please Select</option> <option value="Clothes" name="Clothes" id="Clothes">Clothes</option> <option value="Bags" name="Bags" id="Bags">Bags</option> <option value="Hats" name="Hats" id="Hats">Hats</option> </select> <br /> <br /> <label>Search by name: </label> <input type="text" class="input" name="ProductName" id="ProductName" value="Search" size="30"/> <input type="button" value="Search" onclick="loadXMLDoc1('getProductName.php','txtHint', ProductName='(this.value)')" /> <br /> <br /> <div id="txtHint"></div> Dear all, I'm passing the variables myTitle and myLink to form.php using javascript. This is the way I'm doing it: Code: <a href='form.php?title=" + myTitle +"&link="+myLink+">Click me</a> It's working great but sometimes myTitle and myLink contain the plus character (+). When this happens it's not passed. In the case of the title, it's just a problem of looks but in the case of the link, well, the link won't work without the character. As an example if the title is: Laptop + Accessories What is passed is: Laptop Accessories What can I do to pass also the plus character?? Thanks a lot!! I have the following work in progress: PHP Code: var radiolist = []; var labellist = []; var rps; var tablecells = []; //function taken from JavaScripter.net which will return a hex value for the color function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)} function toHex(N) { if (N==null) return "00"; N=parseInt(N); if (N==0 || isNaN(N)) return "00"; N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N); return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16); } //this function will add all the radio buttons to an array function getRadios(){ var inputs = document.getElementsByTagName('input'); for (i=0; i<inputs.length; i++){ if (inputs[i].type === 'radio'){ radiolist.push(inputs[i]); } } } //this function will add all labels of the "LabelWrapper" class to an array function getLabels(){ var inputs = document.getElementsByTagName('span'); for (i=0; i<inputs.length; i++){ if (inputs[i].className === 'LabelWrapper'){ labellist.push(inputs[i]); } } } getRadios(); getLabels(); //alert("There are " + radiolist.length + " radios"); //alert("There are " + labellist.length + " statements"); rps = radiolist.length / labellist.length; //alert("There are " + rps + " radios per statement") //this function will shade cells depending on their class name function identifyCells(){ var cells = document.getElementsByTagName('td'); for (i=0; i<cells.length; i++){ for (j=3; j<(rps+4); j++){ var tclass = "c" + j; if ((cells[i].className === tclass + " ") || (cells[i].className === tclass + " last ")){ xred = Math.round((j-2) * 255/(rps)); xblue = Math.round((j-2) * 255/(rps) - 50); xgreen = Math.round(50 + (rps-j+4) * 255/(rps)); xcolor = "#" + RGBtoHex(xred,xgreen,xblue); cells[i].setAttribute('col',xcolor); cells[i].addEventListener('mouseover',highlightCells,false); cells[i].addEventListener('mouseout',clearHighlights,false); } } } } } //this function will highlight all preceding cells in the same row function highlightCells(){ var y = this.getAttribute('col'); var z0 = this.className.split("c"); //split the classname in two so that we can use parseInt function var z = parseInt(z0[1]); this.style.backgroundColor = y; var cellfamily = this.parentNode.childNodes; for (i=0; i<cellfamily.length; i++){ cellname = cellfamily[i].className.split("c"); cellnum = parseInt(cellname[1]); if (cellnum > 3 && cellnum < z){ cellfamily[i].style.backgroundColor = y; } } } function clearHighlights(){ var z0 = this.className.split("c"); var z = parseInt(z0[1]); this.style.backgroundColor = "transparent"; var cellfamily = this.parentNode.childNodes; for (i=0; i<cellfamily.length; i++){ cellfamily[i].style.backgroundColor = "transparent"; } } identifyCells(); FireFox is giving me the "missing ) after argument list" at the following line: function highlightCells(){ I can't figure out why I am getting an error. The code was 'working' before and I was able to get the highlighting on the table cells, but I don't know what I did that caused the issue. Any help would be greatly appreciated. I'm trying to figure out why this doesnt work and how it will... The current script is as follows: Code: <script type="text/javascript"> function ReturnValueFromPopup(returnValue) { var imageURL = returnValue; } function SimpleTextEditor(id, objectId) { if (!id || !objectId) { alert("SimpleTextEditor.constructor(id, objectId) failed, two arguments are required"); } var self = this; this.id = id; this.objectId = objectId; this.frame; this.viewSource = false; this.path = ""; // with slash at the end this.cssFile = ""; this.charset = "iso-8859-1"; this.editorHtml = ""; this.frameHtml = ""; this.textareaValue = ""; this.browser = { "ie": Boolean(document.body.currentStyle), "gecko" : (navigator.userAgent.toLowerCase().indexOf("gecko") != -1) }; this.init = function() { if (document.getElementById && document.createElement && document.designMode && (this.browser.ie || this.browser.gecko)) { // EDITOR if (!document.getElementById(this.id)) { alert("SimpleTextEditor "+this.objectId+".init() failed, element '"+this.id+"' does not exist"); return; } this.textareaValue = document.getElementById(this.id).value; var ste = document.createElement("div"); document.getElementById(this.id).parentNode.replaceChild(ste, document.getElementById(this.id)); ste.id = this.id+"-ste"; ste.innerHTML = this.editorHtml ? this.editorHtml : this.getEditorHtml(); // FRAME if (this.browser.ie) { this.frame = frames[this.id+"-frame"]; } else if (this.browser.gecko) { this.frame = document.getElementById(this.id+"-frame").contentWindow; } this.frame.document.designMode = "on"; this.frame.document.open(); this.frame.document.write(this.frameHtml ? this.frameHtml : this.getFrameHtml()); this.frame.document.close(); insertHtmlFromTextarea(); } }; function lockUrls(s) { if (self.browser.gecko) { return s; } return s.replace(/href=["']([^"']*)["']/g, 'href="simpletexteditor://simpletexteditor/$1"'); } function unlockUrls(s) { if (self.browser.gecko) { return s; } return s.replace(/href=["']simpletexteditor:\/\/simpletexteditor\/([^"']*)["']/g, 'href="$1"'); } function insertHtmlFromTextarea() { try { self.frame.document.body.innerHTML = lockUrls(self.textareaValue); } catch (e) { setTimeout(insertHtmlFromTextarea, 10); } } this.getEditorHtml = function() { var html = ""; html += '<iframe id="'+this.id+'-frame" frameborder="0"></iframe>'; return html; }; this.getFrameHtml = function() { var html = ""; html += '<html><head></head><body></body></html>'; return html; }; this.execCommand = function(cmd, value) { if (cmd == "insertimage" && !value) { //var imageUrl = prompt("Enter Image URL:", ""); window.displayWindow(); } else if(cmd == "imageURL" && value){ alert(value); this.frame.focus(); this.frame.document.execCommand(cmd, false, value); this.frame.focus(); } }; this.isOn = function() { return Boolean(this.frame); }; this.getContent = function() { try { return unlockUrls(this.frame.document.body.innerHTML); } catch(e) { alert("SimpleTextEditor "+this.objectId+".getContent() failed"); } }; this.submit = function() { if (this.isOn()) { if (this.viewSource) { this.toggleSource(); } document.getElementById(this.id).value = this.getContent(); } }; } </script> <textarea id="myfield" name="myfield" style="font-family:Arial;font-size:12px;"></textarea> <script type="text/javascript"> var ste = new SimpleTextEditor("myfield", "ste"); ste.init(); </script> <script type="text/javascript"> function insertimage(){ var imgURL = document.getElementById('imageurl').value; ste.execCommand("imageURL", imgURL); } function CallWindowOpener(returnValue){ if (typeof ReturnValueFromPopup == 'function'){ ReturnValueFromPopup(returnValue); } } </script> <input name="imageurl" id="imageurl" type="text" /> <input name="Submit" type="button" onClick="insertimage();" value="Submit Image Url"/> When inserting anything into the imageurl textbox in the bottom of the script and submitting it I get an invalid argument error regarding to this line: this.frame.document.execCommand(cmd, false, value); within the: else if(cmd == "imageURL" && value){ In the end of the first javascript... Can anybody tell me how to get passed this please... Thanks in advance ;-) Code: function get_dims() { winH = getH(); winW = getW(); //alert(document.body.offsetHeight); document.getElementById('bgimg').width = winW; document.getElementById('bgimg').height = winH; document.getElementById('bgimgwrap').width = winW; document.getElementById('bgimgwrap').height = winH; var h = document.getElementById('header').offsetHeight; document.getElementById('layerimg').width = winW; document.getElementById('layerimg').height = (winH-h); document.getElementById('layerimg').style.top = h+"px"; document.getElementById('page').style.top = (document.getElementById('page').offsetTop + h)+"px"; document.getElementById('main').style.width = (winW*7)+"px"; document.getElementById('child').style.top = winH+"px"; document.getElementById('child').height = (winH-h)+"px"; var td = document.getElementsByTagName('td'); for(i = 0; i < td.length; i++) { td[i].width = winW+"px"; td[i].height = (winH-h)+"px"; \\this is the line with the error i have tried all sorts of different things with it to no avail } } function getH() { if (parseInt(navigator.appVersion)>3) { if (navigator.appName=="Netscape") { winH = window.innerHeight; } if (navigator.appName.indexOf("Microsoft")!=-1) { winH = document.body.offsetHeight; } } return winH; } function getW() { if (parseInt(navigator.appVersion)>3) { if (navigator.appName=="Netscape") { winW = window.innerWidth; } if (navigator.appName.indexOf("Microsoft")!=-1) { winW = document.body.offsetWidth; } } return winW; } I'm trying to get some basic javascript down so I can have my text come in from both the top and the bottom of the screen when the page loads. It's working just fine in Firefox, but in IE it stops with an "invalid argument" error. The problem comes on this line: Code: document.getElementById('part1').style.top = down[part1Position] + "px"; Here's the whole code in my separate .js file. Code: var part1Position = 0; var part2Position = 0; var downPosition = -19; var upPosition = 800; var down = new Array(); var up = new Array(); for(var i = 0; i < 91; ++i) { down[i] = downPosition; downPosition += 3; } for(var x = 0; x < 184; ++x) { up[x] = upPosition; upPosition -= 3; } function part1Move(){ document.getElementById('part1').style.top = down[part1Position] + "px"; ++part1Position; /*if (part1Position == 79) part1Position = 79;*/ } function part2Move() { document.getElementById('part2').style.top = up[part2Position] + "px"; ++part2Position; /*if (part2Position == 83) part2Position = 83;*/ } function startMoving() { setInterval("part1Move()",1); setInterval("part2Move()",1); } Any help would be greatly appreciated! I'm stumped. Hi guys , i have this function that allows me to hide a <div ID="ID1"> . function hide(X) { document.getElementById('X').style.visibility='hidden'; } <p><a href="#" onclick="hide('ID1');">show me/</a></p> <div ID="ID1" style="visibility:hidden">This is the content</div> the issue the function only works when i change X by ID1. i want to make it for any ID called with the function by assigning any DIV "ID" as an argument. any help ? thanks Hi ... i am trying to run my website but when i am accessing through the link....i am getting missing ) after argument list .it showing the following peace of code in the firebug.... missing ) after argument list else{$("input[id^=channelPid_]")\n can anyone help me to resolve this issues..its been three days i am working on it but no clue... thanks in advance Hi, So I'm testing my webpage in IE8. In firefox it looks and runs greag, but in IE 8, one issue I'm having is this: I have a button that opens a popup window. Works fine in Firefox, but I get 'invalid argument' error in IE8 and the window does not open. I've enabled at a whim some scripting things in the Internet Options hoping that would resolve the issue, but not so. Here's the code. The "invalid argument" occurs on the window.open call. Code: function open_report() { createURL(); var report_vars = created_URL; report_vars = report_vars.substr(69); report_array = report_vars.split('='); var from_d = report_array[2].substr(0,10); var to_d = report_array[3].substr(0,10); window.open('detailedreport.shtml' + report_vars, 'My Site | Detailed Report - ' + from_d + ' to ' + to_d, 'title=yes, status=no, toolbar=no, location=no, menubar=no, scrollbars=yes, modal=yes, alwaysRaised=yes, width=' + window.outerWidth / 1.1 + ', height=' + window.outerHeight); } In addition, is there any way to have that tile I've given it, "my Site..." appear in the window header? Right now it's not appearing at all in either browser. Thanks for reading! Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> Jackhammer </title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <script type="text/javascript"> /* <![CDATA[ */ var jackhammers = new Array(11); var curJackhammer = 0; var direction; var begin; jackhammers[0] = "jackhammer0.gif"; jackhammers[1] = "jackhammer1.gif"; jackhammers[2] = "jackhammer2.gif"; jackhammers[3] = "jackhammer3.gif"; jackhammers[4] = "jackhammer4.gif"; jackhammers[5] = "jackhammer5.gif"; jackhammers[6] = "jackhammer6.gif"; jackhammers[7] = "jackhammer7.gif"; jackhammers[8] = "jackhammer8.gif"; jackhammers[9] = "jackhammer9.gif"; jackhammers[10] = "jackhammer10.gif"; function bounce() { if(curJackhammer == 10) curJackhammer = 0; else ++curJackhammer; /* Firefox does not register an error with the line of code below, but other browsers do . . . It looks like it is a typo left over from the slightly more advanced technique in 10-4 where jackhammers.src is defined. Also, were you to comment out the final line in this function you would see the animation does not work. In browsers other than Firefox which apparently just ignores this code and no animation occurs, the image element is assigned the source value of "undefined" and of course no image is named "undefined". */ document.getElementsByTagName('img')[0].src = jackhammers[curJackhammer].src; if(curJackhammer == 0) direction = "up"; else if(curJackhammer == 10) direction = "down"; document.getElementsByTagName('img')[0].src = jackhammers[curJackhammer]; } function startBouncing() { if(begin) clearInterval(begin); begin = setInterval("bounce()",90); } /* ]]> */ </script> </head> <body> <h1> Jackhammer Man </h1> <p> <img src="jackhammer0.gif" height="113" width="100" alt="Image of a man with a jackhammer." /> </p> <form action="" enctype="text/plain"> <p> <input type="button" value="Start Bouncing" onclick="startBouncing();" /> <input type="button" value="Stop Bouncing" onclick="clearInterval(begin);" /> </p> </form> </body> </html> My teacher insists that the above code is valid (straight out of our book). He says this because (I'm guessing) it runs okay in Firefox and other browsers. It also throws a ton of error messages in Chrome and makes no logical sense. We define the values of the jackhammer array as literal strings, and then the book instructs us to change the source of the image element on the page to jackhammers[i].src. It then has us change the source of the image element again, correctly at the end of the function. It also has us create a useless variable: "direction" (and I say useless because we never use it, it is just fluff I guess). On a side note, would some of you guys like to check out this animation I created here and let me know what you think. Thanks guys. Hi, I've had problems in the past understanding this, however, after reading this tutorial, I understand. In some languages, like VB6, I notice the "byVal" and the "byRef" is specifically used. In javascript, I don't notice those specifics typed in functions. Is the "default" by value when using in a function to change a parameter? If it is, what is the syntax for using by reference, or is that ever used? My question arises from this notation taken from here: Quote: Note that it is the value that a has at the time that it is passed into the function that gets substituted into the argument and not the value that the original variable has at that point in the processing. It is the values in the parameters that the function uses and not the variables. This is called pass by value . In those languages where you can pass the actual variable into the function instead of just passing its value the method used to do so is called pass by reference . Had we been able to pass the variables into the function by reference rather than by value then the final value in b would have been -16 instead of -14. Here is the example (passing by value): Code: function myfunction(y, z) { a += y; b -= z; } var a = 0; var b = 10; var c = 3; var d = 4; var e = 2; myfunction(c, d); myfunction(d, e); myfunction(9, 2); myfunction(b, a); Results: myFunction(c, d); output: 0 + 3 = 3(y), 10 - 4 = 6(z) myFunction(d, e); output: 3 + 4 = 7(y), 6 - 2 = 4(z) myFunction(9, 2); output: 7 + 9 = 16(y), 4 - 2 = 2(z) myFunction(b, a); output: 2 + 16 = 18(y), 2 -16 = -14(z) Thanks! |