How to make this javascript, show random post by it's label? - javascript

I have searching about random post and it's show Math.random() function, but because my lack of knowledge about javascripting so I need your help to make this javascript work on random, thanks.
<script type='text/javascript'>
//<![CDATA[[
function CompletedProject(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
var judulPost = json.feed.entry[i].title.$t;
var thumbPost = json.feed.entry[i].media$thumbnail.url;
//var linkPost = json.feed.entry[i].link[1].href;
var linkPost;
// Get rel=alternate for truly post url
for (var j=0; j < json.feed.entry[i].link.length; j++)
{
if (json.feed.entry[i].link[j].rel == 'alternate')
{
linkPost = json.feed.entry[i].link[j].href;
break;
}
}
var showcompleted = '<div class="ani-item"><img alt="'+judulPost+'" class="shine" data-original="'+thumbPost+'"/><h4>'+judulPost+'</h4></div>';
document.write(showcompleted);
}
}
//]]>
</script>
<script src='/feeds/posts/default/-/Complete?alt=json-in-script&callback=CompletedProject'/>

var randomNumber = Math.floor(Math.random() * yourlabels.length);
yourlabels[randomNumber].yourmethod;
That's one way to use Math.random() to generate random integers for use as indexes. Here is a link to a project where I randomly generate a quote and randomly generate a background color with each click of the 'Load Quote' button. Find my Math.random() functions and see if you can incorporate them.
https://github.com/KyleVassella/P1_RandomQuoteGenerator/blob/gh-pages/js/script.js
Math.floor() is a way to round down to the nearest whole number so that Math.random() can be used to represent an index value.
Note that my project also has that seen property which represents a boolean value and is attached to each one of my quote objects - this is used with a 'while' loop to prevent the same quote or background color from randomly generating more than once until each quote has been shown. You may or may not want this feature.

Related

Restart a for loop after the end of an array

I working in JavaScript and am trying to add some images to a site.
I have a list of blog posts on a page. And I have a bunch of small stand-alone images (think small icon images) that I want to place on either side of the blog post feed. They are kind of just like random background images. As the feed gets longer, more images will automatically be placed.
Here is some example code of what I have so far. Right now I am just appending text to the page to get this working.
I need help figuring out how to restart this loop once the end of the array is reached. For example, after 6url.jpg is printed, I want to print 1url.jpg and so on if my imageCount is more than 6. I played around with continue and while loops but not sure how to implement that.
var blogIcons = ["1url.jpg", "2url.jpg", "3url.jpg", "4url.jpg", "5url.jpg", "6url.jpg"];
var blogFeedHeight = $(".blog-feed").height();
var imageDistance = 400;
// Determining how many images to place based on the blog feed height;
var imageCount = Math.ceil(blogFeedHeight/imageDistance);
// the number of images that should be inserted.
for(var i = 0; i < imageCount; i++){
$('blog-feed').append('<div class="blog-icon">' + blogIcons[i] +'</div>')
}
What you are looking for is called modulo, the rest of the euclidian division of 2 numbers.
var blogIcons = ["1url.jpg", "2url.jpg", "3url.jpg", "4url.jpg", "5url.jpg", "6url.jpg"];
var imageCount = 10;
// the number of images that should be inserted.
for (var i = 0; i < imageCount; i++) {
console.log(blogIcons[i % blogIcons.length])
}
I simplified your problem so it can run on StackOverflow. but you'll get the proper index by using "%"
So your script should look like that:
var blogIcons = ["1url.jpg", "2url.jpg", "3url.jpg", "4url.jpg", "5url.jpg", "6url.jpg"];
var blogFeedHeight = $(".blog-feed").height();
var imageDistance = 400;
// Determining how many images to place based on the blog feed height;
var imageCount = Math.ceil(blogFeedHeight/imageDistance);
// the number of images that should be inserted.
for(var i = 0; i < imageCount; i++){
$('blog-feed').append('<div class="blog-icon">' + blogIcons[i % blogIcons.length] +'</div>')
}
You don't need to restart a loop. Instead you can use modulo division to fetch an item within bounds from the array
var blogIcons = ["1url.jpg", "2url.jpg", "3url.jpg", "4url.jpg", "5url.jpg", "6url.jpg"];
for (var i = 0; i < 14; i++) {
console.log(blogIcons[i % blogIcons.length]);
}
When doing i % blogIcons.length you will get a number between 0 and blogIcons.length

Select random img in a cell of a table and print on it with jquery or javascript

Problem: I've to print an image on an arbitrary(the coordinates of this element will be random generated) image inside of a cell, without overwriting the existing content.
Restriction: I've to think that in a secondary moment I've to move this printed image like a chess game, plus I can use only Javascript or jQuery.
This is the link to the pen: ---> codepen
Now, with this functions I set the random coordinates and I know if a cell is walkable or not.
function coordinate(){
let rowCoord= map.length;
let cellCoord = map[1].length;
let coord = {
row: Math.floor(Math.random() * rowCoord),
cell: Math.floor(Math.random() * cellCoord)
}
return coord;
};
function placeCharAndItem(){
let coord= coordinate();
// with this if you choose a walkable table to spawn, this is random generated
if(map[coord.row][coord.cell] === 0){
alert(map[coord.rowCoord][coord.cellCoord]);
place(coord);
}
else{
placeCharAndItem();
}
};
And this is the function where I generate the table:
function mapGenerate(){
var map=createMap(); //the function createMap generates a 2dArray full of 1 and 0.
//loop the 2d array map and change the number with the appropriate img
for(var i = 0; i < map.length; i++) {
var innerArrayLength = map[i].length;
for(var j = 0; j<innerArrayLength; j++){
if(map[i][j] === 0){
map[i][j]="<img class=\"walkable\" src=\"https://image.ibb.co/bGanFz/floor_Resized.png\">";
}else{
map[i][j]="<img class=\"nonWalkable\" src=\"https://image.ibb.co/m9s1az/volcanoresize.png\">";
}
;
}
$("#tableGame").append("<tr><td>"+ map[i].join('') + "<td></tr>")
}
}
Any kind of help is really appreciated.
this is the result that i need to achieve, probably this image will be better than my words :).
You can ignore the red square and the red line, they are just to highlight that the character is in this random img, inside a td
Result
I can't say I really understand your issue, but by looking at your pen I've written this function, hope it helps:
function place(coord, char){
var charImage = $("<img>").attr("src", char.image).addClass('char');
var row = $($("#tableGame tr")[coord.row]);
var cell = $($("td", row)[coord.cell]);
cell.append(charImage);
}
Your map is not being built the way you expect since there are lots of images in a single table cell. Here is how to put an image inside each cell:
function mapGenerate(){
...
$("#tableGame").append("<tr><td>"+ map[i].join('</td><td>') + "</td></tr>")
...
}
https://codepen.io/rafaelcastrocouto/pen/qMEVZz?editors=0010

How do I correctly split an array of strings of is it another issue?

I am trying to access a random element from an array of strings as per other examples here on SO. I am using Raphael.js and regions[j] below returns an array of Raphael objects - hence the .data(id). This seems to be ok, but theCountyNames, as outlined in the comment below returns all of the strings as one long string. I am guessing that this is why randCounty returns a single random letter, but when I try appending a comma in the loop (+",") and using split as per this question, I still get one random single letter. Perhaps I am implementing this incorrectly or maybe it is another issue? Thanks.
function pickRandCounty(){
var theCountyNames = new Array();
for (var j = 0; j < regions.length; j++) {
theCountyNames = regions[j].data('id');
document.write(theCountyNames);//THIS GIVES ME THE COMPLETE LIST OF ITEMS IN THE ARRAY BUT ALL AS ONE STRING
//document.write("<hr>");
}
//var randCounty = theCountyNames[Math.floor(Math.random() * theCountyNames.length)];
//document.write(randCounty);//THIS JUST RETURNS ONE RANDOM LETTER??
}
Using Array.prototype.push to append a new item to an Array.
function pickRandCounty(){
var theCountyNames = [],
j;
for (j = 0; j < regions.length; ++j) {
theCountyNames.push(regions[j].data('id'));
}
j = Math.floor(Math.random() * regions.length);
return theCountyNames[j];
}
However, this is not optimised as you can set the length of the Array in advance and you can even completely skip the loop,
function pickRandCounty(){
var j = Math.floor(Math.random() * regions.length);
return regions[j].data('id');
}
The error seems to be in this part of line.
theCountyNames = regions[j].data('id'); //wrong
theCountyNames.push(regions[j].data('id')); //right
Second mistake
document.write(theCountyNames); //it will keep on appending the string in the DOM
document.write("<br>" + theCountyNames);//right

How to get the complete list of hexadecimal color numbers using a loop in javascript

I haven't done much research I must confess, but help is always welcome. This is the code I have but it's not complete because of my laziness caused by stackoverflows tremendous usefulness. The complete list should have at least 3 million colors.
<script>
var i=0;
document.write("arrayColor=[");
for(var i=10;i<99;i++){
for(var j=10;j<99;j++){
document.write("\"#"+j+""+""+j+""+i+"\""+",")
}
};
document.write("]");
</script>
You can use one loop and toString(16) function to get hex representation of number:
<script>
var colors = [];
for (var i = 0; i < 3000000; i++) {
colors.push("#" + ("000000" + i.toString(16)).slice(-6));
}
document.write(JSON.stringify(colors));
</script>
FIDDLE (document.write changed to console.log and only 300 colors)

Loop through colours array with jQuery

I'm trying to give each div a different background colour. Here is my current code:
http://jsfiddle.net/Uy2FX/2/
var imgColours = ['#FCCF94', '#C4C9E5', '#ADE3D6'];
for (i=0; i < imgColours; i++) {
$('.img').css({backgroundColor: imgColours[0]});
}
However, I'm not quite sure where this is going wrong. I understand that's probably too simple to work, but in my mind it makes sense. Could someone point me in the right direction?
There are some relevant errors in your code.
This is probably what you wanted to do:
// V1 : Basic
var imgColours = ['#FCCF94', '#C4C9E5', '#ADE3D6'];
for (var i=0; i < imgColours.length; i++) {
$('.img:eq('+i+')').css({backgroundColor: imgColours[i]});
}
But if you want to get a random color from your array, for any number of divs, and also optimise your jQuery code a bit for better performance:
// V2 : random colors
var $imgs = $('#boxes1').find('.box'),
imgsCount = $imgs.length,
coloursCount = imgColours.length;
for (var i=0; i < imgsCount; i++) {
var rnd = Math.floor(Math.random() * coloursCount),
color = imgColours[rnd];
$imgs.eq(i).css({backgroundColor: color});
}
Or, if you want to loop through the colours following the order of the array, just change the loop:
// V3 : sequential colors
// Add V2 variables here
for (var i=0; i < imgsCount; i++) {
var color = imgColours[i%coloursCount];
$imgs.eq(i).css({backgroundColor: color});
}
UPDATED FIDDLE: http://jsfiddle.net/Uy2FX/12/
For some very basic tips on jQuery selectors performance: http://www.sitepoint.com/efficient-jquery-selectors/
You are always assigning imgColours[0] to EVERY div. I think what you are looking for is imgColours[i]
You will also need to use imgColours.length to tell your loop how long the array is.
You are also grabbing all HTML elements with the class of img, so this will change all of them each time.
To grab each element separately, you can use the CSS nth-of-type selector. Basically you can just do something like
$(".img:nth-of-type(" + i + ")")
You need to use imgColours.length
The for loop has no idea how long the array is otherwise
Edit: What's the point in this for loop if you end up using imgColours[0] anyways? If you want to loop each color, use i instead of 0.
And either way, this will not achieve a different background per div.
Try selecting by className (I'm going to use vanilla.js because it's simple)
var elements = document.getElementsByClassName("img");
for (var i = 0; i<elements.length; i++) {
var color = imgColours[Math.floor(Math.random()*imgColours.length)]; //get a RANDOM color change me if needed
elements[i].style.backgroundColor = color;
}
How about this?
var ec = 0;
var i = 0;
for(ec; ec < elements.length; ec++, i++) {
elements[ec].style.backgroundColor = imgColours[i];
if(i == (imgColours.length - 1)) i = -1;
}
http://jsfiddle.net/y2dq3/

Categories

Resources