How to change the position randomly? - javascript

var imgOut = function(){
var outImg = Math.floor(Math.random()*slideRandom.length);
document.getElementById("random").src = imgRandom[outImg];
var outSlide = slideRandom[outImg];
outSlide();
var wr = Math.floor(Math.random()*imgRandom.length);
var btl = Math.floor(Math.random()*bottle.length);
document.getElementById("bottle2").src = bottle[outImg];
document.getElementById("bottle1").src = bottle[btl];
document.getElementById("bottle3").src = bottle[wr];
/* try below but doesn't work or syntax error occured*/
var position= ['bottle[outImg]','bottle[btl]','bottle[wr]'];
var pos = Math.floor(Math.random()*position.length);
var pos1 = position[pos];
pos1();
}
what I'm try to do is
with different arrays to get different each images in different random position.
I've done different images to get but with three different arrays to put in random position doesn't work. what have I done wrong? or how to change above code?

I don't understand your requirements exactly, but consider this code:
var setImage = function(id, src) {
document.getElementById(id).src = src;
};
var chooseOne = function(array) {
return array[Math.floor(Math.random()*array.length)];
};
var setRandomImages = function() {
setImage("bottle1", chooseOne(bottle));
setImage("bottle2", chooseOne(bottle));
setImage("bottle3", chooseOne(bottle));
};
If the array bottle is a list of URLs, this will do something, though I cannot guarantee it will do what you want.

var position= ['bottle[outImg]()','bottle[btl]()','bottle[wr]()'];
var pos = Math.floor(Math.random()*position.length);
var pos1 = position[pos];
//pos1();
eval( pos1 );
// or
(new Function("return pos1"))();

Related

$ dot each not working for recursion (JS)

I have a loop in which I am calling rec_append() recursively, apparently the first pass alone works, then the loop stops.
I have an array of 4 elements going into that $.each loop but I see only the first element going into the function recursively. Help!
I switched it for a element.forEach but that gives me only the second element and I am stuck, is there a better solution to process a tree of elements? My array is a part of a tree.
var data = JSON.parse(JSON.stringify(result))
var graph = $(".entry-point");
function rec_append(requestData, parentDiv) {
var temp_parent_details;
$.each(requestData, function (index, jsonElement) {
if (typeof jsonElement === 'string') {
//Element construction
//Name and other details in the form of a : delimited string
var splitString = jsonElement.split(':');
var details = document.createElement("details");
var summary = document.createElement("summary");
summary.innerText = splitString[0];
details.append(summary);
temp_parent_details = details;
parentDiv.append(details);
var kbd = document.createElement("kbd");
kbd.innerText = splitString[1];
summary.append(' ');
summary.append(kbd);
var div = document.createElement("div");
div.className = "col";
details.append(div);
var dl = document.createElement("dl");
div.append(dl);
var dt = document.createElement("dt");
dt.className = "col-sm-1";
dt.innerText = "Path";
div.append(dt);
var dd = document.createElement("dd");
dd.className = "col-sm-11";
dd.innerText = splitString[2];
div.append(dd);
var dt2 = document.createElement("dt");
dt2.className = "col-sm-1";
dt2.innerText = "Type";
div.append(dt2);
var dd2 = document.createElement("dd");
dd2.className = "col-sm-11";
dd2.innerText = splitString[1];
div.append(dd2);
} else {
$.each(jsonElement, function (jsonElementArrIndx, jsonChildElement) {
rec_append(jsonChildElement, temp_parent_details); //Only 1 pass works, rest skip
});
}
});
}
rec_append(data, graph);
Sample data:enter image description here

Reduction over an image collection Google Earth Engine

I am using CHIRPS data set (daily precipitation) to derive mean, median, min and max precipitation within a certain time frame. Then, I want to extract the values at specific locations included in a point shapefile and save the results in a table.
The script seem to work but the output table only has zeros (0) as values for the 4 variables.
Please see the script below
var lng = 65.64;
var lat = 34.35;
var point = ee.Geometry.Point(lat, lng);
//var aoi = point.buffer(100000); // Create an area (1km buffer around point)
var country = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017')
.filter(ee.Filter.eq('country_co', 'AF'));
var aoi = country;
Map.setCenter(lng, lat, 5); // Center the map on this location, zoom level 10
var start = '2018-02-15'; // initial date of the image collection
var end = '2018-07-15'; //final date of the image collection
var p1 = ee.Geometry.Point([69.78086, 34.65411])
var p2 = ee.Geometry.Point([61.82234, 30.66048])
var table = ee.FeatureCollection(ee.List([ee.Feature(p1),ee.Feature(p2)]))
var AddPrMean = function(image) {
var PrMean = image.reduce(ee.Reducer.mean()).rename('PrMean');
return image.addBands(PrMean);
};
var AddPrMedian = function(image) {
var PrMedian = image.reduce(ee.Reducer.median()).rename('PrMedian');
return image.addBands(PrMedian);
};
var AddPrMin = function(image) {
var PrMin = image.reduce(ee.Reducer.min()).rename('PrMin');
return image.addBands(PrMin);
};
var AddPrMax = function(image) {
var PrMax = image.reduce(ee.Reducer.max()).rename('PrMax');
return image.addBands(PrMax);
};
var dataset = ee.ImageCollection('UCSB-CHG/CHIRPS/DAILY')
.filterDate(start, end)
.filterBounds(aoi)
.map(AddPrMean)
.map(AddPrMedian)
.map(AddPrMin)
.map(AddPrMax);
var composites = dataset.select(['PrMean','PrMedian','PrMin','PrMax']).first();
var YieldLocations = ee.FeatureCollection(table);
var YPrec = composites.reduceRegions(YieldLocations, ee.Reducer.max(), 1);
print(YPrec); ```
I found a solution that seems to work, however, the median always gives 0 as result.
var lat = 34.35;
var point = ee.Geometry.Point(lat, lng);
//var aoi = point.buffer(100000); // Create an area (1km buffer around point)
var country = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017')
.filter(ee.Filter.eq('country_co', 'AF'));
var aoi = country;
Map.setCenter(lng, lat, 5); // Center the map on this location, zoom level 10
var start = '2018-02-15'; // initial date of the image collection
var end = '2018-07-15'; //final date of the image collection
var p1 = ee.Geometry.Point([69.78086, 34.65411])
var p2 = ee.Geometry.Point([61.82234, 30.66048])
var table = ee.FeatureCollection(ee.List([ee.Feature(p1),ee.Feature(p2)]))
var dataset = ee.ImageCollection('UCSB-CHG/CHIRPS/DAILY')
.filterDate(start, end)
.filterBounds(aoi);
var PrMean = dataset.mean().rename('PrMean');
var PrMedian = dataset.median().rename('PrMedian');
var PrMin = dataset.min().rename('PrMin');
var PrMax = dataset.max().rename('PrMax');
var composites = PrMean
.addBands(PrMedian)
.addBands(PrMin)
.addBands(PrMax);
var YieldLocations = ee.FeatureCollection(table);
var YPrec = composites.reduceRegions(YieldLocations, ee.Reducer.max(), 1);
print(YPrec);```

What is wrong with my image slide show code?

I'm trying to make an image cycle through a set of images, when you click a button. Why won't it work? I want to make sure the images are preloaded, so that it will not make the website slower.
var ImageSet = new Array();
ImageSet[0] = ImageOne;
ImageOne = newImage();
ImageSet[0].src = 'Website/Images/CoverPhotos/LogoCover.jpg';
ImageSet[1] = ImageTwo;
ImageTwo = newImage();
ImageSet[1].src = 'http://p1.pichost.me/i/64/1886374.jpg';
ImageSet[2] = ImageThree;
ImageThree = newImage();
ImageSet[2].src = 'http://abduzeedo.com/files/originals/5/50cuteanimpic6.jpg';
ImageSet[3] = ImageFour;
ImageFour = newImage();
ImageSet[3].src = 'http://www.onsecrethunt.com/wallpaper/wp-content/uploads/2015/01/Cool-Wallpapers-Card-Pictures-1200x675.jpg';
var ImageSwitchNo = 0;
function Change() {
if (ImageSwitchNo < 3) {
ImageSwitchNo++;
}else {
ImageSwitchNo = 0;
}
var ImageSrc = document.getElementById('HeaderPhotoImage').innerHTML;
ImageSrc.src = ImageSet[3];
}
You are giving ImageOne a value on line three after trying to store it in the array on the line before it.
Instead of this:
var ImageSet = new Array();
ImageSet[0] = ImageOne;
ImageOne = newImage();
ImageSet[0].src = 'Website/Images/CoverPhotos/LogoCover.jpg';
try doing it like this for all of them:
var ImageSet = [];
ImageOne = newImage(); //gives ImageOne a value.
ImageSet[0] = ImageOne; //THEN sets the index of ImageSet to that value.
ImageSet[0].src = 'Website/Images/CoverPhotos/LogoCover.jpg';
Your code may work if you change the second line from bottom,
ImageSrc.src = ImageSet[3];
to
ImageSrc.src = ImageSet[ImageSwitchNo];

How to get concotenate value with string to get the value from variable

Please check the script below.
Dynamic form, so the script also dynamic, I have to calculate when the form data changes. during this i am getting some problem.
am getting the value from the variable Final_price1, Final_price2 .....,Final_price7, Final_price8 and then am calculating the total of those.
During this calculation, am concatenating the following concat("Final_price",i); to get the values of the above. This concatenated correctly, but the above variables values are not coming. I dont know why the values are not getting there. So check the script and update me.
function assign_body()
{
var a_7= document.getElementById("option[280]").value;
var spl_7 = a_7.split("_");
//alert(spl);
var cr_7 = spl_7[1];
var operator3_7 = cr_7.split("[");
var symbol7 = operator3_7[0];
var dtt_7 = operator3_7[1];
var myarr_7 = dtt_7.split("$");
var symbol_st_7 = myarr_7[1];
//alert(symbol_st);
//alert(symbol_s);
//var symbol_a = symbol_s.split("(");
//var symbol = symbol_a[1];
//alert(symbol);
var split_value_7 = myarr_7[1];
//alert(split_value);
var final_value_7 =symbol_st_7.split(".");
var Final_price7 =final_value_7[0];
var a_8= document.getElementById("option[281]").value;
var spl_8 = a_8.split("_");
//alert(spl);
var cr_8 = spl_8[1];
var operator3_8 = cr_8.split("[");
var symbol8 = operator3_8[0];
var dtt_8 = operator3_8[1];
var myarr_8 = dtt_8.split("$");
var symbol_st_8 = myarr_8[1];
//alert(symbol_st);
//alert(symbol_s);
//var symbol_a = symbol_s.split("(");
//var symbol = symbol_a[1];
//alert(symbol);
var split_value_8 = myarr_8[1];
//alert(split_value);
var final_value_8 =symbol_st_8.split(".");
var Final_price8 =final_value_8[0];
var j=8;
var total_amount=0;
for(var i=1; i<=j; i++)
{
final_prices=concat("Final_price",i);
alert(final_prices);
symbol_prices=concat("symbol",i);
alert(symbol_prices);
if(isNumber(final_prices)){
alert("number");
/*if(symbol_prices =='+') {
alert("plus");
var total_amount+=parseInt(original_prices)+parseInt(final_prices);
calculated_price_element.innerHTML=total_amount;
alert(total_amount);
} else if(symbol_prices =='-') {
alert("minus");
var total_amount+=parseInt(original_prices)-parseInt(final_prices);
calculated_price_element.innerHTML=total_amount;
alert(total_amount);
}*/
//alert('test');
}
}
}

Cloned objects and reference inside functions

I am trying to do the following:
var element = {};
element.attrA = 'A';
element.attrB = 1;
element.autoAdvance = function(){
var that = this;
setInterval(function(){
that.attrB++;
},100);
}
element.instance = function(){
var clone = $.extend(true, {}, this);
return clone;
}
Now I can do the following just fine:
var e1 = element.instance();
var e2 = element.instance();
e1.attrA = 'not e2s business';
e2.attrA = 'not e1s attrA';
The trouble starts when I try to use autoAdvance:
e1.autoAdvance();
will start the autoAdvance for all cloned 'instances' of element. I am sure this is probably rather trivial but I just don't know how to refer to the parent object inside my autoAdvance-function in a way that it gets properly cloned and only affects the instance. Thanks!
EDIT:
This is the actual code I am using:
var player = {};
player.sprites = {};
player.sprites.back = ['img/playerback_01.png','img/playerback_02.png','img/playerback_03.png'];
player.sprites.head = ['img/playerhead_01.png','img/playerhead_02.png','img/playerhead_03.png'];
player.back = new Image();
player.back.src = player.sprites.back[0];
player.head = new Image();
player.head.src = player.sprites.head[0];
player.loop = function(){
var that = this;
var loop = setInterval(function(){
//remove the [0] state from the sprite array and add it at [2]
var state = that.sprites.head.shift();
that.sprites.head.push(state);
state = that.sprites.back.shift();
that.sprites.back.push(state);
that.back.src = that.sprites.back[0];
that.head.src = that.sprites.head[0];
}, 100);
}
player.x = 0;
player.y = 0;
player.instance = function(){
var clone = $.extend(true, {}, this);
return clone;
}
I generate two players:
var player1 = player.instance();
var player2 = player.instance();
But what is happening is that when I use:
player1.loop();
The animation for player2 will start to play as well.
I suggest you start using "class" in JavaScript. They are more or less a function.
function Player(){
this.sprites={};
......
}
Player.prototype.loop=function(){
....
}
var player1=new Player();
var player2=new Player();
player1.loop();
player2.loop();// this should work better
It doesn't really answer your question but it's an alternative way to write code in a cleaner and better way.

Categories