JavaScript - Javascript Help...i Don't Understand This
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. Similar TutorialsHi, 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 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. 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'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") 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 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 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 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! 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?
This 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 all - I am updating a website at my new place of work, changing the form they have for requesting information on the company. I am trying to understand some JavaScript I found while googling forms. I am unsure of the significance of the following vertical code marks preceeding the form.name.value: Code: var msg = "form.name.value = "+document.registar.name.value; alert(msg); var form = document.registar; if (form.name.value=="Name" || form.name.value == "" || form.email.value == "E-Mail Address" || form.email.value == "" || form.phone.value == "" || form.password1.value == "" || form.password2.value == "" || form.selection.value == "" || form.sq_answer.value == "Question Answer" || form.sq_answer.value == "" || form.radanswer.value == "") { window.alert("You must enter all fields above."); return false; } else return true; } Thanks in advance. Rick I want to have another go at Javascript. I have several books on the subject but I find that my eyesight is a major problem. Therefore I want to try an on-line solution, preferably free. I have Googled, but there are so many that I am almost dizzy with the choices. Perhaps someone could recommend one. Not too fussy visually. My knowledge is VERY basic. Frank Hello! I am trying to find a script that allows you to open multiple browser tabs and then close each of those tabs, either one by one or all at once. Does anyone know how to do this please? Thanks so much for your help. Does anyone know how to make URL links that use Javascript still work when users have Javascript disabled on their browser? The only reason I'm using JS on a URL is because my link opens a PDF file, and I'm forcing it not to cache so users have the latest version. I tried the <script><noscript> tags, but I'm not sure if I'm using it correctly, as my URL completely disappears. Below is my HTML/Javascript code: <p class="download"> <script type="text/javascript">document.write("<span style=\"text-decoration: underline;\"><a href=\"javascript:void(0);\" onclick=\"window.open( 'http://www.webchild.com.au/mediakit/Direct_Media_Kit_Web.pdf?nocache='+ Math.floor( Math.random()*11 ) );\" >The Child Magazines Media Kit</a></span> (PDF 1 MB) ");</script> <noscript><span style="text-decoration: underline;"><a href="http://www.webchild.com.au/mediakit/Direct_Media_Kit_Web.pdf" >The Child Magazines Media Kit</a></span> (PDF 1 MB)</noscript> </p> Thanks for any help, Michael Hi, I have the following code snippet: test.html ====== <script language="javascript" type="text/javascript"> var testVariable = "test"; </script> <script language="javascript" type="text/javascript" src="test.js"> </script> test.js ===== var testVariable = window.top.testVariable; In firefox, I'm able to access testvariable defined within test.html in test.js. But in chrome, test.js couldnot get the window.top.testVariable field defined in test.html. Can any one please let me know how i can make it work in chrome?. Am i missing something here?. Hi Guys, I am new at JavaScript and start to do some tutorials.What I am trying to do here is prompting user to input a name and if the name was valid the page(document) will display with all objects like the button.But if user enter a wrong name then the button will be disabled! I create the following code but it did not work <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>New Web Project</title> <script language="JavaScript" type=""> function changeColor(){ document.bgColor = "Gray"; } </script> </head> <body> <script language="JavaScript" type="text/javascript"> var person = ""; person = prompt('What is Your Name:'); if (person == "Foo") { document.write("<h1 />Welcome " + person); document.bgColor = "Yellow"; } else { document.write("<h1 />Access Denied!!!!"); document.bgColor = "Red"; document.getElementById("gree").disabled = true; } </script> <div> <p/><input id="gree" type="button" value="Gray " onClick="changeColor();"> </div> </body> </html> as you can see I used the: document.getElementById("gree").disabled = true; but it did not work , could you please give an idea how I can solve this problem? Thanks |