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);
Related
Is there a way for me to make sure each img tag created also contains or can be linked with its individual data from the api? If only one image is returned in the search, it will give me the data for that image. However, if multiple images are returned, once clicked, it will return a only one possible image and data. I am new to coding and javascript in general, so please forgive any rookie mistakes. Thanks!
var scryfallURL = "https://api.scryfall.com/cards/search?q=";
var cardName = "";
var container = $("#list");
$("#searchBtn").on("click", function(event) {
event.preventDefault();
container.empty();
cardName = $("#search").val().trim();
queryURL = scryfallURL + cardName;
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
debugger;
var result = response.data;
console.log(result);
$('#search').val('');
//loops through creating an image tag for each search result
for (let index = 0; index < result.length; index++) {
var showCard = $("#list").append("<image src=' " + result[index].image_uris["normal"] + "' ></image>", "</br>");
var name = result[index].name + "<br>";
var creature = result[index].type_line + "<br>";
var flavorText = result[index].flavor_text + "<br>";
var legality = result[index].legalities + "<br>";
var cardFront = "<image src=' " + result[index].image_uris["large"] + "' ></image>" + "<br>";
};
// click function to clear the div and replace with only one card image and info
showCard.click(function() {
$("#searchForm").empty();
container.empty();
$("#info").append(name, creature, flavorText, legality);
$("#oneCard").append(cardFront);
})
});
});
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.
This is most probably a silly mistake but I can't see the issue. I'm trying to create an array of objects for an image gallery in my Angularjs app. Each photo object has a thumb and img attribute. The for loop is creating the objects fine and I'm logging each to the console to check them:
{thumb: "/10000/0_t.jpg", img: "/10000/0_l.jpg"}
{thumb: "/10000/1_t.jpg", img: "/10000/1_l.jpg"}
{thumb: "/10000/2_t.jpg", img: "/10000/2_l.jpg"}
...
However, after running this code:
var images = [];
var image = {};
for (var i = 0; i < property.images.length; i++) {
image.thumb = "/" + property.id + "/" + i + "_t.jpg";
image.img = "/" + property.id + "/" + i + "_l.jpg";
console.log(image); //this gives expected output
images.push(image);
};
console.log(images); //this gives all entries as the same
the final console.log gives me:
{thumb: "/10000/27_t.jpg", img: "/10000/27_l.jpg"} //X28
for each image. The 27 comes from the fact that there are 28 images but I can't understand why they all have the same paths?
You need to make a new object on each iteration:
var image;
for (var i = 0; i < property.images.length; i++) {
image = {};
image.thumb = "/" + property.id + "/" + i + "_t.jpg";
image.img = "/" + property.id + "/" + i + "_l.jpg";
console.log(image); //this gives expected output
images.push(image);
};
If you don't, then each iteration will re-use that same original object. Passing an object to .push() does not make a copy.
how about this:
var path = "/" + property.id + "/";
var images = property.images.map((img,i)=>{
return {
thumb: path + i + "_t.jpg",
img: path + i + "_l.jpg"
}
});
console.log(images);
Works just fine for me. Please, limit your scope as much as possible in JavaScript.
Refer to chapter 16 Introducing a New Scope via an IIFE in the book; Speaking JavaScript.
Note: An IIFE is an "immediately invoked function expression."
var property = {
id : 10000,
images: [{ id: 1 }, { id: 2 }, { id: 3 }]
};
var images = [];
for (var i = 0; i < property.images.length; i++) {
(function(){
var image = {}; // This should be inside the loop.
// This way the scope does not leak.
image.thumb = "/" + property.id + "/" + i + "_t.jpg";
image.img = "/" + property.id + "/" + i + "_l.jpg";
images.push(image);
}());
};
document.body.innerHTML = '<pre>' + JSON.stringify(images, null, 4) + '</pre>';
I apologize in advance if I'm vague or my code is difficult to understand, I'm still learning this stuff. I'm trying to display information that is stored within an array. I want to display this information when a button is clicked and when it is clicked again, the next index in the array displays its information..
I need help setting up a function that advances to the next index of the array. Thanks!
(function(){
var students =[ //array of information
{name:'john',
address:{
address:'821 Imaginary St',
city:'Chicago',
state:'Il'},
gpa:[4.0,3.5,3.8]},
{name:'jim',
address:{
address:'127 fake Rd',
city:'Orlando',
state:'Fl'},
gpa:[2.5,3.3,3.6]}];
var redBut = document.querySelector('.buttonred');
redBut.onclick = getInfo;
var count = 0;
function getInfo(){
var stn = students[0];
if(count<3){
count++;
document.getElementById('name').innerHTML = 'Name: ' + stn.name; //this is what is to be displayed when the button is clicked
document.getElementById('address').innerHTML = 'Address: ' + stn.address.address + " " + stn.address.city + ", " + stn.address.state;
document.getElementById('gpa').innerHTML = 'GPA: ' + stn.gpa[0] +", " + stn.gpa[1] + ", " + stn.gpa[2];
document.getElementById('date').innerHTML = 'Date: ' + d.toLocaleDateString();
document.getElementById('gpaavg').innerHTML = 'Average GPA: ' + gpas;
}
}
I think you want: var stn = students[count];
And not: var stn = students[0];
(DOH!)
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().