JavaScript - Change Css Property With Math
I have this simple manual photo slide show. It shows four photos and when you click the next button and it moves one photo over and one photo back for the previous button. I have to moving by changing the CSS property of 'left' by 195 pixels each move. So for it to move next it will subtract 195 pixels from the left property and for moving back it add 195 pixels to the left property. I have the code setup so when you click it changes the property of left to either -195 or 195 pixels but I need it so it actually does the math, not just give it a set value. But I don't know how to do that.
Code: function MM_changeProp(objId,x,theProp,theValue) { //v9.0 var obj = null; with (document){ if (getElementById) obj = getElementById(objId); } if (obj){ if (theValue == true || theValue == false) eval("obj.style."+theProp+"="+theValue); else eval("obj.style."+theProp+"='"+theValue+"'"); } } function nextPhoto() { MM_changeProp('fanThumbWrapOne','','left','-195px','DIV') } function prevPhoto() { MM_changeProp('fanThumbWrapOne','','left','195px','DIV') } so where you see -195px and 195px in the functions for nextPhoto and prevPhoto I need those to actually be functions where it subtracts 195px or adds 195px. Similar TutorialsFor the sample code: Code: <form name=form> <ul> <li><input type="text" onkeyUp="calc1();" name=x ></li> <li><input type="text" onkeyUp="calc2();" name=y ></li> </ul> </form> <script> function calc1() { document.form.y.value = (10 * document.form.x.value).toPrecision(5); } function calc2() { document.form.x.value = (0.1 * document.form.y.value).toPrecision(5); } </script> How can I use a checkbox to : (1) Upon check, change the current values to toExponential(5) format (2) Use a different script and/or function that would then calculate with toExponential(5) [as opposed to the hard coded toPrecision(5) in the current functions. (3) Upon unchecking, the result should should go back to Precision and change the function and/or script back to the original. I am and seem to remain newbie ... I have a JS script that presents a series of "pages" with different questions inside a single HTML file, by rewriting certain <div>s. I have an object like this that contains the questions and information about answer labels etc (the idea is that this should be easy to modify for someone who doesn't know JS): Code: var Questions = [ { "question" : "How good is this?", "labels" : ["excellent","very good","good","bad","very bad","awful"], "page" : 0 , "random" : false , "type" : "default", "varname" : "allgood" }, { "question" : Change[curCase]+"What do you think now?", "labels" : BetterLabels, "page" : 1 , "random" : true , "type" : "default", "varname" : "betteradapt" } ] This object is initialized when the page loads, and a function reads the total number of pages by getting the maximum number of the "page" property across elements. Later, the object is accessed by thenextQuestion() function which uses the "page" property to looks whether each element belongs on the current page , then reads out the properties and presents the question. This works okay. Now the tricky bit: For some questions, their text should be different depending on which case is currently on the screen (Change[curCase]). curCase is different on each page, an integer between 0 and Change.length. I cannot get this to work for the Questions object, probably because the Questions object has been already initialized when the page loaded. How can I get my function nextQuestion() to "re-evaluate" the property "question" for all the elements of the Questions objectwhen nextQuestion() is called , using the current value of "curCase"? nextQuestion() is longer, but the (i think!) crucial bits are he Look whether question belongs on current page and push it onto new array: Code: for (i=0; i < Questions.length; i++) { Questions[i].page = Questions[i].page; if ( Questions[i].page == BlockNum ) { // if the q belongs on the current page QuestionsObjectThisPage.push(Questions[i]); } } Then, extract an array containing the questions, which will then be presented: Code: for (i=0; i < QuestionsObjectThisPage.length; i++) { QuestionsThisPage.push(QuestionsObjectThisPage[i].question) ; } So what I'm looking for is something to change either of these two Object.push() functions so they don't simply take the value they find in the Questions (or QuestionsThisPage) object, but to re-evaluate the code for the "questions" property, taking into account the current value of curCase Phew. I found that really hard to describe; hope it's somewhat clear. Try to figure out how to change the css display property of a table, from hidden, to block outside of an iframe. //This data is outside of the iframe Code: <style> #table {display: hidden; z-index: 100;} </style> <table id='table' ><td> ......data</td></table> //This link is inside of an iframe Code: <script> function change(){ document.getElementById("table").style.display='block'; } </script> <a href='javascript:void(0)' onclick='change()'>Change</a> How can you add/substract two numbers in javascript if they are written out as words such as one|two|three|four|five|six|seven|eight|nine|ten. Code: if ((word[0].match(/one|two|three|4|five|six|seven|eight|nine|ten/)) && (word[1].match(/plus|add/)) && (word[2].match(/one|two|three|4|five|six|seven|eight|nine|ten/))) { document.result.result.value = "The answer is ?"; return true;} hey. im working on a facebook app.. this is what i got so far. PHP Code: <script language="JavaScript"> <!-- var theImages = new Array() theImages[0] = "http://img688.imageshack.us/img688/4787/logo1tq.jpg" theImages[1] = "http://img641.imageshack.us/img641/8292/logo2yex.jpg" theImages[2] = "http://img864.imageshack.us/img864/4097/logo3ik.jpg" theImages[3] = "http://img543.imageshack.us/img543/9046/logo4pu.jpg" theImages[4] = "http://img21.imageshack.us/img21/2567/logo5q.jpg" theImages[5] = "http://img842.imageshack.us/img842/696/logo6o.jpg" theImages[6] = "http://img85.imageshack.us/img85/7831/logo7k.jpg" var j = 0 var p = theImages.length; var preBuffer = new Array() for (i = 0; i < p; i++){ preBuffer[i] = new Image() preBuffer[i].src = theImages[i] } var whichImage = Math.round(Math.random()*(p-1)); function showImage(){ document.write('<img src="'+theImages[whichImage]+'">'); } //--> </script> <script language="JavaScript"> <!-- showImage(); //--> </script> now i want that the app posts the random image automaticlly to the useres timeline.. for example: if the random image is theImages [3] then it should post the image theimage [3] to the users timeline.. i see alot of facebook apps doing this.. thanks in advance I'm making a 3d pie chart. I have the points and the correct method to fill everything but when the slice rotates I want to make the outer edge filled, but in order to do that I have to figure out what math I use to find the leading edge. I made a picture to hopefully explin what I need to find. I figure it might be the tangent but I was hoping someone smarter than I could send me in the right direction. I just need someone to help me pinpoint my next step. Right now the rendering uses start and end angles to first make the top and bottom sections, fills them and then it makes an arc along the top of the slice from start to end then from end to start on the bottom slice and completes the polygon by going back the first point in the arc. I need to make two separate polygons if the end or start are further from the center than the( tangent?) point. Need some advice. Hope someone has an idea. I can't wrap my head around this at the moment so with the hope of finding someone willing to take a stab I am posting this to all of you. I need to create a savings ticker that shows $ saved per second. The data is as follows then = date script is created now = current date std = savings to date in $ avg = average savings per second in $ It would need to calculate the difference in time between then and now, convert that to an integer that can then be multiplied by avg then std would be added. thanks in advance Either I made an uh-oh, or there is a serious problem with Javscripts math functions. Math.sin(x) returns the sine of x in radians. Last time I checked, the sine of pi radians is 0, but in javascript: Code: Math.sin(Math.PI) // returns 1.2246467991473532e-16 Any idea why? Julian Just started to learn java & came up with the following, but can't get the math.round to work. Anyone able to tell me where I'm going wrong please ??? <p> <script type="text/javascript">// <![CDATA[ var metrics = { "mm" : 1, "cm" : 10, "m" : 1000, "inch" : 25.4, "foot" : 304.8 }; function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes) } function roundme(len, wid, sq){ math.round.len; wid = math.round(wid); sq = math.round(sq); alert(len); }; function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes) }; function changeme(id, action) { var val = document.getElementById("sizegroup"); if (val.style.display == 'none') { val.style.display = 'block' } else { val.style.display = 'none' } }; function convert(num, dec){ var val = document.getElementById("boxa").value; var val2 = document.getElementById("boxb").value; if(isNaN(val)){return val}; if(isNaN(val2)){return val2}; document.getElementById("boxc").value = val * metrics[document.getElementById("choice1").value]/ metrics[document.getElementById("choice3").value]; metrics[document.getElementById("choice1").value]/ metrics[document.getElementById("choice3").value]; document.getElementById("boxd").value = val2 * metrics[document.getElementById("choice2").value]/ metrics[document.getElementById("choice4").value]; document.getElementById("sqmtrs").value = document.getElementById("boxc").value * document.getElementById("boxd").value ; document.getElementById("boxc").value = math.round(document.getElementById("boxc").value); }; var interval = null; function watchChanges(){ interval == null ? setInterval("convert()", 500) : clearInterval(interval); } // ]]></script> </p> <p>Length in imperial-metric / Width in imperial-metric</p> <div><input id="boxa" style="width: 40px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="choice1" onchange="convert();"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">metres</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select> <input id="boxb" style="width: 40px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="choice2" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">metres</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select></div> <div><input id="boxc" style="width: 40px;" type="text" disabled="disabled" /><select id="choice3" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option selected="selected" value="m">metres</option> <option value="foot">feet</option> <option value="inch">inches</option> </select> <input id="boxd" style="width: 40px;" type="text" disabled="disabled" /><select id="choice4" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option selected="selected" value="m">metres</option> <option value="foot">feet</option> <option value="inch">inches</option> </select></div> <p> </p> <div>Total sq metres : <input id="sqmtrs" style="width: 40px;" type="text" value="" disabled="disabled" /></div> <p> </p> <div class="label">Please round up to half a metre when choosing</div> <table border="0" cellspacing="0" cellpadding="5"> <tbody> <tr> <td>Round:</td> <td><input type="text" name="numberfield" value="" /> to <input type="text" name="decimalfield" value="2" size="3" /> decimal places</td> </tr> <tr> <td>Result:</td> <td><input type="text" name="roundedfield" value="" /> <input onclick="roundNumber(numberfield.value, decimalfield.value);" type="button" value="Calculate" /></td> </tr> </tbody> </table> I'm a student learning javascript, I'm having a very basic problem. I have to write a script that outputs XHTML text that keeps displaying in the browser window that multiples of the integer 2, namely 2, 4, 8, 16, 32, 64, etc. This is the code i have, Code: <!-- var product=2; while { product =2*product; } document.writeln( +product+ ); // --> And it pretty much does nothing. Help would be much appreciated Dave I'm new to programming and can't figure out why this won't work: Code: print " var 1A == Math.sqrt(Math.pow(B,2) - Math.pow(C,2)); \n"; print " var 1B == Math.sqrt(Math.pow(A,2) + Math.pow((F + G),2)); \n"; print " var 1C == B + D; \n"; print " var 1D == C - B; \n"; print " var 1E == E; \n"; print " var 1F == (Math.sqrt(Math.pow(C,2) - Math.pow(A,2)) - G); \n"; print " var 1G == (Math.sqrt(Math.pow(C,2) + Math.pow(A,2)) - F); \n"; print " var 1H == ((F + G) / B); \n"; I have tried debugging it using Firebug and I get this error: Quote: identifier starts immediately after numeric literal I get the error on the line with var 1A, but I'm pretty sure that 1B, 1F, and 1G would all have the same error. Thanks for the help in advance guys! BTW the reason why the code is being printed is because I'm programming with Perl and running on a webpage using html and javascript. i had to create a function to calculate percentage and round to integer need 2 parameters of item and sum function will return value of item variable divide the sum by 100 and round to nearest integer using Math.round this is my code that i came up with Code: function calcPercent(item,sum){ // script element to calculate the percentage which is rounded to the nearest integer var items = Math.round( (item/sum)*100); // script element to get the percentage return items; } calcPercent(1, 3); Does this make sense? thanks ok so heres where I stand, I don't know too much about javascript. Just enough to get me by. I am a PHP developer, I know how to do this in PHP but the client insists on doing it through javascript. Basically there are 3 different form values that determine the Premium Death Benefit Ratio. This is the formula the client wants: Premium to Death Benefit Ratio % (Created by formula = Annual (Level) Premium Amount (Divided by) Death Benefit Amount (equals a percentage) That percentage multiplied by Life Expectancy The 3 form values in the formula would be Annual Premium Amount (fypremium), Death Benefit Amount (dbp), Life Expectancy (average_le) I was messing around with javascript trying to figure it out and I have gotten no where since I am not used to writing formulas in JS. Anyways here is what I have so far: Code: function calculateLE(inputFieldId1, inputFieldId2, inputFieldId3, outputFieldId){ var DBR; var input = document.getElementById(inputFieldId).value; APA = document.getElementById(fypremium).value; DBA = document.getElementById(dbp).value; LE = document.getElementById(average_le).value; formula = document.getElementById(fypremium).value / document.getElementById(dbp).value = formula3; formula2 = document.getElementById(average_le).value * formula3; if { APA = "" } { document.getElementById(outputFieldId).value = "Error getting Annual Premium Amount"; } else if { DBA = "" } { document.getElementById(outputFieldId).value = "Error getting Death Benefit Amount"; } else if { LE = "" } { document.getElementById(outputFieldId).value = "Error getting Life Expectancy"; } else { document.getElementById(outputFieldId).value = formula3; } } Now I honestly have no clue if I am on the right track but what i've found on the net hasnt really pointed me in the right direction Here is the form values. Code: <input type="text" name="fypremium" id="fypremium" onblur="calculateLE('fypremium', 'dbp', 'average_le', 'premium_dbr')"> <input type="text" name="dbp" id="dbp" onblur="calculateLE('fypremium', 'dbp', 'average_le', 'premium_dbr')"> <input type="text" name="average_le" id="average_le" onblur="calculateLE('fypremium', 'dbp', 'average_le', 'premium_dbr')"> In a nut shell the values for the 3 inputs stated above will determine premium_dbr's value. fypremium / dbp = percentage; average_le * percentage = DBR (death benefit ratio); If someone could point me in the right direction to finishing this id be very greatful. Hi. I am new to javascript programming so please go easy on me. I am creating a site for a flooring store and need to include a price calculator/estimator. What I need to do is allow the visitor to input the room size (length x width) and choose a flooring material from a pulldown list, and receive a price. The pulldown list would have flooring materials such as carpet, tile, wood, etc and each of these would have a fixed dollar amount associated with them (which would be hidden). So basically it is just a script that would multiply 3 numbers, with two of the numbers being input by the visitor, and th tird being selected from the pulldown. Can someone please educate me on how to do this? Im trying to get all of these math functions into one table with each one going into an individual row. The following is what my Grad Assistant gave us as instructions..he is not real helpful..lol The goal of project to is to create a webpage that makes use of javascript to perform a dynamic number of operations. The program must first ask for a number of operations to perform (n).It is therefore required that a loop construct be used. The program will then ask the user n times what operation they would like to perform and the appropriate inputs for that operation. All of the operations will use integer type inputs except ceiling, floor, and round which will use float types. The required operations for this project will be 1. + 2. * 3. / 4. % 5. min 6. max 7. floor 8. ceil 9. round The output of each operation will be stored in a table. The required outputs for each row are the operation requested, the expression for the operation showing its structure (see below), the result of the operation and additionally a random number. The random number should be within one and the number of operations requested. (ex: 5 operations requested, random number is in the range 0-5) A sample of what this output will look like is shown here. let me know if you can help it is much appreciated..the course book does not cover most of what is being taught and in class time could be better spent self taught! lol ..midterms suck and its almost time for the weekend so I could really use some help!! thx again Hi. I am new to javascript programming so please go easy on me. I am creating a website for a flooring store and need to include a price calculator/estimator. What I need to do is allow the visitor to input the room size (length x width) and choose a flooring material from a pulldown list, and receive a price. The pulldown list would have flooring materials such as carpet, tile, wood, etc and each of these would have a fixed dollar amount associated with them (which would be hidden). So basically it is just a script that would multiply 3 numbers, with two of the numbers being input by the visitor, and the third being selected from the pulldown. Can this be done with Javascript, and can someone please educate me on how to do this? Hi. I'm in JS kindergarten. I have a form with a field that asks for a full year. If the year is greater than 20 years ago, I'd like additional form fields to be revealed. If the year is equal to or less than 20 years ago, it will not reveal the fields. (And it should be based on getFullYear(), so I don't have to update the script every year, yeah?) I figured out how to script onclick functions and some basic .value == functions in order to show/hide just about every type of form field. So I don't need that info. But I'm unsure of how to calculate the value. I'd be interested to see your solutions. No rush. Thanks in advance. Code: <script type="text/javascript"> function countItDown(){ var current=parseFloat(document.getElementById("currentsecondscount").value); var seconds=current; document.getElementById("debug").innerHTML="S "+current; var minutes=Math.floor(seconds/60); document.getElementById("debug").innerHTML+="<br>M "+minutes; var hours=Math.floor(minutes/60); document.getElementById("debug").innerHTML+="<br>H "+hours; var days=Math.floor(hours/24); document.getElementById("debug").innerHTML+="<br>D "+days; var remainingseconds=seconds-(minutes*60); document.getElementById("debug").innerHTML+="<br>RS "+remainingseconds; var remainingminutes=minutes-(hours*60); document.getElementById("debug").innerHTML+="<br>RM "+remainingminutes; var remaininghours=hours-(days*24); document.getElementById("debug").innerHTML+="<br>RH "+remaininghours; if(days<10){ days="0"+days; } if(remaininghours<10){ remaininghours="0"+remaininghours;} if(remainingminutes<10){ remainingminutes="0"+remainingminutes;} if(remainingseconds<10){ remainingseconds="0"+remainingseconds;} document.getElementById("days").innerHTML=days; document.getElementById("hours").innerHTML=remaininghours; document.getElementById("minutes").innerHTML=remainingminutes; document.getElementById("seconds").innerHTML=remainingseconds; document.getElementById("currentsecondscount").value=(current-1); } </script> ....... <input type="hidden" id="currentsecondscount" value="<?=$seconds;?>" /> ....... Chrome/IE/etc on Left... FF 3.6.3 [windows] on Right im not sure why Firefox is doing this. it seems to work fine on Firefox 3.6.3 for Mac... I am at a lost, new to JavaScript and not sure why I am getting Nan Code: <script type="text/javascript"> var num1; var num2; var num3; var ave_num=Math.round((num1 + num2 + num3) / 3); //follow prompts to enter numbers and print average </script> I have been asked by a friend to create a math sheet generator for their child, however i don't have a clue where to start with javascript. Similar to this.. http://cemc2.math.uwaterloo.ca/mathf...sheetgen.shtml It doesn't need to be advanced as that as all i'm looking for is how to create the sums. If someone could help either by informing me where to start or even an online tutorial i would be extremely greatful! Many thanks, James |