This is all of my code for the object I'm working with, but I'm thinking it's only the "create building in screen" part you really need to help me with.
My goal is to have it where instead of saying class="House houseRed", it says something like class="House +'randomClass'" etc, and that variable holds my other class names(i have 5 total).
It's for a mini-game I'm working on, and I need the buildings that spawn to have different looks, based on their class names.
//CREATE BUILDING IN MEMOMORY
function CreateHouseInMemory() {
//GET VALUES
var sAddress = $("#HouseAddress").val();
var sUniqueId = getUniqueId();
var iMaxResidents = $('input[name=housemaxresidents]').val();
var oHouse = {
sType: "House",
sAddress: sAddress,
sId: sUniqueId,
iMaxResidents: iMaxResidents,
Residents: aResidents = [],
babyInHouse: false
};
oCity.aBuildings.push(oHouse);
console.dir(oCity.aBuildings);
return oHouse;
}
//CREATE BUILDING IN SCREEN
function CreateHouseInScreen(oHouse)
{
$("#City").append('<div id="' + oHouse.sId + '" class="House houseRed" title="' + oHouse.sAddress + '"></div>');
$(".House").draggable();
$(".House").droppable();
}
;
//SPAWN BUILDING
$("#BtnCreateHouse").click(function() {
var oHouse = CreateHouseInMemory();
CreateHouseInScreen(oHouse);
});
Something like this
var classesnames = ['toto', 'titi', 'tata', 'tutu'],
classrandom = classesnames[Math.floor(Math.random() * classesnames.length)];
$("#City").append('<div id="' + oHouse.sId + '" class="House '+ classrandom +'" title="' + oHouse.sAddress + '"></div>');
Create an array of the target class names
var array = ['one', 'two','three','four', 'five'];
//then
var random = array[Math.floor(Math.random() * array.length)]
You can add a class randomly in a way like this:
function CreateHouseInScreen(oHouse)
{
var classes = ['houseRed', 'houseBlue', 'houseGreen'];
var randomIndex = Math.floor(Math.random() * classes.length);
var div = $('<div id="' + oHouse.sId + '" class="House" title="' + oHouse.sAddress + '"></div>');
div.addClass(classes[randomIndex]);
$("#City").append(div);
$(".House").draggable();
$(".House").droppable();
}
You could use something like
i = parseInt(Math.random() * 4)
to either generate an array index for an array of classes, e.g
classArray = ['class1', 'class2', 'class3', 'class4', 'class5']
obj.className = classArray[i]
or convert the integer to a string and append it to a constant string, e.g
obj.className = "myClass" + i.toString().
Related
I extracted value from the title as you can see. But I have problem with the addition. Basically I dont know how to add every .work-day-graph element in .ct-chart. So it will be like 1,25+8,25+0,75+0,5 = XY and 2,25+7,25+2,75+0,5 =XY. Any ideas ? Thanks a lot
DEMO: https://jsfiddle.net/1xn1eLfs/6/
JS:
$('.ct-chart').each(function() {
var graphTitle;
$(this).find('.work-day-graph').each(function() {
graphTitle = $(this).attr('title');
var graphTime = graphTitle.substring(graphTitle.lastIndexOf('(') + 1, graphTitle.lastIndexOf('h'));
//graphTimeVal = graphTime.parseInt();
$('<span class=output-val>' + graphTime + '</br>' + '</span>').appendTo('.output');
});
});
Here's a modified JsFiddle:
https://jsfiddle.net/3woe2cdq/4/
If you want to display the sum for both charts, you need a separate output inside both of them to make it work.
$('.ct-chart').each(function() {
var graphTitle;
// Save the sum of the hours
var graphTimeSum = 0;
$(this).find('.work-day-graph').each(function() {
graphTitle = $(this).attr('title');
var graphTime = graphTitle
.substring(graphTitle
.lastIndexOf('(') + 1, graphTitle
.lastIndexOf('h')
).replace(',', '.');
// Add the current hours to the sum
graphTimeSum += parseFloat(graphTime);
});
// Here we select the output class inside the chart
$('<span class=output-val>' + graphTimeSum + '</br>' + '</span>').appendTo($(this).find('.output'));
});
First, be carefull because you use "," and not "." in your string. To add those number, you must parseFloat on them.
Demo : https://jsfiddle.net/1xn1eLfs/6/
var val = 0;
$('.ct-chart').each(function() {
var graphTitle;
$(this).find('.work-day-graph').each(function() {
graphTitle = $(this).attr('title');
var graphTime = graphTitle.substring(graphTitle.lastIndexOf('(') + 1, graphTitle.lastIndexOf('h'));
graphTime = graphTime.replace(',', '.');
val += parseFloat(graphTime);
$('<span class=output-val>' + graphTime + '</br>' + '</span>').appendTo('.output');
});
});
console.log(val); // 23.5
Do the same but changing the second ct-chart class by ct-chart2 or whatever, so you can add element independently.
Here's my code for gathering titles/posts from reddit's api:
$.getJSON("http://www.reddit.com/search.json?q=" + query + "&sort=" + val + "&t=" + time, function (data) {
var i = 0
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
i++
});
});
Basically every post (selftext) is assigned a different paragraph id (post0, post1, post2, etc) for every result that's pulled. I'm also going to create a "hide" button that follows the same id scheme based on my i variable (submit0, submit1, submit2, etc). I want to write a function so that based on which button they click, it will hide the corresponding paragraph. I've tried doing an if statement that's like if("#hide" + i) is clicked, then hide the corresponding paragraph, but obviously that + i doesn't work. How else can I tackle this?
Could you try something like the below?
showhide = $("<a class='hider'>Show/Hide</a>");
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
}
Alternatively:
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var showhide = $("<a class='hider" + i + "'>Show/Hide</a>");
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
});
i++
});
I have an array object that needs another array object added to it. So i have details of the object that need the rows in a table to be added to that object as an array. I have tried a few suggestions on stackoverflow , but none seems to be working, and i am not sure this has something to do with the fact that the table is created by js.
// Adding Cosignment number
$('#parcel-overview').append(
// Add main tables which will display the added packages
'<table border="1">' +
'<thead><tr><th>Packages</th><th>Weight</th> <th>Vol Weight</th><th>Charge Weight</th> <th>Price</th></tr></thead><tbody id="parcels-added-overview"></tbody> ' +
'</table>'
);
for (var i = 0; i < packageNum; i++) {
var ii = (i + 1).toString();
// Working out volemetric weight
wei = $('#added-parcels #weighting-' + ii + ' input').val();
len = $('#added-parcels #lengthing-' + ii + ' input').val();
wid = $('#added-parcels #widthing-' + ii + ' input').val();
hei = $('#added-parcels #heighting-' + ii + ' input').val();
//Calculating Volumetric weight
tot = ((len * wid * hei) / 5000).toFixed(1);
pri = (tot * 23).toFixed(2);
chr = (tot * 12).toFixed(2);
$('#parcels-added-overview').append(
'<tr>' +
'<td class="par-id">' + (i + 1).toString() + '</td>' +
'<td class="par-weight">' + wei.toString() + ' kg\'s</td>' +
'<td class="par-vol-weight">' + tot.toString() + ' kg\'s</td>' +
'<td class="par-charge-weight">R ' + chr.toString() + '</td>' +
'<td class="par-price">R ' + pri.toString() + ' </td>' +
'</tr>'
);
}
I then want to add the values of that table that have been added dynamically to an object array that is then added to the primary object array.
var parcelObj = new Object();
$.each($('#parcels-added-overview tr'),function (index) {
parcelObj.parcelId = $(this).children('.par-id').text();
parcelObj.totalWeight = $(this).children('.par-weight').text();
parcelObj.volWeight = $(this).children('.par-vol-weight').text();
parcelObj.chargeWeight = $(this).children('.par-charge-weight').text();
parcelObj.overallPrice = $(this).children('.par-price').text();
parcelsArr.push(parcelObj);
});
consignmentObj.parcels = parcelsArr;
consignmentsArr.push(consignmentObj);
I might be a n00b , but this code (although i think its fairly verbose ) should work.
Does the $(this).children not identify directly on each() row that it is iterating over?
When i add console.log(consignmentsArr); i get the array within the object as it should be but the values for the parcel object are just repeating the last row of the table.
1: Object
deliName: ""
deliStreet: ""
docType: "Document"
insurance: "None"
parcels: Array[2]
0: Object
chargeValue:"R34.43"
overallPrice:"R43.54"
parcelId:"2"
totalWeight:"65 kg's"
volWeight:"63 kg's"
1: Object
chargeValue:"R34.43"
overallPrice:"R43.54"
parcelId:"2"
totalWeight:"65 kg's"
volWeight:"63 kg's"
Why can I not get the first row values to be added to parcels[0]?
Thanks
Try to declare parcelObj object inside the function.
$.each($('#parcels-added-overview tr'),function (index) {
var parcelObj = new Object();
parcelObj.parcelId = $(this).children('.par-id').text();
parcelObj.totalWeight = $(this).children('.par-weight').text();
parcelObj.volWeight = $(this).children('.par-vol-weight').text();
parcelObj.chargeWeight = $(this).children('.par-charge-weight').text();
parcelObj.overallPrice = $(this).children('.par-price').text();
parcelsArr.push(parcelObj);
});
consignmentObj.parcels = parcelsArr;
consignmentsArr.push(consignmentObj);
I'm wondering if someone can help me with trying to know why and possible solution to my error. I'm using JavaSript to load images, but when I test my page the src attribute is getting a / at the end of .jpg.
My console looks as follows:
loop: avatars/bugsbunnyundefined
loop: avatars/chimchim.jpg/
loop:avatars/christmastree.jpg/
loop: avatars/princess.jpg/
loop: avatars/squarepants.jpg/
loop: avatars/yosemite.jpg/
loop: avatars/wilma.jpg/
loop: avatars/coatandtie.jpg/
loop: avatars/lilymunster.jpg/
loop: avatars/georgejetson.jpg/
loop: avatars/tweety.jpg/
loop: avatars/cleveland.jpg/
//JavaScript OBJECT
var reviews = [
{ Id: "ajjhwejkssl",
Title: "The little camera that could!",
Rating: 5, Body: "text here",
CreateDate: new Date(2012,5,23,14,12,10,0),
Owner: {
Id: "kwergiueerwq",
Name: "Bugs Bunny",
Url: "./users.html?id=kwergiueerwq",
AvatarImage: "avatars/bugsbunny",
IsFeaturedReviewer: false,
CreateDate: new Date(2012,2,12,9,44,0,0)
}
}]
var data = reviews;
var newDiv = null;
var my_div = null;
var my_img = null;
var total = document.getElementById('total');
var review = $('#reviews');
$(document).ready(function(){
for (var i = 0; i < data.length; i++){
console.log("loop: " + data[i].Owner.AvatarImage + rand);
var rand = ".jpg/";
rand.replace(rand , ".jpg");
//CREATE NEW REVIEW DIV
var reviewPost = "<div class='review'><div class='clear'></div><div class='content'><div class='datePosted'>" + data[i].CreateDate + "</div><div class='avatar'><div class='header'><div class='rating'><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/></div></div><div class='clear'></div><div class='title'>" + data[i].Title + "</div><div class='memberImg'><img class='userImg' src=" + data[i].Owner.AvatarImage + '.jpg'+"/></div><div id='member'><div class='reviewedBy'>Reviewed by <a href='"+data[i].Owner.Url+"' class='member'>" + data[i].Owner.Name + "</a></div><div class='membership'>Member Since " + data[i].Owner.CreateDate + "</div></div></div></div><div class='clear'></div><div class='message'>" + data[i].Body + "</div></div><div class='clear'></div>";
//adds reviewPost inside of reviews
review.append(reviewPost);
$.each(".userImag" , function (){
//console.log("data: " + data[i].Owner.AvatarImage);
$(this).attr('src', data[i].Owner.AvatarImage + 'jpg');
});
}
});
I think the problem is in
var rand = ".jpg/";
rand.replace(rand , ".jpg");
the String.replace method just returns a changed string but do NOT change the original one.
String.replace
Description
This method does not change the String object it is called on. It simply returns a new string.
Take a look at this code:
console.log("loop: " + data[i].Owner.AvatarImage + rand);
var rand = ".jpg/";
rand.replace(rand , ".jpg");
The first line you're adding "+ rand" which rand has not be defined.
The second line you are setting the rand variable
And the third line is pretty much being ignored because no variable is being assigned to it. I don't think .jpg/ is actually in your image's source.
Josh
var rand = ".jpg/";
rand.replace(rand , ".jpg");
This doesnt make any sense at all. You are asigning a variable a value and replace that variable by itself ._0
You may want something like this:
var StringContainingFilePath;
var search = ".jpg/";
var replace = ".jpg";
StringContaingingFilePath = StringContaingingFilePath.replace(search,replace);
I am creating hangman in javascript and I have (I think) successfully generated a random word from an array in a function, to check if it works I am trying to print the generated word in to the console but it doesn't seem to be working here's my code for the function
var word = function() //Random word is genereated from an array for the user to guess
{
GameWordArray = new Array(7);
GameWordArray[0] = "monitor";
GameWordArray[1] = "program";
GameWordArray[2] = "application";
GameWordArray[3] = "keyboard";
GameWordArray[4] = "javascript";
GameWordArray[5] = "gaming";
GameWordArray[6] = "network";
randno = Math.floor(Math.random() * GameWordArray.length);
document.write(GameWordArray[randno]);
console.log(word);
}
Thanks in advance :)
Here is an example on jsfiddle
var words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];
var word = words[Math.floor(Math.random() * words.length)];
console.log(word);
document.getElementById("word").textContent = word;
And to have it fit in directly with you present code:
var getRandomWord = function () {
return words[Math.floor(Math.random() * words.length)];
};
Try using it this way:
var getRandomWord = (function () {
var gameWordArray = [];
gameWordArray.push("monitor");
gameWordArray.push("program");
gameWordArray.push("application");
gameWordArray.push("keyboard");
gameWordArray.push("javascript");
gameWordArray.push("gaming");
gameWordArray.push("network");
return function () {
var randNum, finalWord;
randNum = Math.floor(Math.random() * gameWordArray.length);
finalWord = gameWordArray[randNum];
return finalWord;
};
})();
DEMO: http://jsfiddle.net/bCEFA/1/
Instead of declaring an array with a predefined length, you might as well declare an empty one and add values to the end of it (with .push()). You could've also declared the array like:
var gameWordArray = ["monitor", "program", ...];
You were trying to print word (which I renamed to getRandomWord), which was/is a function. You probably meant to use console.log(gameWordArray[randno]), which should work.
That's what helped me to avoid duplicate alt tags for my online shop:
var items = ['word1', 'word2', 'word3'];
var item = items[Math.floor(Math.random() * items.length)];
I even doubled it and had a much more range on unique alt tags:
var items2 = ['word4', 'word5', 'word6'];
var item2 = items2[Math.floor(Math.random() * items2.length)];
And in the end it looked like this for my alt-tags on my product gallery thumbnails:
markup += '<div class="product-image-thumbnail"><img alt="' + alt + ' ' + item + ' ' + item2 + '" title="' + title + '" src="' + image + '" /></div>';