I have a var..
var random = Math.ceil(Math.random() * 8.8);
and I have a click function
$('.passShort').bind('click', function() {
// do something here and get new random number
});
I'm trying to change the global random var not just inside this particular function.
I like to strictly define global variables when they need to be truly global, and I avoid repetitive code when possible:
setRandom();
$('.passShort').bind('click', setRandom);
function setRandom() { window.random = Math.ceil( Math.random() * 8.8 ); };
Setting the variable on the window object ensures it's truly global. You can refere to it as random anywhere and it will give you window.random but using window.random assures you are setting the value of the global random variable.
Use var outside the function, but not inside it:
var random = Math.ceil(Math.random() * 8.8);
$('.passShort').bind('click', function() {
random = Math.ceil(Math.random() * 8.8);
});
Depending on where you declared the random variable will determine it's scope. If you want to make it global, just declare it without the var keyword.
random = Math.ceil(Math.random() * 8.8);
Really, it would nicer if you could combine the functionality you're looking for into some re-usable object, a Random Number Generator? An example might be:
var RNG = {
get randInt() { return Math.ceil(Math.random() * 8.8); },
get randFloat() { return Math.random() * 8.8; },
randRange: function(min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
}
};
console.log(RNG.randInt);
console.log(RNG.randFloat);
console.log(RNG.randRange(5,10));
$('.passShort').bind('click', function() {
console.log(RNG.randInt); // Whatever you want here.
});
Related
Need help with Javascript to generate number in HTML. I'm close but can't get it to quite work. Help would be appreciated.
http://jsfiddle.net/xmPgR/251/
function getNumber() {
var minNumber = 0; // The minimum number you want
var maxNumber = 100; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
$('#myNumber').html(randomnumber); // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = getNumber; // Runs the function on click
document.getElementById("yourNumber").innerHTML = randomnumber;
<div id="myNumber"></div>
<p id="yourNumber">
</p>
Your onload works after the next statement, because it works asynchronously. And besides this, you use a randomnumber outside from it's scope, where it is not accessible.
So I suggest you to return the randomnumber from the function and use that function in the onload event handler. Inside that handler call your function, get the number and assign to your element's text.
And also if your getNumer's logic is to return the number, don't assign anything inside it, just return the number. It's responsibility is to return a random number. Pass the range to it, don't hard code: in another place you can need a random number in the different range. Other logic implement outside of that function.
function getRandomNumber(minRange, maxRange) {
return Math.floor(Math.random() * (maxRange + 1) + minRange);
}
window.onload = function() {
const rand = getRandomNumber(0, 100);
document.getElementById("yourNumber").innerHTML = rand;
$('#myNumber').html(rand);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myNumber"></div>
<p id="yourNumber"></p>
Here you go:
function getNumber() {
var minNumber = 0; // The minimum number you want
var maxNumber = 100; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
document.getElementById("myNumber").innerHTML = randomnumber; // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = getNumber; // Runs the function on click
<div id="myNumber"></div>
<p id="yourNumber">
</p>
I am using a random function to randomly slide between 4 swiper sliders, here is my code :
var swipers = [swiper1, swiper2, swiper3, swiper4];
setInterval(function(){
var rand = Math.floor(Math.random() * 4);
swipers[rand].slideNext();
}, 3000);
}
How should i proceed if i wanted to randomize between slideNext() and slidePrev() ? I tried many things like this :
var direction = ['slideNext()', 'slidePrev()'];
var swipers = [swiper1, swiper2, swiper3, swiper4];
setInterval(function(){
var randx = Math.floor(Math.random() * 4);
var randy = Math.floor(Math.random() * 2);
swipers[randx].direction[randy];
}, 3000);
But it's not working, probably for obvious reasons, but please help me understand why it's not working. And how i could possibly achieve that?
Just put the method name in the arrays, without parentheses. Then use it to index the object, and call the result of that.
You should also use <arrayname>.length rather than hard-coding the lengths when you get the random index, so you don't have to change it if you add more swipers or directions.
var direction = ['slideNext', 'slidePrev'];
var swipers = [swiper1, swiper2, swiper3, swiper4];
setInterval(function(){
var randx = Math.floor(Math.random() * swipers.length);
var randy = Math.floor(Math.random() * direction.length);
swipers[randx][direction[randy]]();
}, 3000);
You're pretty close! Just change how you're setting the direction and I think you got it:
swipers[randx][direction[randy]]();
Also remove the parenthesis from your array and just leave the function names there.
now the repeating code problem has been solved but when executed the if condition function of moveHorse is being executed repeteadly. please help.
function moveHorse(horseId)
);
interval=setInterval(function(){moveHorse('horseID');},20);
}
now the repeating code problem has been solved but when executed the if condition function of moveHorse is being executed repeteadly. please help.
Pass in the element ID as the function parameter, then you can refactor the code to -
// TODO: rename your local variable name because now it doesn't need to be horse4, right?
function horseUp(horseElementId) {
var horse = document.getElementById(horseElementId);
// do the rest
}
function horseDown(horseElementId) {
var horse = document.getElementById(horseElementId);
// do the rest
}
function horseleft(horseElementId) {
var horse = document.getElementById(horseElementId);
// do the rest
}
To use the function, pass in the element Id
horseUp('horse4');
horseLeft('horse2');
and so on
Since the only part that appears to be different is the horse being changed, just pass that in. For example:
var horse4 = document.getElementById('horse4');
function horseUp(horse, moving) {
var horseTop = horse.offsetTop;
var random = Math.random() * 2.7 + 2;
horse.style.top = horseTop - 0.5 * random + 'px';
if (horseTop <= window.innerHeight * 0.05) {
clearInterval(interval4);
interval4 = setInterval(moving, 10);
}
}
There's a few other variables like interval4 that you'll need to figure out, but this should give you the general idea.
May use OOP:
function Horse(id) {
this.el = document.getElementById(id);
}
Horse.prototype={
move(x,y){
this.el.offsetTop+=(this.y=typeof y !=="undefined"?y:this.y);
this.el.offsetLeft+=(this.x=typeof x !== "undefined"?x:this.x);
},
up(){
this.move(0,0.5*Math.random() * 2.7 + 2* + 'px';
},
down(){ this.move(0,- 0.5* Math.random() * 2.4 + 2);},
left(){ this.move(0.5* Math.random() * 2.4 + 2,0);},
right(){ this.move(- 0.5* Math.random() * 2.4 + 2,0);},
setInterval(){
this.interval=setInterval(_=>this.move(),10);
}
}
use like this:
var horse4=new Horse("horse4");
horse4.setInterval();
horse4.left();
I have a equation like this stored in a varible
(50 * 1.07^1) its very simple. I want to know how I can change the power each time a function runs like so: 50*1.07^2, 50*1.07^3 and so forth. Any help?
Here is my code:
var mathForCost = 50 * 1.07 ^ 1;
function gainCoinsPS() {
if (coins >= costPS) {
coinsPS += 10;
coins -= costPS;
// Here is where I am changing the cost each time the function runs,
// so I need to make the power(^1) add 1 each time
costPS = document.getElementById("changePrice1").innerHTML = "Cost: " + costPS;
} else {;
alert("You dont have enough coins!");
};
}
Save the power to a variable, and you can update it when needed. It is preferred that you put the equation into a function and pass power to it, and return the solution.
var power = 1,
eq = function(p){
return 50*1.07^+p; // returns solution
};
for(var i=0; i<10; i++){
power = i;
console.log( eq(power) ); // solution
}
You can store your power in a variable and increment it each time your function is called.
var power = 1;
function calculate() {
console.log(50 * Math.pow(1.07, power));
power++;
}
calculate();
calculate();
calculate();
In Javascript you can't really store an equation in a variable, except maybe as a string (but that is fraught with issues of its own). Your function will be evaluated the moment you execute, and the value of the output will instead be stored in the variable.
To do what you want to do, you would be better having a function that runs the equation, and increments the power each time-- this works if the power is in a higher scope (or it can be accomplished with a closure)
var power = 1;
function getCost()
var cost = Math.pow(50*1.07, power);
power++;
return cost;
}
Each time this function runs, it returns the calculated cost and also increments the value of power, so it will be one higher the next time it runs.
Alternately, if you wanted to go the closure route, you could do something like this:
var getCost = (function () {
var power = 1;
return function () {
var cost = Math.pow(50*1.07, power);
console.log(power);
power++;
return cost;
}
})();
You can store a state to the function that runs the equation. This helps you avoid adding more state outside of the function. Let the function keep track of how many times it has been called.
function calc() {
if (!this.i) {
this.i = 1;
}
return (50 * Math.pow(1.07, this.i++));
}
console.log(calc());
console.log(calc());
console.log(calc());
There is Math.pow function is javascript for this.
You can use something like this
var pow = 1;
for(var power=1; power<limit; power++){ // run the loop upto a limit
console.log(Math.pow(50*1.07, power);
}
To increment power of 1.07 by 1, just multiply value by 1.07 every time (pow function is not needed at all)
var mathForCost = 50 * 1.07;
...
mathForCost = mathForCost * 1.07;
You could use a function for it.
getCost = function (n) { return 50 * Math.pow(1.07, n); };
Or with ES6's arrow function
getCost = n => 50 * Math.pow(1.07, n);
Call it with
value = getCost(1);
I am using jQuery to generate and add a random amount of Clouds to the Header of the page and move them left on the specified interval. Everything is working fine, execpt the interval only runs once for each Cloud and not again. Here is my code:
if(enableClouds) {
var cloudCount = Math.floor(Math.random() * 11); // Random Number between 1 & 10
for(cnt = 0; cnt < cloudCount; cnt++) {
var cloudNumber = Math.floor(Math.random() * 4);
var headerHeight = $('header').height() / 2;
var cloudLeft = Math.floor(Math.random() * docWidth);
var cloudTop = 0;
var thisHeight = 0;
var cloudType = "one";
if(cloudNumber == 2) {
cloudType = "two";
}else if(cloudNumber == 3) {
cloudType = "three";
}
$('header').append('<div id="cloud' + cnt + '" class="cloud ' + cloudType + '"></div>');
thisHeight = $('#cloud' + cnt).height();
headerHeight -= thisHeight;
cloudTop = Math.floor(Math.random() * headerHeight);
$('#cloud' + cnt).css({
'left' : cloudLeft,
'top' : cloudTop
});
setInterval(moveCloud(cnt), 100);
}
function moveCloud(cloud) {
var thisLeft = $('#cloud' + cloud).css('left');
alert(thisLeft);
}
}
Any help is appreciated!
This is the way to go:
setInterval((function(i){
return function(){
moveCloud(i);
};
})(cnt), 100);
Engineer gave you the code you need. Here's what's happening.
The setInterval function takes a Function object and an interval. A Function object is simply an object that you can call, like so:
/* Create it */
var func = function() { /* ... blah ... */};
/* Call it */
var returnVal = func(parameters)
The object here is func. If you call it, what you get back is the return value.
So, in your code:
setInterval(moveCloud(cnt), 100);
you're feeding setInterval the return value of the call moveCloud(cnt), instead of the the function object moveCloud. So that bit is broken.
An incorrect implementation would be:
for(cnt = 0; cnt < cloudCount; cnt++) {
/* ... other stuff ... */
var interval = setInterval(function() {
moveCloud(cnt);
}, 100);
}
Now, you're feeding it a function object, which is correct. When this function object is called, it's going to call moveCloud. The problem here is the cnt.
What you create here is a closure. You capture a reference to the variable cnt. When the function object that you passed to setInterval is called, it sees the reference to cnt and tries to resolve it. When it does this, it gets to the variable that you iterated over, looks at its value and discovers that it is equal to cloudCount. Problem is, does not map on to a Cloud that you created (you have clouds 0 to (cloudCount -1)), so at best, nothing happens, at worst, you get an error.
The right way to go is:
setInterval((function(i){
return function(){
moveCloud(i);
};
})(cnt), 100);
This uses an 'immediate function' that returns a function. You create a function:
function(i){
return function(){
moveCloud(i);
};
}
that returns another function (let's call it outer) which, when called with a value i, calls moveCloud with that value.
Then, we immediately call outer with our value cnt. What this gives us is a function which, when called, calls moveCloud with whatever the value of cnt is at this point in time. This is exactly what we want!
And that's why we do it that way.