i have a js file (which utilises the jquery framework) that is a simple equation to calculate corresponding values.
JS FILE (sample):
var colorOneRed = parseFloat($('#colorOneRed').text()); ...
var totalRed = (parseFloat(colorOneRed) + parseFloat(colorTwoRed) ...
$('#totalColorRed').text(totalRed); ...
I have the same exact equation multiple times, only the color changes. So the same equation is used for green var colorGreen, blue, purple, etc.
My question is can I write just the one equation to encompass all the variables and #id's
instead writing the same equation over and over.
I tried the id^='totalcolor' method for example, but it will only calculate the one variable. So what I mean is, if #colorOneRed has a value of 40 but #colorOneGreen has a value of 60 it will only calculate the one value for all using the id^=colorOne method.
I'm not sure its even possible but i'm hoping to have one equation that will be able to have a calculation for all the greens and one for all the blues and so on.
Thanks in advance for any help.
I think this is what you are trying to do. Checkout this fiddle. You can always extend this for other color elements.
Put the calculation in one function:
function calc(displayElt, color){
var total=parseFloat($('#colorOne'+color).text()) + parseFloat($('#colorTwo'+color).text())+..
$('#'+displayElt).text(total);
}
calc(totalColorRed,Red);
Wrap your code in a function where you pass in the required DOM elements to perform the calculation:
function calculate(colorOneElement, totalElement) {
var colorOne = parseFloat($(colorOneElement).text()); ...
var total = (parseFloat(colorOneRed) + parseFloat(colorTwoRed) ...
$(totalElemenet).text(totalRed); ...
}
The use as follows:
calculate(document.getElementById("colorOneRed"),
document.getElementById("totalOneRed"));
calculate(document.getElementById("colorOneGreen"),
document.getElementById("totalOneGreen"));
etc ...
Related
I'm a beginner on here, so apologies in advance for naivety. I've made a simple image on Brackets using Javascript, trying to generate circles with random x and y values, and random colours. There are no issues showing when I open the browser console in Developer Tools, and when I save and refresh, it works. But I was expecting the refresh to happen on a loop through the draw function. Any clues as to where I've gone wrong?
Thanks so much
var r_x
var r_y
var r_width
var r_height
var x
var y
var z
function setup()
{
r_x = random()*500;
r_y = random()*500;
r_width = random()*200;
r_height = r_width;
x = random(1,255);
y= random(1,255);
z= random(1,255);
createCanvas(512,512);
background(255);
}
function draw()
{
ellipse(r_x, r_y, r_width, r_height);
fill(x, y, z);
}
Brackets.io is just your text editor (or IDE if you want to be technical) - so we can remove that from the equation. The next thing that baffles me is that something has to explicitly call your draw() method as well as the setup() method -
I'm thinking that you're working in some sort of library created to simplify working with the Canvas API because in the setup() method you're calling createCanvas(xcord,ycord) and that doesn't exist on it's own. If you want to rabbit hole on that task check out this medium article, it walks you thru all the requirements for creating a canvas element and then drawing on that canvas
Your also confirming that you're drawing at least 1 circle on browser refresh so i think all you need to focus on is 1)initiating your code on load and 2)a loop, and we'll just accept there is magic running in the background that will handle everything else.
At the bottom of the file you're working in add this:
// when the page loads call drawCircles(),
// i changed the name to be more descriptive and i'm passing in the number of circles i want to draw,
// the Boolean pertains to event bubbling
window.addEventListener("load", drawCircles(73), false);
In your drawCircles() method you're going to need to add the loop:
// im using a basic for loop that requires 3 things:
// initialization, condition, evaluation
// also adding a parameter that will let you determine how many circles you want to draw
function drawCircles(numCircles) {
for (let i = 0; i < numCircles; i++) {
ellipse(r_x, r_y, r_width, r_height);
fill(x, y, z);
}
}
here's a link to a codepen that i was tinkering with a while back that does a lot of the same things you are
I hope that helps - good luck on your new learning venture, it's well worth the climb!
Thank you so much for your help! What you say makes sense - I basically deleted the equivalent amount of code from a little training exercise downloaded through coursera, thinking that I could then essentially use it as an empty sandpit to play in. But there's clearly far more going on under the hood!
Thanks again!
I use a CodeMirror for displaying code on the HTML page. I have a version of the code which was saved in BD and when a user edits it in CodeMirror, I want to highlight unsaved changes like Visual Studio Code does:
I know that I can use method: codeMirror.removeLineClass(line, 'gutter', 'my_class'); to add a border that shows that changes were done at the specific line. My problem is in the calculation of the changed lines. I tried to use diff and diff2html packages and calculates changes like this:
var diff = Diff.createTwoFilesPatch('some name', 'some name', cm.state.savedText, cm.getValue());
var diffInfo = Diff2Html.getJsonFromDiff(diff, options);
This approach gives me a diff and I can get changed lines from it:
But this solution has a performance problem - it works slowly if a text contains more than 40 lines, and I will have large texts in CodeMirror.
I also tried to use history (the structure that codeMirror.getDoc().getHistory() returns) and highlight lines that are stored in 'changes' array, but it works only for new lines which were added. This approach doesn't work if the user removes the line.
What is the right way of calculation for such changes?
I was thinking of using the change event and tracking a specific change("+delete",
"+input"), then collect changed lines in special array. But this solution looks painful because in this case, I need to update this array manually if lines were added/deleted in the next iteration.
Is there a simpler way of how to do it?
After some research I've realized that even for big texts (~12 000 lines) approach with calculating the diff still works:
var diff = Diff.createTwoFilesPatch('some name', 'some name', cm.state.savedText, cm.getValue());
var diffInfo = Diff2Html.getJsonFromDiff(diff, options)
It takes ~30ms to calculate the diff for big text, and 5-6ms for small ones (~100lines). So for now it seems the most simple way for highlighting updated lines.
I am working on a portion of a project that I am trying to detect when certain divs hit each other. In the code that I made, that doesn't work, I basically say take the first div's left amount, compare it to the other div's left amount, if they are within a certain amount it triggers an alert. If I get that much to work I am going to implant a way to say that if the distance between the two divs is 0 then it will run a certain function. I am afraid the scope of this project is too big for me, even though I am basically at the last part, because I have spent hours researching a simple way to add collision detection, but everything I find looks like rocket science to me, that is why I tried to create my own way below. So in summary, what I want to know is why my collision detection code doesn't work, how I can make it work if possible, and if not possible what is the next best option that I should use.
//Collision
function collision(){
var tri = $('#triangle');
var enemyPos = $('.object1').css('left');
var minHit = enemyPos - 32.5;
var maxHit = enemyPos + 32.5;
var triLoc = tri.css('left');
if(triLoc > minHit && triLoc < maxHit){
alert('hit');
}
}
collision();
}
}
full code: https://jsfiddle.net/kc59vzpy/
If the code you have above is definitely where the problem is, then you need to look at the enemyPos variable. Getting the left position also adds px, so enemyPos is 100px or something like that. When you add 32.5, you get 100px32.5 and when you subtract you get NaN, neither of which you want.
Before you add or subtract, use enemyPos = parseInt($('.object1').css('left')); to turn it into an actual number.
I need to find the speed of an object in a game. The game is made in HTML5 with jquery and jquery.box2d.
For this I can use these methods:
GetLinearVelocity().x;
GetLinearVelocity().y;
I'm then trying to calculate the speed from this piece of code, but get some values that doesn't make sense when I console.log it. This is my code:
var heroVelX = game.currentHero.GetLinearVelocity().x;
var heroVelY = game.currentHero.GetLinearVelocity().y;
var speed = Math.sqrt(heroVelX^2 + heroVelY^2);
console.log(speed);
Some of the values in console.log are numbers, but most of them are NaN (Not-A-Number), which confuses me? Can someone help me solve this?
The goal I want to achieve, is to see when the speed(of object .currenHero) drop below a certain value, so I can excute a new state in the game.
Your problem is that you're using the wrong operator (Bitwise XOR) for doing square - see here.
What you need to do is:
var speed = Math.sqrt(Math.pow(heroVelX, 2) + Math.pow(heroVelY, 2));
The only time the square root function should return NaN is when the value being square rooted is negative. A way to go about testing if this is the issue would be to try squaring the values in a different line of code before square rooting them.
heroVelX = (heroVelX) * (heroVelX)
Another way to potentially shine some light on the problem would be to add log statements printing out the values of the velocities and the velocities squared before square rooting.
This obviuosly works perfectly:<script>alert(5*8-4)</script>
but i need to solve whatever someone puts inside an input box.
Heres what I thought of doing: I would get the value of the input, into a variable. then I would use
document.write("<script>alert("+theinputvalue+")<script>");
or do this:
var string="<script>alert("+theinputvalue+")<script>";document.write(string);
but nothing works.
Is it even possible to do this? if not, tell my what simple other system I could use.
eventually, I will use it to graph lines like this:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d")
for(var x=-100; x<100; x=x+.2){
y = .1*(x*x)
ctx.fillRect(x+50, -1*y+50, 2, 2);
}
http://jsfiddle.net/KGgq4/
eval('5*8-4')
will result in 36
I'm not aware of any library that is doing that (this doesn't mean that there are no such it simply means I never actually needed that) but what you should end up doing is to build an automata that will parse input string and transform it to a proper graph with proper transformations. This is not very easy topic and if you want to go this route you should start reading on arithmetic expressions parsing algorithms (sorry I do not have any solution in place).
Or you can cheat and define types of equations that will be selected by user. Once user selects type of equation you should be able show user inputs where user will be able to select coefficients. You can read those coefficients into different variables and apply transformations in your draw procedure (For example if user will select type sin(x) you know that general equation has following formula: y = k*sin(a*x + b) + c. So once it is selected you can allow user to enter k, a, b, c and based on that input calculate appropriate locations of points for your graph.)
Well, third solution could involve "eval ", but usually you should avoid eval at any cost (B/c it is straight forward JavaScript injection which may be an OK for this case but may get you in trouble later in your life. ).
You can use math.js, which comes with an advanced expression parser. It supports definition of variables and functions.
// create an instance of math.js
var math = mathjs();
// evaluate an expression
math.eval('5*8-4'); // 36
// user defined function (returns a native JavaScript function)
var f = math.eval('f(x) = 2*x^2 + 6');
// use the function (for graphing or something)
f(2); // 14