JavaScript-produced elements not working - javascript

I am making a game so I stared at it for awhile (and yes, I did look at the developer log console for errors), and found no errors (within my reasoning) of why it wouldn't open a battle function.
It is saying that for whatever reason that Giant is not defined when clicked, Zombie is not defined when clicked, and for Giant Spider it says something along the lines of missing parameter. I am quite sure it falls down to the code below -->
for(var z = 0; z < monsters.length; z++) {
Gid("atkOpt_container").innerHTML += ("<div onclick='battle(" + monsters[z].name + "," + this.value + ")' class='monsterContainer' value=" + z + "><div class='monsterT'>" + monsters[z].name + "</div><table><tr><td>Strength</td><td>Health</td><td>XP</td><td>Level</td></tr><tr><td>" + monsters[z].dmg + "</td><td>" + monsters[z].hp + "</td><td>" + monsters[z].xp + "</td><td>" + monsters[z].lvl + "</td></tr></table></div>");
}
If you wish to look at all the code look below. And if you're wondering why everything is so small it's because I'm making it on my phone, and transferred it to ask via GitHub.
var monsters = []; //All monsters are stored here
//All types of monsters are listed below
monsters.push(new monster_prototype("Giant", 50, 30, 1, 20, 20));
monsters.push(new monster_prototype("Giant spider", 20, 50, 1, 15, 30));
monsters.push(new monster_prototype("Zombie", 50, 50, 2, 40, 70));
for (var z = 0; z < monsters.length; z++) {
Gid("atkOpt_container").innerHTML += ("<div onclick='battle(" + monsters[z].name + "," + this.value + ")' class='monsterContainer' value=" + z + "><div class='monsterT'>" + monsters[z].name + "</div><table><tr><td>Strength</td><td>Health</td><td>XP</td><td>Level</td></tr><tr><td>" + monsters[z].dmg + "</td><td>" + monsters[z].hp + "</td><td>" + monsters[z].xp + "</td><td>" + monsters[z].lvl + "</td></tr></table></div>");
} //Where I believe the error occurs, it basically loads all monster stats into a div
function Gid(id) {
return document.getElementById(id);
} //So I don't have to write the whole document.getElementById
function monster_prototype(name, hp, dmg, lvl, xp, money) {
this.name = name;
this.hp = hp;
this.dmg = dmg;
this.lvl = lvl;
this.xp = xp,
this.money = money;
} //How I store the monsters info
function save() {
localStorage.player = JSON.stringify(playerStats);
}
var playerStats = {
lvl: 1,
xp: 0,
xpToLvl: 100,
name: null,
dmg: null,
hp: null,
money: 100
};
if (localStorage.player === undefined) {
save();
playerSetup();
} else {
playerStats = JSON.parse(localStorage.player);
alert("Welcome back " + playerStats.name);
refreshStats();
} //Checks if the player is new, and if so starts the main player setup. If not it loads it
function refreshStats() {
Gid("maxDmg").innerHTML = "Max damage: " + playerStats.dmg;
Gid("hp").innerHTML = "Health: " + playerStats.hp;
} //Refreshes some stats
function playerSetup() {
document.getElementById("mainContainer").style.display = "none";
$("#class_container").show();
}
function classChosen(pClass) {
if (pClass === "Juggernaut") {
playerStats.hp = 100;
playerStats.dmg = 10;
} else if (pClass === "Average Joe") {
playerStats.hp = 60;
playerStats.dmg = 30;
} else {
playerStats.hp = 40;
playerStats.dmg = 70;
}
refreshStats();
document.getElementById("class_container").style.display = "none";
var getName = prompt("What is your name?");
playerStats.name = getName;
document.getElementById("mainContainer").style.display = "block";
save();
} //Starts the class choosing feature
function toggle(id) {
$("#" + id).toggle();
} //Toggles display (Hidden or block)
function restartGame() {
localStorage.removeItem('player');
location.reload();
}
function battle(enemy, enemyLoc) {
console.log(enemy + " and " + enemyLoc);
enemy = enemy.toLowerCase();
Gid("attackInfo").innerHTML = "";
var battleWords = ['slashed', 'bashed', 'stabbed', 'punched'];
var enemyHp = monsters[enemyLoc].hp;
var enemyDmg = monsters[enemyLoc].dmg;
var playerHp = playerStats.hp;
var playerDmg = playerStats.dmg;
var battleLoop = setInterval(function() {
var atkName1 = Math.floor(Math.random() * battleWords.length);
var atkName2 = Math.floor(Math.random() * battleWords.length);
var enemyDealt = Math.round(Math.random() * enemyDmg);
var playerDealt = Math.round(Math.random() * enemyDmg);
playerHp -= enemyDealt;
enemyHp -= playerDealt;
Gid("attackInfo").innerHTML += ("<strong>•</strong>" + enemy + " " + battleWords[atkName1] + " you and dealt " + enemyDealt + " damage to you and you now have " + playerHp + " health remaining.<br>You " + battleWords[atkName2] + " the " + enemy + " and dealt " + playerDealt + " damage. The " + enemy + " has " + enemyHp + " health remaining.<br><br>");
if (enemyHp <= 0 && playerHp <= 0) {
clearInterval(battleLoop);
alert("You both died at the same time! A win... but mainly a loss. Game over");
restartGame();
} else if (enemyHp <= 0) {
clearInterval(battleLoop);
alert("You won!");
playerStats.money += monsters[enemyLoc].money;
playerStats.xp += monsters[enemyLoc].xp;
if (playerStats.xp >= playerStats.xpToLvl) levelUp();
} else if (playerHp <= 0) {
alert("Game over");
clearInterval(battleLoop);
restartGame();
}
}, 1000);
} //Main battle, this is the function that won't load
function levelUp() {
} //TBA
#container {
background-color: gray;
width: 300px;
height: 350px;
margin: auto;
}
#atkOpt_container {
display: none;
}
#attackBtn {
background-color: black;
width: 96px;
color: yellow;
border: 4px groove red;
float: left;
font-size: 30px;
text-align: center;
display: block;
margin-top: 5px;
margin-left: 5px;
}
#attackInfo {
float: left;
background-color: #eee;
width: 200px;
font-size: 10px;
height: 250px;
clear: left;
display: block;
margin-top: 5px;
margin-left: 5px;
border: 2px solid red;
}
#class_container {
z-index: 10;
display: none;
width: 300px;
height: 150px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: orange;
overflow: auto;
border: 5px groove black;
}
.playerClass {
margin: auto;
width: 200px;
border: 5px groove red;
color: #00FF00;
font-size: 35px;
text-align: center;
margin-bottom: 5px;
display: block;
background-color: black;
}
#title {
width: 95%;
background-color: black;
color: #00FF00;
border: 1px solid orange;
font-size: 25px;
font-weight: bolder;
text-align: center;
margin: auto;
}
#atkOpt_container {
z-index: 11;
width: 275px;
height: 300px;
overflow: auto;
background-color: black;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
border: 2px solid orange;
}
.monsterContainer {
width: 200px;
margin: auto;
text-align: center;
background-color: orange;
border: 5px groove red;
margin-bottom: 5px;
}
.monsterT {
width: 100%;
background-color: black;
color: #eee;
font-size: 30px;
text-align: center;
}
td {
background-color: Cyan;
font-size: 15px;
width: 49%;
border: 1px solid black;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="class_container">
<div id="title">Choose a class</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Juggernaut</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Masculine Mat</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Average Joe</div>
</div>
<div id="mainContainer">
<div id="container">
<div id="attackBtn" onclick="toggle('atkOpt_container'); toggle('mainContainer');">Attack</div>
<div id="attackInfo"></div>
<div id="maxDmg">Max damage: 0</div>
<div id="hp">Health: 0</div>
</div>
<button onclick="restartGame();">Delete stats</button>
</div>
<div id="atkOpt_container"></div>
</body>
</html>

Because
"<div onclick='battle(" + monsters[z].name + "," + this.value + ")'
produces
<div onclick='battle(whatever, whatever)'
Which is wrong, because you do not have quotes around the strings. You need to quote them. So add in the "
"<div onclick='battle(\"" + monsters[z].name + "\",\"" + this.value + "\")'
Ideally you would use DOM methods such as createElement and addEventListener so you would not have to deal with this.

Related

Make CSGO Case Opener Responsive (CSS)

I am trying to implement CSGO like case opener code on my website.
Code can be found here:
https://codepen.io/killerek/pen/ObBOJE
I am trying to make it responsive on all screens (full width and centered), but when I resize the window or open it on a mobile device, the red arrow is not in the center. After changing the CSS of the arrow-down class to margin-left:50%; and after centering the cardList class with full screen width: "width: 100%; margin: auto;" 2 problems arise:
After resizing the window, the red arrow is always centered (correct behaviour) but the items in the cardList are not moving (even if the arrow would be pointing at the won item, the arrow is moving, but not the item)
Now the arrow is not pointing at the right item, it has something to do with this code:
$('.card').first().animate({ marginLeft: -rand }, 5000, timing,
function(){ ... }
The spin is animated based on the generated random reward, but I dont know what value to put there in order for it to work.. I am guessing the marginLeft should be changed in % values instead.
I would like to ask for help in this matter.
Relevant CSS code:
#cardList {
height: 100px;
width: 800px;
position: relative;
overflow: hidden;
white-space: nowrap;
}
.card {
display: inline-block;
text-align: center;
width: 100px;
height: 100px;
}
.arrow-down {
margin-left: 380px;
width: 0;
height: 0;
}
Relevant JS code:
var rand = random(1000,20000);
var childNumber = Math.floor(rand/100)+4;
var timings = ["easeInOutBack","easeOutExpo","easeInOutBounce","easeOutQuad","swing","easeOutElastic","easeInOutElastic"];
var timing = timings[random(0,timings.length)];
var reward = $('#itemNumber'+childNumber).attr('data-rarity');
$('.card').first().animate({
marginLeft: -rand
}, 5000, timing, function(){ ... }
EDIT:
I think I´ve gotten closer with the following change in the JavaScript, the cards are now more responsive, but the won item still leaves the arrow.
var mywidth = (rand*100) / screen.width;
$('.card').first().animate({
marginLeft: -mywidth+"%"
}, 5000, timing, function(){ ... }
EDIT 2:
Current state of the codepen code
https://codepen.io/chris-fodor/pen/GRxjpYO
I've restructured the styling little bit, try this one.
var img = {
blue: '<img src="https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpopujwezhhwszYI2gS09-5mpSEguXLPr7Vn35c18lwmO7Eu9TwjVbs8xVqZm_3J4TGcVU3YFCE-Ae5weq81JXovJXLyiRjvyFw4nfD30vgN-NX6nY/360fx360f"/>',
purple: '<img src="http://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgposr-kLAtl7PLZTjlH7du6kb-FlvD1DLfYkWNF18lwmO7Eu46h2QS1r0tvZjvyLI-RIwI6aV7X_ADrwevmhZO0up_AwSM1uHNw5nzD30vgQ0tV-jw/360fx360f"/>',
pink: '<img src="https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgposr-kLAtl7PLZTjlH_9mkgIWKkPvxDLDEm2JS4Mp1mOjG-oLKhF2zowcDPzixc9OLcw82ZlyF8wC8wb251MW4tcifmydi7CEn4HiPlhyy1BxJbeNshqPIHELeWfJvK5CfiA/360fx360f"/>',
red: '<img src="https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot7HxfDhjxszJemkV09-5gZKKkPLLMrfFqWZU7Mxkh9bN9J7yjRrhrUFuazjzJteVJlQ6NVHTrFe3wObs15G06picwHFnvid25C3bnhSzn1gSOQz0szG-/360fx360f"/>',
yellow: '<img src="http://vignette4.wikia.nocookie.net/cswikia/images/a/ad/Csgo-default_rare_item.png/revision/latest?cb=20150227163025"/>'
}
function reset() {
$('.card').remove();
for (var i = 0; i < 210; i++) {
var element = '<div class="card" style="background-color: lightblue;" data-rarity="blue" id=itemNumber' + i + '>' + img.blue + '</div>';
var rand = random(1, 10000) / 100;
if (rand < 20) {
element = '<div class="card" style="background-color: purple;" data-rarity="purple" id=itemNumber' + i + '>' + img.purple + '</div>';
}
if (rand < 5) {
element = '<div class="card" style="background-color: hotpink;" data-rarity="pink" id=itemNumber' + i + '>' + img.pink + '</div>';
}
if (rand < 2) {
element = '<div class="card" style="background-color: red;" data-rarity="red" id=itemNumber' + i + '>' + img.red + '</div>';
}
if (rand < 0.5) {
element = '<div class="card" style="background-color: yellow;" data-rarity="yellow" id=itemNumber' + i + '>' + img.yellow + '</div>';
}
$('#cardList').append(element);
}
$('.card').first().css('margin-left', -1000);
}
function openCase() {
reset();
var rand = random(1000, 20000);
var childNumber = Math.floor(rand / 100) + 4;
var timings = ["easeInOutBack", "easeOutExpo", "easeInOutBounce", "easeOutQuad", "swing", "easeOutElastic", "easeInOutElastic"];
var timing = timings[random(0, timings.length)];
var reward = $('#itemNumber' + childNumber).attr('data-rarity');
var mywidth = (rand * 100) / screen.width;
$('.card').first().animate({
marginLeft: -mywidth + "%"
}, 5000, timing, function() {
var src = $('#itemNumber' + childNumber + ' img').attr('src');
$('#itemNumber' + childNumber).css({
background: "linear-gradient(#00bf09, #246b27)"
});
$('#dialog-msg').html("You have received " + reward + " item!" + "<br><img src=" + src + ">");
$('#dialog').dialog({
modal: true,
title: "New item!",
resizeable: false,
draggable: false,
width: 400,
buttons: {
"Receive item": function() {
$(this).dialog("close");
// add resources
}
}
});
});
//$('.card').css({backgroundColor: 'red'})
//$('.card:nth-child('+(childNumber+1)+')').css({backgroundColor: 'green'})
}
function random(min, max) {
return Math.floor((Math.random() * (max - min)) + min);
}
* {
box-sizing: border-box;
}
#cardList {
height: 100px;
width: 800px;
position: relative;
border: 2px solid black;
overflow: hidden;
white-space: nowrap;
}
.card {
display: inline-block;
background-color: red;
text-align: center;
border-left: 1px solid black;
border-right: 1px solid black;
width: 100px;
height: 100px;
}
.card>img {
width: 100px;
height: 100px;
}
.arrow-down {
margin-left: 380px;
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 20px solid #f00;
}
#dialog-msg>img {
width: 150px;
height: 150px;
}
#dialog-msg {
text-align: center;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<div id=unbox-area>
<div class="arrow-down"></div>
<div id=cardList></div>
</div>
<button onclick="openCase();">Open</button>
<div id=dialog>
<div id=dialog-msg></div>
</div>
</body>
</html>

how to avoid document.write my below code

This code is working, but google pagespeed detect avoid document.write.
I've tested various alternatives, lining up my HTML elements prior to the JS, then using getElementById, followed by either innerHTML or appendChild, or even lining up the elements inside the JS, by means of createElement, but to no avail, really. maybe my tested was wrong.
Probably a factor as to why they're doing so poorly. I'm sure I couldn't sort the above codes correctly. I'm basically not experienced in JavaScript.
Here is my CSS/HTML/JS inside this snipet code:
.cat-back {
font-size: 18px;
font-weight: 400;
border-bottom: 1px solid #000;
margin-top: 13px;
margin-bottom: 5px;
padding: 5px;
border-left: 3px solid #000
}
.row:after {
content: "";
display: table;
clear: both
}
.catcol {
float: left;
width: 33.33%;
padding: 10px;
box-sizing: border-box
}
.mbtlist {
list-style-type: none;
overflow: hidden
}
.mbtlist li {
margin: 0px auto 20px auto;
clear: both;
color: #666;
font-family: Helvetica;
font-size: 12px;
border-bottom: 1px dotted #ddd;
padding-bottom: 10px;
}
.mbtlist .mbttitle {
font-family: oswald;
font-size: 16px;
color: #0080ff;
font-weight: normal;
text-decoration: none;
}
.mbtlist .mbttitle:hover {
color: #00A5FF;
}
font-family:georgia;
font-size:15px;
font-weight:bold
}
.mbtlist div span {
margin: 0 10px 0 0;
display: inline-block;
}
.mbtlist span {
display: block;
margin: 5px 0px 0px;
padding-right: 5px;
}
.mbtlist .imore {
font-size: 16px;
font-weight: bold;
text-decoration: none;
color: #666;
line-height: 0.7em;
}
.mbtlist img {
float: left;
margin: 0px 10px 10px 0px;
border: 6px solid #fff;
padding: 0px;
width: 80px;
height: 65px;
box-shadow: -1px -1px 4px #777;
}
.mbtlist .icontent {
text-align: justify;
}
<script>
//----------------------------Defaults
var ListBlogLink = window.location.hostname;
var ListCount = 5;
var TitleCount = 70;
var ListLabel = " ";
var ChrCount = 80;
var ImageSize = 100;
//----------------------------Function Start
function mbtlist(json) {
document.write('<ul class="mbtlist">');
for (var i = 0; i < ListCount; i++) {
//-----------------------------Variables Declared
var listing = ListUrl = ListTitle = ListConten = ListContent = ListImage = thumbUrl = sk = "";
//----------------------------- Title URL
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
break;
}
}
ListUrl = "'" + json.feed.entry[i].link[j].href + "'";
//----------------------------------- Title Stirng
if (json.feed.entry[i].title != null) {
ListTitle = json.feed.entry[i].title.$t.substr(0, TitleCount);
}
//----------------------------------- Content Check
ListConten = json.feed.entry[i].content.$t;
ListContent = ListConten.replace(/(<([^>]+)>)/ig, "").substr(0, ChrCount);
//------------------------------------ Thumbnail Check
if (json.feed.entry[i].media$thumbnail) {
thumbUrl = json.feed.entry[i].media$thumbnail.url;
sk = thumbUrl.replace("/s72-c/", "/s" + ImageSize + "/");
ListImage = "'" + sk.replace("?imgmax=800", "") + "'";
}
// Support For 3rd Party Images
else if (json.feed.entry[i].content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/) != null) {
ListImage = json.feed.entry[i].content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)[1];
} else {
ListImage = "'http://4.bp.blogspot.com/-HALLtgFeep0/VfryhQ0C5oI/AAAAAAAAPcY/77mSGND4q84/s200/Icon.png'";
}
//----------------------------------- Printing List
var listing = "<li><a href=" +
ListUrl +
"><img src=" +
ListImage +
"/></a><a class='mbttitle' href=" +
ListUrl +
"target='_blank'>" +
ListTitle +
"</a><span class='icontent'>" +
ListContent +
" ... <a href=" +
ListUrl +
" class='imore'>»</a></span></li>";
document.write(listing);
}
document.write("</ul>");
}</script>
<div class='row'>
<div class='catcol'><div class='cat-back'><h3>Seba Top</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "seba-top";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
<div class='catcol'><div class='cat-back'><h3>Lead News</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "lead-news";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
<div class='catcol'><div class='cat-back'><h3>Top News</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "top-news";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
</div>
<div class='row'>
<div class='catcol'><div class='cat-back'><h3>জাতীয়</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "জাতীয়";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
<div class='catcol'><div class='cat-back'><h3>রাজনীতি</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "রাজনীতি";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
<div class='catcol'><div class='cat-back'><h3>বিশ্ব</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "বিশ্ব";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
</div>
Would it be possible for anyone to point me to the right direction?
Please solve this problem any one.
So based on new code I suggest this
//----------------------------Defaults
var ListBlogLink = "https://www.sebahotnews.org",
ListCount = 4,
TitleCount = 70,
ChrCount = 150,
ImageSize = 100;
const lists = [{"label":"seba-top" },{"label":"lead-news" },{"label":"top-news" }]
let cnt = 0;
function next() {
if (cnt>=lists.length) return
document.getElementById("container").innerHTML += `<div class='catcol ${lists[cnt].label}'></div>`
const scr = document.createElement("script");
scr.src = ListBlogLink + "/feeds/posts/default/-/" + lists[cnt].label + "?alt=json-in-script&callback=mbtlist";
document.querySelector("head").appendChild(scr);
};
next(); // start
function mbtlist(json) {
let div = document.querySelector("#container ."+lists[cnt].label);
let html = '<ul class="mbtlist">';
for (var i = 0; i < ListCount; i++) {
//-----------------------------Variables Declared
var listing = ListUrl = ListTitle = ListConten = ListContent = ListImage = thumbUrl = sk = "";
//----------------------------- Title URL
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
break;
}
}
ListUrl = "'" + json.feed.entry[i].link[j].href + "'";
//----------------------------------- Title Stirng
if (json.feed.entry[i].title != null) {
ListTitle = json.feed.entry[i].title.$t.substr(0, TitleCount);
}
//----------------------------------- Content Check
ListConten = json.feed.entry[i].content.$t;
ListContent = ListConten.replace(/(<([^>]+)>)/ig, "").substr(0, ChrCount);
//------------------------------------ Thumbnail Check
if (json.feed.entry[i].media$thumbnail) {
thumbUrl = json.feed.entry[i].media$thumbnail.url;
sk = thumbUrl.replace("/s72-c/", "/s" + ImageSize + "/");
ListImage = "'" + sk.replace("?imgmax=800", "") + "'";
}
// Support For 3rd Party Images
else if (json.feed.entry[i].content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/) != null) {
ListImage = json.feed.entry[i].content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)[1];
} else {
ListImage = "'http://4.bp.blogspot.com/-HALLtgFeep0/VfryhQ0C5oI/AAAAAAAAPcY/77mSGND4q84/s200/Icon.png'";
}
//----------------------------------- Printing List
var listing = "<li><a href=" +
ListUrl +
"><img src=" +
ListImage +
"/></a><a class='mbttitle' href=" +
ListUrl +
"target='_blank'>" +
ListTitle +
"</a><span class='icontent'>" +
ListContent +
" ... <a href=" +
ListUrl +
" class='imore'>»</a></span></li>";
html += listing;
}
html += "</ul>";
div.innerHTML = html;
cnt++;
next(); // call next
}
.seba-top { background-color:orange;}
.top-news { background-color:tan;}
.lead-news { background-color:yellow;}
.catcol {
float: left;
width: 33.33%;
padding: 10px;
box-sizing: border-box;
border: 1px solid black;
}
.mbtlist {
list-style-type: none;
overflow: hidden
}
.mbtlist li {
margin: 0px auto 20px auto;
clear: both;
color: #666;
font-family: Helvetica;
font-size: 12px;
border-bottom: 1px dotted #ddd;
padding-bottom: 10px;
}
.mbtlist .mbttitle {
font-family: oswald;
font-size: 16px;
color: #0080ff;
font-weight: normal;
text-decoration: none;
}
.mbtlist .mbttitle:hover {
color: #00A5FF;
}
font-family:georgia;
font-size:15px;
font-weight:bold
}
.mbtlist div span {
margin: 0 10px 0 0;
display: inline-block;
}
.mbtlist span {
display: block;
margin: 5px 0px 0px;
padding-right: 5px;
}
.mbtlist .imore {
font-size: 16px;
font-weight: bold;
text-decoration: none;
color: #666;
line-height: 0.7em;
}
.mbtlist img {
float: left;
margin: 0px 10px 10px 0px;
border: 6px solid #fff;
padding: 0px;
width: 80px;
height: 65px;
box-shadow: -1px -1px 4px #777;
}
.mbtlist .icontent {
text-align: justify;
}
<div id="container"></div>

On Click not updating the output of a function

$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
changeUnits();
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
I am trying to use a button on click event to change the temp display, but it doesn't seem to work like this. The function keeps seeing Celsius no matter what. I tried $(this).html too. The text of the button is actually changing, just the function isn't updating. I tried running the change units function inside the the button click even as well and it still doesn't update.
What am I not understanding about this onclick event and how can I get it to work.
JS Code:
var apiKey = "get your own key from http://openweathermap.org";
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
changeUnits();
});
$(function() {
var loc;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
//weather API call
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
function(weather) {
var currentLocation = weather.name;
var currentConditions = weather.weather[0].description;
var currentTemp = changeUnits(weather.main.temp);
var high = changeUnits(weather.main.temp_max);
var low = changeUnits(weather.main.temp_min);
var currentWind = weather.wind.speed;
var currentWdir = weather.wind.deg;
var sunRise = weather.sys.sunrise;
var sunSet = weather.sys.sunset;
var icon = weather.weather[0].icon;
//set HTML elements for weather info
$('#currentLocation').append(currentLocation);
$('#currentTemp').html(currentTemp);
$('#high-low').html('<span id="high">High: ' + high + '</span><br>'
+ '<span id="low">Low: ' + low + '</span>');
$('#currentConditions').html(currentConditions);
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
});
});
});
HTML:
<html>
<head>
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
<title></title>
</head>
<body>
<div id="header">
<div class="left"><h1 id="currentLocation">Your Current Location is </h1></div>
<div class="navbar"></div>
<div class="right"><i class="fa fa-github bigger_icon"></i></div>
</div>
<div id="container">
<h2 class="text-center content-title" id="currentTemp"></h2>
<div class="content-body text-center">
<p id="high-low"></p>
<button data-text-swap="Fahrenheit" id="unitButton" type="button" class="btn btn-success">Celsius</button>
<p id="currentConditions"></p>
</div>
</div>
</body>
</html>
I have done every change I can think of. console.log(el.text()) in the onclick clearly shows the text changing; but the function for changeUnits never seems to pick it up in the if statement when I run the function again during the onclick.
Looks like you're using html() instead of text(). I assume you're looking for button text instead of html, so try this:
$('.btn').on("click", function() {
$(this).text(function(f, c) {
return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
});
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius'){
return Math.round(Temp - 273.15) + " &degC";
}else{
return Math.round((Temp* (9/5)) - 459.67) + " &degF";
}
}
you are not calling the function, read comments in code
Also you are not passing any information to the '.btn' in the function passed to the text method.
$('.btn').on("click", function() {
var text = function(f, c) { // where are you getting your f and c parameters?
console.log(f); // should be undefined
console.log(c); // should be undefined
return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
}();
console.log(text); // should be 'Celsius'
$(this).text(text); // changed from }) to }())
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius') // change html() to text() as well
return Math.round(Temp - 273.15) + " &degC";
else
return Math.round((Temp* (9/5)) - 459.67) + " &degF";
}
Additionaly you should use a ID to associate your button to do this
<input id='thisID'>
// then call it in javascript
$("#thisID")
Toggleing the button
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
});
Here is what I think is your problem. I didn't get to test it because I need to get the weather API and stuff. By looking at your code, here is what I get.
When the page loads, you are getting weather data from OpenWeatherMap. However, you are not cashing this info in some sort of global variable in order for you to access it later. You have declared all your variables inside the ajax callback and you have no way of accessing them later.
Try to do this:
var currentTemp;
var high;
var low;
$(function() {
var loc;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
//weather API call
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
function(weather) {
var currentLocation = weather.name;
var currentConditions = weather.weather[0].description;
currentTemp = weather.main.temp;
high = weather.main.temp_max;
low = weather.main.temp_min;
var currentWind = weather.wind.speed;
var currentWdir = weather.wind.deg;
var sunRise = weather.sys.sunrise;
var sunSet = weather.sys.sunset;
var icon = weather.weather[0].icon;
//set HTML elements for weather info
$('#currentLocation').append(currentLocation);
updateDisplay();
$('#currentConditions').html(currentConditions);
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
});
});
});
function changeUnits(Temp) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
updateDisplay();
});
function updateDisplay(){
$('#currentTemp').html(changeUnits(currentTemp));
$('#high-low').html('<span id="high">High: ' + changeUnits(high) + '</span><br>'
+ '<span id="low">Low: ' + changeUnits(low) + '</span>');
}
I have introduced another function updateDisplay() to actually handle the changing of the displayed temps. As I said, I didn't get to test it. But I am pretty sure it will work.
JS:
var apiKey="get an openweathermap APIKey";
var loc;
var lat;
var long;
var temp;
var high;
var low;
var icon;
//var wind;
//var windDir;
//var windSpd;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
lat = parseFloat(loc[0]);
long = parseFloat(loc[1]);
getWeather(lat, long);
initGmaps(lat, long);
});
//api call to use lat and long to generate a map
window.addEventListener('load', function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '?key=AIzaSyDKgEmSnYmFmbhQVGY8K6NXxV5ym2yZXdc&callback=initMap';
document.body.appendChild(script);
});
function initGmaps(lat, long) {
var map = new GMaps({
div: '#map',
lat: lat,
lng: long,
zoom: 14,
disableDefaultUI: true,
mapTypeId: "satellite",
});
map.addMarker({
lat: lat,
lng: long
});
}
//using weather to get data and plug it into our page
function getWeather(lat, long) {
var api = 'http://api.openweathermap.org/data/2.5/weather?lat=' +
lat + '&lon=' + long + '&appid=' + apiKey;
$.ajax({
url: api,
dataType: 'json',
success: function(data) {
temp = {
f: Math.round(((data.main.temp * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp - 273.15)) * 100) / 100 + " °C"
};
high = {
f: Math.round(((data.main.temp_max * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
};
low = {
f: Math.round(((data.main.temp_min * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
};
windSpd = {
f: Math.round((data.wind.speed * 2.23694)*10)/10 + " MPH",
c: Math.round((data.wind.speed)*10)/10 + " M/S"
};
var windArr = ["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];
var windDir = windArr[Math.floor(((data.wind.deg/22.5)+.5))];
$('#currentLocation').append(data.name);
$('#high').append(" " + high.f);
$('#low').append(" " + low.f);
$('#currentTemp').html(temp.f);
$('#weatherDesc').html(data.weather[0].description);
$('#windDir').html(windDir);
$('#windDir').append('<span id="windSpd">' + windSpd.f + '</span>');
icon = data.weather[0].icon;
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').html('<img id="weatherImg" src="' + iconSrc + '"><br>');
}
});
}
$('#currentTemp').on('click', function() {
var current = $(this).data('nexttemp');
$('#currentTemp').text(temp[current]);
$('#high').html(high[current]);
$('#low').html(low[current]);
$('#windSpd').html(windSpd[current]);
if (current == 'c') {
$(this).data('nexttemp', 'f');
return;
}
$(this).data('nexttemp', 'c');
});
HTML:
<html>
<head>
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
<title></title>
</head>
<body>
<div id="header">
<div class="left"></div>
<div class="navbar"><h4>Free Code Camp Weather App</h4></div>
<div class="right"><i class="fa fa-github bigger_icon"></i></div>
</div>
<div id="container">
<div class="col-lg-4" id="map"></div>
<div class="col-lg-4">
<h1 id="currentLocation">Your Current Location is </h1>
</div>
<h2 class="center-text content-title" id="currentTemp"></h2>
<h3 id="caption">Click temperature to change Units</h3>
<div class="center-text">
<p class="oneLine" id="labels">High: <span id="high"></span></p>
<p class="oneLine" id="labels">Low: <span id="low"></span></p>
</div>
<p class="center-text" id="currentConditions"></p>
<p class="center-text" id="weatherDesc"></p>
<div class="windCompass col-lg-4">
<div class="compass">
<div class="direction">
<p id="windDir"></p>
</div>
<div class="arrow ne"></div>
</div>
</div>
</div>
</body>
</html>
CSS:
#import url(http://fonts.googleapis.com/css?family=Dosis:200,400,500,600);
body {
background: url(http://eskipaper.com/images/pixel-backgrounds-1.jpg);
background-size: auto;
background-repeat: no-repeat;
font-family: Ranga, cursive;
}
h4 {
margin-top: 7px;
}
h1 {
margin-left: -7px;
font-size: 1.05em;
color: white;
}
#header {
background: #2980b9;
color: white;
padding: 0 5px;
display: inline-block;
width: 100%;
margin: 0;
box-shadow: 0 2px 5px #555555;
}
#header .left {
display: inline-block;
width: auto;
float: left;
margin-top: 7px;
margin-left: 7px;
}
#header .navbar {
display: inline-block;
width: 60%;
}
#header .right {
display: inline-block;
width: auto;
text-align: right;
float: right;
margin-top: 2px;
margin-right: 7px;
vertical-align: bottom;
}
.bigger_icon {
margin-top: 10px;
font-size: 2em;
color: white;
}
#map {
height: 200px;
width: 200px;
border-radius: 5%;
margin-top: 20px;
}
#container {
background: rgba(66, 66, 66, 0.6);
display: block;
position: relative;
width: 40%;
margin: 24px auto;
min-height: 300px;
padding: 16px;
border-radius: 4px;
}
#container .center-text {
text-align: center;
}
h2 {
color: white;
font-family: Ranga, cursive;
font-size: 2.5em;
font-weight: bold;
margin-top: -230px;
}
#caption {
font-size: 17px;
text-align: center;
color: pink;
}
#labels {
color: darkGrey;
font-size: 1.5em;
}
.oneLine {
color: darkGrey;
font-size: 1.5em;
text-align: center;
display: inline;
padding: 5px;
}
#high {
text-align: center;
color: orange;
}
#low {
text-align: center;
color: blue;
}
#currentConditions {
text-align: center;
color: black;
}
#weatherDesc {
margin-top: -25px;
color: white;
}
.windCompass {
margin-left: 75%;
margin-top: -20%;
}
.compass {
display: block;
width: 120px;
height: 120px;
border-radius: 100%;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.85);
position: relative;
font-family: 'Dosis';
color: #555;
text-shadow: 1px 1px 1px white;
}
.compass:before {
font-weight: bold;
position: absolute;
text-align: center;
width: 100%;
content: "N";
font-size: 14px;
top: -2px;
}
.compass .direction {
height: 100%;
width: 100%;
display: block;
background: #f2f6f5;
background: -moz-linear-gradient(top, #f2f6f5 30%, #cbd5d6 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f2f6f5), color-stop(100%, #cbd5d6));
background: -webkit-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
background: o-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
border-radius: 100%;
}
.compass .direction p {
text-align: center;
margin: 0;
padding: 0;
position: absolute;
top: 50%;
left: 0;
width: 100%;
height: 100%;
line-height: 80px;
display: block;
margin-top: -35%;
font-size: 28px;
font-weight: bold;
}
.compass .direction p span {
display: block;
line-height: normal;
margin-top: -10%;
font-size: 17px;
text-transform: uppercase;
font-weight: normal;
font-family: Ranga, cursive;
}
.compass .arrow {
width: 100%;
height: 100%;
display: block;
position: absolute;
top: 0;
}
.compass .arrow:after {
content: "";
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 10px solid red;
position: absolute;
top: -6px;
left: 50%;
margin-left: -5px;
z-index: 99;
}
.compass .arrow.nne {
transform: rotate(22.5deg);
}
.compass .arrow.ne {
transform: rotate(45deg);
}
.compass .arrow.ene {
transform: rotate(67.5deg);
}
.compass .arrow.e {
transform: rotate(90deg);
}
.compass .arrow.ese {
transform: rotate(112.5deg);
}
.compass .arrow.se {
transform: rotate(135deg);
}
.compass .arrow.sse {
transform: rotate(157.5deg);
}
.compass .arrow.s {
transform: rotate(180deg);
}
.compass .arrow.ssw {
transform: rotate(202.5deg);
}
.compass .arrow.sw {
transform: rotate(-135deg);
}
.compass .arrow.wsw {
transform: rotate(-114.5deg);
}
.compass .arrow.w {
transform: rotate(-90deg);
}
.compass .arrow.wnw {
transform: rotate(-69.5deg);
}
.compass .arrow.nw {
transform: rotate(-45deg);
}
.compass .arrow.nnw {
transform: rotate(-24.5deg);
}
I ended up finding some Ajax and working with it to do what I expected the button to do. While not a button, it does what is intended. I also worked in changing the high, low, and wind speed to also change with the unit change.
I appreciate the help that everyone offered.
feel free to offer suggestions on the code as well for fixing the css for the compass gradient and making the stupid thing more responsive if you'd like. (The Map is not doing the responsive thing.
Your script probably gets loaded before the DOM is ready.
What you want to do here is one of a few options:
1. Load the JS script tag at the end of the body.
2. Wrap your $('.btn').on(...) function with document.on('ready') event, so this code will only be triggered when the DOM is ready.

Array element undefined while iterating and performing $.ajax opertaion

$(document).ready(function() {
loadStreamInfo();
displayAll();
});
var allStreamInfo = [{ "user": "ogaminglol"}, { "user": "faceittv" }, { "user": "twitch"}, { "user": "hearthstonesea"}, { "user": "stephensonlance"}, {"user": "aegabriel" }];
function loadStreamInfo() {
for (var i = 0; i < 6; i++) {
$.ajax({
url: ("https://wind-bow.gomix.me/twitch-api/streams/" + allStreamInfo[i].user),
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
if (data.stream == null) {
allStreamInfo[i]["status"] = "offline";
} else {
allStreamInfo[i]["status"] = "online";
}
}
});
}
for (var i = 0; i < 6; i++) {
$.ajax({
url: ("https://wind-bow.gomix.me/twitch-api/channels/" + allStreamInfo[i].user),
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
allStreamInfo[i]["logo"] = data.logo;
allStreamInfo[i]["gameName"] = data.game;
allStreamInfo[i]["views"] = data.views;
allStreamInfo[i]["followers"] = data.followers;
allStreamInfo[i]["url"] = data.url;
}
});
}
}
function displayAll() {
for (var i = 0; i < 6; i++) {
var outString = "";
outString += "<div class='item'>";
outString += "<img src='" + allStreamInfo[i].logo + "' alt='logo'>";
outString += "<a href='" + allStreamInfo[i].url + "'><span id='gameName'>" + allStreamInfo[i].gameName + "</span></a>";
outString += "<span id='state'>" + allStreamInfo[i].status + "</span>";
outString += "<span id='views-block'>Views:<span id='view'>" + allStreamInfo[i].views + "</span></span>";
outString += "<span id='follow-block'>Followers:<span id='followed'>" + allStreamInfo[i].followers + "</span></span>";
outString += "</div>";
$("#result").append(outString);
}
}
body {
padding: 40px;
;
}
.toggle-button {
width: 400px;
color: white;
height: 100px;
text-align: center;
margin: 0 auto;
}
.all {
background-color: #6699CC;
width: 30%;
height: 70px;
line-height: 70px;
border-right: 2px solid grey;
display: inline;
float: left;
cursor: pointer;
}
.online {
cursor: pointer;
line-height: 70px;
background-color: cadetblue;
border-right: 2px solid grey;
width: 30%;
height: 70px;
display: inline;
float: left;
}
.offline {
cursor: pointer;
background-color: darkorange;
line-height: 70px;
width: 30%;
height: 70px;
display: inline;
float: left;
}
#result {
margin-top: 30px;
}
.item {
width: 500px;
height: 70px;
margin: 5px auto;
background-color: #666699;
border-left: 4px solid red;
color: whitesmoke;
/*border: 2px solid red;*/
}
a {
text-decoration: none;
}
img {
width: 50px;
height: 50px;
margin-top: 10px;
margin-left: 20px;
margin-right: 21px;
}
span#gameName,
span#views-block,
span#state,
span#follow-block {
position: relative;
bottom: 18px;
}
span#gameName,
span#state,
span#views-block {
margin-right: 21px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div class="toggle-button">
<div class="all" onclick="displayAll()">All</div>
<div class="online" onclick="displayOnline()">Online</div>
<div class="offline" onclick="displayOffline()">Offline</div>
</div>
<div id="result">
</div>
I want dynamically add property in JSON object.I have read post1 and post2. But why I got undefined property? allStreamInfo[i]["prop"] = "value" isn't the way to add property to a object? In the debug window, there is Uncaught TypeError: Cannot set property 'logo' of undefined(…). I have check the API call,it goes well.It seems I don't define the prop,but isn't it the way to dynamically add a prop?
As you are using $.ajax() which is an ansynchornous opertion in loop. When the get the result of ajax operation i will not have value with which it was initiated, So allStreamInfo[i] is undefined.
You can use Closures, to maintain the value of i till the ajax operation is complete
Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created.
for (var i = 0; i < 6; i++) {
(function(j) {
$.ajax({
url: "https://wind-bow.gomix.me/twitch-api/streams/" + allStreamInfo[j].user,
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
allStreamInfo[j]["status"] = data.stream == null ? "offline" : "online";
}
});
})(i);
}
Do read JavaScript closure inside loops – simple practical example
Well, above all, your code doesn't seem right to me. $.ajax returns a promise, which is a future object.
i becomes 6 when these promises are resolved (the loop terminates when i == 6). So in the success callback the expression becomes allStreamInfo[6]["status"].
Since allStreamInfo[6] is undefined in your code, the error is thrown.
you dealing with promises try this code
$(document).ready(function() {
loadStreamInfo();
});
var allStreamInfo = [{
"user": "ogaminglol"
}, {
"user": "faceittv"
}, {
"user": "twitch"
}, {
"user": "hearthstonesea"
}, {
"user": "stephensonlance"
}, {
"user": "aegabriel"
}];
var i = 0;
function loadStreamInfo() {
$.ajax({
url: ("https://wind-bow.gomix.me/twitch-api/channels/" + allStreamInfo[i].user),
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
if (data.stream == null) {
allStreamInfo[i].status = "offline";
} else {
allStreamInfo[i].status = "online";
}
allStreamInfo[i].logo = data.logo;
allStreamInfo[i].gameName = data.game;
allStreamInfo[i].views = data.views;
allStreamInfo[i].followers = data.followers;
allStreamInfo[i].url = data.url;
i++;
if (i < allStreamInfo.length)
loadStreamInfo();
else
displayAll();
}
});
}
function displayAll() {
for (var i = 0; i < 6; i++) {
var outString = "";
outString += "<div class='item'>";
outString += "<img src='" + allStreamInfo[i].logo + "' alt='logo'>";
outString += "<a href='" + allStreamInfo[i].url + "'><span id='gameName'>" + allStreamInfo[i].gameName + "</span></a>";
outString += "<span id='state'>" + allStreamInfo[i].status + "</span>";
outString += "<span id='views-block'>Views:<span id='view'>" + allStreamInfo[i].views + "</span></span>";
outString += "<span id='follow-block'>Followers:<span id='followed'>" + allStreamInfo[i].followers + "</span></span>";
outString += "</div>";
$("#result").append(outString);
}
}
body {
padding: 40px;
;
}
.toggle-button {
width: 400px;
color: white;
height: 100px;
text-align: center;
margin: 0 auto;
}
.all {
background-color: #6699CC;
width: 30%;
height: 70px;
line-height: 70px;
border-right: 2px solid grey;
display: inline;
float: left;
cursor: pointer;
}
.online {
cursor: pointer;
line-height: 70px;
background-color: cadetblue;
border-right: 2px solid grey;
width: 30%;
height: 70px;
display: inline;
float: left;
}
.offline {
cursor: pointer;
background-color: darkorange;
line-height: 70px;
width: 30%;
height: 70px;
display: inline;
float: left;
}
#result {
margin-top: 30px;
}
.item {
width: 500px;
height: 70px;
margin: 5px auto;
background-color: #666699;
border-left: 4px solid red;
color: whitesmoke;
/*border: 2px solid red;*/
}
a {
text-decoration: none;
}
img {
width: 50px;
height: 50px;
margin-top: 10px;
margin-left: 20px;
margin-right: 21px;
}
span#gameName,
span#views-block,
span#state,
span#follow-block {
position: relative;
bottom: 18px;
}
span#gameName,
span#state,
span#views-block {
margin-right: 21px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div class="toggle-button">
<div class="all" onclick="displayAll()">All</div>
<div class="online" onclick="displayOnline()">Online</div>
<div class="offline" onclick="displayOffline()">Offline</div>
</div>
<div id="result">
</div>

Why is append() not attaching itself to a div but it is appending to the heading h2

In the below code, why aren't the values in the array appending to the div element but I am able to append it to the heading? I am storing semicolon separated values in a local storage, then splitting each item and appending it to the div.
<!DOCTYPE html>
<html>
<head>
<title>To do</title>
<style type="text/css">
html {
overflow-y: scroll;
}
body {
padding: 0px;
margin: 0px;
font-family: Verdana, Geneva, sans-serif
}
h2 {
color: black;
text-align: center
}
#omnibox {
margin-left: 400px;
height: 30px;
width: 500px;
font-size: 14px;
padding: 10px;
position: center;
}
#searchWrapper {
margin-left: 500px
}
/*#omnibox,#listWrapper{margin:20px;position:center}*/
.searchable {
color: white;
display: block;
padding: 10px;
font-size: 16px;
background: #4298E8;
width: 300px;
margin-bottom: 10px
}
.searchable:hover {
background-color: #E8C420;
}
.delete {
display: block;
float: right;
height: 20px;
width: 20px;
line-height: 20px;
border-radius: 10px;
background-color: black;
color: white;
text-align: center;
font-size: 1em;
transform: rotate(-45deg);
}
.delete:hover {
background-color: #D8FFF1;
color: red;
cursor: pointer;
}
.comments {
margin-left: -10px;
margin-top: 10px;
width: 310px;
display: inline-block
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
console.log('ready');
$(function() {
// body...
$('#omnibox').focus();
if (window.localStorage) {
localStorage.setItem(1,"how do;you do");
localStorage.setItem(2,"ok;got it");
myList();
function myList() {
var list = "";
console.log('Items in Local Storage = ' + localStorage.length);
document.querySelector('h2').innerHTML = "To do - " + localStorage.length;
for (var i = localStorage.length - 1; i >= 0; i--) {
var itemKey = localStorage.key(i);
var values = new Array();
values = localStorage.getItem(itemKey);
values = values.split(";");
console.log("Array - " + values + " Items - " + values.length);
list += "<div class='searchable' id='" + itemKey + "'><span class='note'>" + itemKey + " " + values[0] + " </span><input type='text' class='comments' placeholder='Comments.'><br/></div>";
var myComments = ""
for (var j = values.length - 1; j >= 0; j--) {
console.log("Element - " + values[j] + " parentNode is " + itemKey);
myComments += '<span>' + ' ' + values[j] + ' ' + '</span>';
};
//Why doesn't this work?
$("#itemKey").append(myComments);
//This works though.
$("h2").append(myComments);
}
$("#listWrapper").html(list);
}
var todo = document.querySelector('#omnibox');
$('#omnibox').keyup(function(e) {
document.querySelector('.errorMessage').innerHTML = "";
if (e.keyCode == 13) {
var todoVal = document.querySelector('#omnibox').value;
if (!todoVal.match(/\S/)) {
console.log('Empty value entered.');
document.querySelector('.errorMessage').innerHTML = "Enter something!";
return false;
} else {
console.log("Some value entered.");
$(this).trigger("enterKey");
var remember = new Array();
myNote = document.querySelector('#omnibox').value;
$('#omnibox').val("");
document.location.reload(true);
return true;
}
}
});
}
});
</script>
</head>
<body>
<h2></h2>
<div id='searchWrapper'>
<div id="listAddWrapper">
<div id="empty"></div>
</div>
<div id="listWrapper">
</div>
</div>
</body>
</html>
You can't use a selector to find an element before you've added it to the DOM. Even if you could, your selector is wrong — it should be "#" + itemKey. But that doesn't matter because it won't work anyway; the element it would match is still just part of that list string you're building.
Looking at your code, I think the best thing to do is to add the comments to the text while you're building it.
list += "<div class='searchable' id='" + itemKey + "'><span class='note'>" + itemKey + " " + values[0] + " </span><input type='text' class='comments' placeholder='Comments.'><br/>";
var myComments = ""
for (var j = values.length - 1; j >= 0; j--) {
console.log("Element - " + values[j] + " parentNode is " + itemKey);
myComments += '<span>' + ' ' + values[j] + ' ' + '</span>';
};
list += myComments + "</div>";

Categories