JavaScript - Trying To Understand Functions
I'm sorry if this is asking too much I just find it much easier to learn interacting directly with experience coders but I'm tryign to understand functions better and wanna make sure I got it right.
the function syntax looks like this right Code: function functionname() { function code } the perameters kinda confuses me, inside them can go variables right? but where do you declare those variables? before the function or in the function? is it like this? Code: function functionname(x) { var x="Hello" } if thats right do you write the code you want to execute below the variables? like under var x I wanna make a alert I would write alert("x") Similar TutorialsThis is a little hard to explain so I'm posting an example. Code: //NESTED FUNCTION I'M USING TO DEMONSTRATE MY QUESTION function foo(a) { this.x = 5; //USED TO SET THE VALUE OF X if( a == 0 ) return function(z) { return x = z; } //USED TO RETRIEVE THE VALUE OF X else if( a == 1 ) return function() { return x; } } //MAKES setX THE SETTER FUNCTION var setX = foo(0); //MAKES getX THE GETTER FUNCTION var getX = foo(1); print( "setX(25), not an instance: " + setX( 25 ) ); print( "getX(), not an instance: " + getX() ); print( "" ); //CREATES AN OBJECT INSTANCE USING FOO AS CONSTRUCTOR var q = new foo(); print( "value of x in object instance: " + q.x ); print( "" ); print( "setX(25), not an instance: " + setX( 25 ) ); print( "getX(), not an instance: " + getX() ); This code will output: Code: setX(25), not an instance: 25 getX(), not an instance: 25 value of x in object instance: 5 setX(25), not an instance: 25 getX(), not an instance: 25 Observations: It seems like this.x actually has two meanings. 1)x becomes a member of the "Function" object foo(). 2)x becomes a part of the constructor for prototype class foo. But why then does x revert back to the original value of 5 when I use foo as a constructor? Does javascript automatically save the original value on creation for a reason? What is going on behind the scenes to make this happen? Is this behavior part of an ontological model that makes sense? Similarly, if I change "this.x" to "var x" I can access the value of x but I can't change it. Not that that I should be able to, the syntax "var x" doesn't make x a member of foo anyway. But I'm still having trouble classifying the relationship "var x" has to the function. Anyways this is more of a tangent. My main question is above but if anyone has something to say about this, I'd be interested to hear it. It seems like all these behaviors have rules to them, but there is no conceptual model to think through that guide these behaviors. Or maybe I'm just ignorant. Enlighten me. Hi, I have written a number of functions designed to return frequency data on 1000 randomly chosen numbers using different math functions for the rounding. I would like to include all of these functions within the wrapper of another function so that only one call is needed to get returns from all of the 'inner' functions. However, while each of the functions works in isolation, the moment I wrap them in another function they stop working. The following code is one of the functions 'frequencyWrapperOne' that has been wrapped in the function 'testWrapper'. A call to testWrapper does nothing. Can anyone see what I'm doing wrong? Code: function testWrapper() { function frequencyWrapperOne() { var numberArrayOne = new Array(0,0,0); for (var i = 0; i < 1000; i = i + 1) { var chosenNumber = Math.floor(Math.random() * 3); if (chosenNumber == 0) { numberArrayOne[0] = numberArrayOne[0] + 1; } if (chosenNumber == 1) { numberArrayOne[1] = numberArrayOne[1] + 1; } if (chosenNumber == 2) { numberArrayOne[2] = numberArrayOne[2] + 1; } } return window.alert(numberArrayOne.join(',')); } } testWrapper(); Thanks. Hi, I am very new to JavaScript. I am trying to understand what this does and I am hoping someone here can help. A user fills in some data for a search and results are displayed on the page but there is no option to save the results. I would like to be able to just dump them into a text file, but I have no way of changing this code.. so I'm thinking if I could find out specifically what this is doing then maybe some other tool or command can be used to get the results and save them into a file (maybe wget?? or something). Here is the code: <script type="text/javascript">//<![CDATA[ $(document).ready(function() {$.get('\x2fTraceMessage.mvc\x2fAsyncMessageList\x2f736251', { s:'google\x40google.com', r:'yahoo.com', d:'1\x2f10\x2f2012 2\x3a18\x3a37 AM', e:'1\x2f16\x2f2012 2\x3a18\x3a37 PM', i:'', a:'-5' }, function(data) { $('#message_trace_list').html(data); }); }); //]]></script> Thanks in advance for any help! Hey, so I've been trying (in vain) to get my head around how this little script is doing what it's doing. Code: var msg = "From Person (*Account): .tp" var reg = /^.*\(\*(\w*)\)(\swhispers)?\s*:\s\.(.*)$/gi; if (msg.match(reg)) { var sender = msg.replace(reg, "$1"); var command = msg.replace(reg, "$3"); Say(sender+" told me to "+command); Delay(500); } So there is this message that comes in, and somehow this script is able to just take the characters after the . as well as getting the word between (* and ) . And all this from just one line of code?? If you've got some free time and are able to help me understand what the "var reg" line is doing I'd be so thankful. Feel free to assume I'm new at Javascript, I've done a little C and VB, but never java. Thanks in advance I have seen this code-piece different places - to use to make a webpage redirect if it is a mobilephone. I don't quit understand the code - especially the line: if (redirectagent.indexOf(redirect_devices[i]) != -1) - why -1 ? Please help me - I would be so thankful. Code: <script language=javascript> var redirectagent = navigator.userAgent.toLowerCase(); var redirect_devices = ['vnd.wap.xhtml+xml', 'sony', 'symbian', 'nokia', 'samsung', 'mobile', 'windows ce', 'epoc', 'nitro', 'j2me', 'midp-', 'cldc-', 'netfront', 'mot', 'up.browser', 'up.link', 'audiovox', 'blackberry', 'ericsson', 'panasonic', 'philips', 'sanyo', 'sharp', 'sie-', 'portalmmm', 'blazer', 'avantgo', 'danger', 'palm', 'series60', 'palmsource', 'smartphone', 'rover', 'au-mic', 'alcatel', 'ericy', 'vodafone', 'wap1', 'wap2', 'teleca',, 'lge', 'lg-', 'iphone', 'android', 'htc', 'dream', 'webos', 'bolt', ]; for (var i in redirect_devices) { if (redirectagent.indexOf(redirect_devices[i]) != -1) { location.replace("http://www.example.com"); } } </script> I'm totally new when it comes to JavaScript and I'm trying to learn new things. Here I found the codes I tried it and it works but I would like to have comments for the code to understand how they have proceeded. can someone help me and explain these codes with comments? I really appreciate it. Code: var config = { "tags": "vfx+compositing", "user": "andreasl", "scriptTagTarget": "scriptTagDiv", "deliciousTarget": "deliciousLinks", "callbackFunction": "fetchDelicious" }; window.onload = function() { var url = 'http://feeds.delicious.com/v2/json/' + config.user + '/' + config.tags + '?callback=' + config.callbackFunction; var scriptDiv = document.getElementById(config.scriptTagTarget); addScriptTag(url, scriptDiv); }; function addScriptTag(url, scriptDiv) { if (scriptDiv.hasChildNodes()) { scriptDiv.removeChild(scriptDiv.firstChild) }; var scriptElement = document.createElement('script'); scriptElement.setAttribute('src', url); scriptDiv.appendChild(scriptElement); } function fetchDelicious(json) { var html = ""; for (var i = 0; i < json.length; i++) { var uri = json[i].u; var description = json[i].d; var tags = json[i].t; //array var time = json[i].dt; //var n = json[i].n; //new? var author = json[i].a; var bHtml = "<li><a href=\":u\">:d</a>:t</li>".replace(":u", uri).replace(":d", description); var tagHtml = ""; for(var n = 0; n < tags.length; n++) { tagHtml += "<li><a href=\"http://delicious.com/:u\">:d</a></li>".replace(":u", [author,tags[n]].join("/")).replace(":d", tags[n]); } tagHtml = "<ul>" + tagHtml + "</ul>"; html += bHtml.replace(":t", tagHtml); } html = "<ul>" + html + "</ul>"; document.getElementById(config.deliciousTarget).innerHTML = html; } I sometimes see that some people use this expression: event = event || window.event Why people need to do this? What does it mean? <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script src="https://code.oovoo.com/webrtc/oovoosdk-0.0.7.min.js"></script> <script type="text/javascript"> function TestId() { WebService1.GetAppId(onSuccess, onFailure); } //situation 1 function onSuccess(result) { alert(result); } //situation 2 //function onSuccess(result) { // return result; //} function onFailure(result) { alert("Error Invoking the Web Service..."); } </script> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager runat="server" ID="scriptManager"> <Services> <asp:ServiceReference Path="~/WebService1.asmx" /> </Services> </asp:ScriptManager> <div> <video id="localVideo" style="width: 300px; height: auto;" autoplay muted></video> </div> </form> <script type="text/javascript"> TestId(); // This line is working in situation 1 (onSuccess method situation 1) //BUT, WHEN I COMMENT METHOD IN SITUATON 1 AND UNCOMMENT SITUATION2 THEN LINE BELOW IS NOT WORKING var a = TestId(); //THIS LINE IS NOT WORKING WHEN SITUATION2 IS ACTIVE </script> </body> </html> I am taking a class to learn javascript, and this book has so many typo's, just typing in the code they suggest, I can never get this to work. I am NOT a programmer...but a 50 something year old person, wanting to learn more about web design. I applaud those who actually understand javascript. I think it is amazing how it can do so many things to a web page. If you can help, I certainly would appreciate it. This is the code for the website: Code: <html> <head> <!-- New Perspectives on JavaScript Tutorial 3 Case Problem 1 The Lighthouse Author: Date: Filename: clist.htm Supporting files: lhouse.css, list.js, logo.jpg --> <title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="title"> <img src="logo.jpg" alt="The Lighthouse" /> The Lighthouse<br /> 543 Oak Street<br /> Delphi, KY 89011<br/> (542) 555-7511 </div> <div id="data_list"> </div> <div id="totals"> </div> </body> </html> This is the javascript: Code: <html> <head> <!-- New Perspectives on JavaScript Tutorial 3 Case Problem 1 The Lighthouse Author: Date: Filename: clist.htm Supporting files: lhouse.css, list.js, logo.jpg --> <title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="title"> <img src="logo.jpg" alt="The Lighthouse" /> The Lighthouse<br /> 543 Oak Street<br /> Delphi, KY 89011<br/> (542) 555-7511 </div> <div id="data_list"> </div> <div id="totals"> </div> </body> </html> This is the cascading style sheet: Code: /* New Perspectives on JavaScript Tutorial 3 Case Problem 1 Filename: lhouse.css This file contains styles used in the clist.htm file */ #title {width: 600px; text-align:right; color: rgb(192,142,90); border-bottom: 1px solid rgb(232,182,130); margin-bottom:9px; font-size:10pt; height: 100px} #title img {float: left} #data_list {float: left} table {font-size: 8pt; font-family: Arial, Helvetica, sans-serif; border: 1px solid brown; margin-right: 20px} .yellowrow {background-color: yellow} th {color: white; background-color: brown; padding: 2px 5px} td {vertical-align: top; padding: 2px 5px} .amt {text-align: right} #totals table {font-size: 12pt} #totals table th {text-align: left} #totals table td {text-align: right; width: 75px} #totals table #sumTitle {text-align: center; background-color: yellow; color: black} 1. suppose to add a script element that points to the list.js file 2. Under this element insert another script element that contains the function amountTotal(). The purpose of this is to return the sum of all of the values in the amount array. There are no parameters for this fuction. Then add the following commands to the function: Declare a variable named total, setting its initial value to 0. Create a for loop that loops through all of the values in the amount array. At each iteration of the loop add the current value of the array item to the value of the total variable. Then after the for loop is completed, return the value of the total variable. 3. locate the div element with the id "data_list" Within the div element add a script element that contains the following commands: a. write the following code to the document: <table border='1' rules='rows' cellspacing='1'> <tr> <th>Date</th><th>Amount</th><th>First Name</th><th>Last Name<.th><th>Address</th> </tr> B. Create a for loop in which the counter variable starts at 0 and while the counter is less than the length of the amount array increase the counter in increments of 1. C. Every other row in the data list is to be displayed with a yellow background; to do this, within the for loop insert an IF condition that tests whether the counter variable is divisible evenly by 2 using the % modulus operator. If the counter variable is divisible by 2 write the following HTML tag: <tr> Otherwise write the tag, <tr class='yellowrow'> D. next within the loop write the following html code to the document: <td>date</td> <td class='amt'>amount</td> <td>firstName</td> <td>lastName</td> where date, amount, firstName and lastName are the values of the date, amuont, firstName, lastName arrays fro the index indicated by the current value of thefor loop's counter variable. E. Finally within the for loop, write the html code <td>street<br/> city, state zip </td> </tr> where street, city, state and zip are the values of the street, city state and zip arrays for the current index value. 4. go to the div element with the id "totals" insert a script element that writes the following html code to the document. <table border='1' cellspacing='1'> <tr> <th id='sumTitle' colspan='2'> summary </th> </tr> <tr> <th>Contributors</th> <td>contributions</td> </tr> <tr> <th>Amount</th> <td>$total</td> </tr> </table> where contributions is the length of the amount array and total is the value returned by the amountTotal() function you created earlier. Supposedly when complete, a list of 35 contributions totalling $5175 is displayed on the table and that alternate rows of the contributor list are displayed with a yellow background. If this makes any sense to someone who likes a challenge...I would appreciate hearing from you. I feel like I am taking an exam of a foreign language and I missed all the classes prior to the exam. We are getting NO (ZERO) help from teachers. Hi all, I've been working with the book "DOM Scripting: Web Design with JavaScript and the Document Object Model, Second Edition" It's available on the Safari ebooks library collection, which I get a subscription to through my school. It seems like a really good book, but in chapter 7 they get to this function and don't really explain it much: Code: function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } I understand the first part, where it stores window.onload into the variable oldonload, and then checks to see if window.onload is already handling a function. But I don't understand why it calls the variable oldonload(which then turns into a function with the (); right?) and then the func parameter somehow doesn't get overwritten. If anyone could explain this or point me in the direction of an online article or instructional book that might explain it better, I would really appreciate it. Ok here is what I have so far, my ending part of my Call Function I think is ok. for my main function. I think I misplaced the { and } I will show you all the codes I have for my main function this is what I have I think I did misplace something but I can not pin point where that one small things should be Code: unction showResults(race,name,party,votes) { // script element to display the results of a particular race var totalV = totalVotes(votes); document.write("<h2>" + race + "</h2>"); document.write("<table cellspacing='0'>"); document.write("<tr>"); document.write("<th>Candidate</th>"); document.write("<th class ='num'>Votes</th>"); document.write("<th class='num'>%</th>"); document.write("</tr>"); } for (var i=0; i < name.length; i++) { document.write("<tr>"); document.write("<td>" name[i] + "(" + party[i] + ")</td>"); document.write("td class='num'>" + votes[i] + "</td>"); var percent=calcPercent(votes[i], totalV) document.write("<td class='num'>(" + percent +"%)</td>"); createBar(party[i],percent) document.write("</tr>"); } document.write("</table>"); } </script> Just wondering if i misplaced any ; or { or } anywhere suggestions? Here is my call function Code: <script type="text/javascript"> showResults(race[0],name1,party1,votes1); showResults(race[1],name2,party2,votes2); showResults(race[2],name3,party3,votes3); showResults(race[3],name4,party4,votes4); showResults(race[4],name5,party5,votes5); </script> I been going over this, I can not seem to figure out what { i might be missing? Thanks Is there a way to activate a function from another function? It has to be in the script tag, it can't be in the HTML section. Can I use something similar to this following code? If not, can anyone give me some help? I have tried to do it various ways, and have looked it up a few times, but to no avail. Can I use something similar to this following code? If not, can anyone give me some help? if (condition) {activate functionname();} Any help I can get would be appreciated. Thanks a lot to anyone who can help. Hi, I am using the following code to generate a temporary window: In the js: Code: var win=null; function NewWindow(mypage,myname,scroll){ settings='width=850,height=500,top=200,left=50,scrollbars=yes,location=yes,directories=no,status=no,menubar=no,toolbar=no,resizable=yes'; win=window.open(mypage,myname,settings); if(win.focus){win.focus();}} function hidestatus(){ window.status='' return true } And in the HTML: Code: <a href=\"http://www.support-focus.com/check.php?key=$sup_cd2\" onclick=\"NewWindow(this.href,'','yes','default'); return false\" onfocus=\"this.blur()\" > This code works , but I don't understand the mis-match or parameters This is passing four param: onclick=\"NewWindow(this.href,'','yes','default'); But this is only receiving three: NewWindow(mypage,myname,scroll) Is the last one (default) not counted for some reason ? The was able to move the scroll param (yes) out With this: onclick=\"NewWindow(this.href,'','default'); and NewWindow(mypage,myname) Which now leaves just two params and a default. Does anyone know why this appears to be unbalanced and also what the myname param does? ( do I need it ? can I get rid of the '' and the myname ? ) Thanks Hi, I inherited an html demo (used to show customers our product w/o being connected to a server). Was going through the Html files to update the dates and fields and it seems that on some html files, when I change a date <td>08/11/2008 </td> to <td>08/11/2011</td>, save and refesh, I start getting a bunch of JS errors when I try and log back into the demo. I'm not changing anything in the JS files, so I don't understand why the errors are occuring. I have a bunch of html files to change, and now, no matter which file I change (the dates, sample names, etc), I lose functionality on that particular page. I'm beyond frustrated with this - I've modified similar demos at other companies and never had a problem. Appreciate the help and assistance! i wrote like this: Code: var a = function b(){ return b; }; alert(a() === a ); and ie6~ie8 return false , ie9 chrome ff return true. how to explain it? and Code: var a = function b(){ }; alert( typeof b ); b is undefined in most of browser but is function in ie6~ie8, that's why? thx Ive searched on this board but cant find out why this doesn't work. Code: <script type="text/javascript"> function showSelected(val) if (val == "Nil") { document.getElementById('JustText').innerHTML='hi' } else { document.getElementById('selectedResult').innerHTML="<a href='mailto:" + val + "'>" + val + "</a><p>" } </script> What can I do to find out what the errors in the error console mean?
im no jQuery rookie but for the first time ...instead of simply writing out the animation jQuery('element').hide() in that way.... i instead needed to keep track of the functions so i wrote it like function hidetheElement() { jQuery('element').hide() } but now i need to run 2 of those functions together after a click ...for example jQuery('ClickedElement').click( movethelement,hidethelement ) see what i mean?....i dont know how to properly run two defined functions whats the proper syntax.... and here is my actual code for reference (its basically a menu link being clicked...hiding one page...and showing another....i needed to define the functions so if a menu link is clicked it could hide every other page first...by function....and then call a function to show the page Code: jQuery(document).ready( function() { jQuery('#ladiesmenu').click( previewoff,ladieson ); function previewoff() { jQuery('#preview').fadeOut(500); } function ladieson() { jQuery('#ladies').fadeIn(500); } Code: <html> <head> <script> //declare variable //var temp = 0; var Num = parseInt(prompt('Enter an Intger')); // starts the function factorial factorial(Num); //The function is declared function factorial(currentNumber) { if(currentNumber > 1) { //temp = temp + (currentNumber); factorial(currentNumber - 1); alert(currentNumber); } else { alert("here"); } } </script> </head> <body> </body> </html> This code is suppose to take the prompt number and keep subtracting one if > 1 but it seems to be not doing that at all and doing the else statement first then + till it gets to the prompt number. I have been staring at it for a while now and cant work it out. Thanks I would really like to thank the guys that have been helping me. I think my brain would have exploded otherwize. Some of the problems have been simple misspellings, but when you have been staring at the same thing for hours it can sorta slip by. HOPEFULLY this will be the last thing that I need some help with. Bascially Im not sure if Im using the function command properly. When Submit Details is click it should validate the form and then when Calculate is pressed calculate the form (obviously). I think maybe my var Array table is wrong? And the way the functions are set out doesnt seem it sit right. Code: <script type="text/javascript"> var element; var itemArray = new Array(); itemArray [0] = "Bike" //not sure if these are properly writen?// itemArray [1] = "TV" itemArray [2] = "iPod" itemArray [3] = "Car" var flag="OK"; var count = 0 document.write ("<form name='myform'><br><table>"); while (count <= 3) { if (count < 3) { document.write ("<tr><td><value>Enter money from " + itemArray [count] + " sale.</td><td><input type='text' name=" + itemArray [count] + "></td></tr>"); count++ } else { document.write ("<tr><td><value>Enter the price of " + itemArray [count] + ".</td><td><input type='text' name=" + itemArray [count] + "></td></tr>"); document.write ("<tr><td><input type='submit' value='Submit Details' onClick='validateform'</td></tr>"); document.write ("<tr><td><input type='submit' value='Calculate Details' onClick='calculateform'</td></tr></table></form>"); count++ } } function validateform() //<=== doesnt run { element=document.getElementsByTagName ('input'); for (counter=0; counter<element.length; counter++) { switch (element[counter].type) { case "submit": break; default: if (isNaN(element[counter].value) || (element[counter].value == "") ) { alert("You need to enter a number into " + element[counter].name); flag="NotOK" } else { Bike=element[0].value; TV=element[1].value; iPod=element[2].value; Car=element[3].value; } break; } } } function calculateform() //<=== Doesnt run either { if (flag=="OK") { if ( (Number(element[Bike])) && (Number(element[TV])) && (Number(element[iPod])) && (Number(element[Car])) ) //<========= Gets Bike is not defined error easy// { TotalMoney= parseFloat (Bike) + parseFloat (TV) + parseFloat (iPod) if (TotalMoney >= Car) { alert ("The total money is " + TotalMoney + " and the car price is " + Car + " and you can afford the car") } else { alert ("The total money is " + TotalMoney + " and the car price is " + Car + " and you cannot afford the car") } } } } </script> |