Reputation: 8963
I'm making a small text-based game and I'm trying to incorporate some background music through Youtube-embeds. Probably not the best solution, but for my goal it works :)
I have a Javascript database built up with multiple data collections, built up like this:
{
"question":"blabla.",
"answers":[
{"title":"Left","response":3},
{"title":"Right","response":2}
],
"youembed":"<iframe id='youtube' width='100' height='100' src='http://www.youtube.com/embed/VIIOVtWGSj8?autoplay=1' frameborder='0' allowfullscreen></iframe>"
},
I place the content from the database in my HTML with the following piece:
document.getElementById("question").innerHTML = db[currentLocation].question;
However, I only want the youembed
to actually be placed in the HTML, if the length of db[currentLocation].youembed
is over 0.
So I wrote the following:
if (youembed > 0) {
document.getElementById("youembed").innerHTML = db[currentLocation].youembed;
}
Whenever I use the document[..].youembed
outside of the if-statement, it works without a problem, however, I want it to work IN the if-statement, so it doesn't replace the current playing song, until db[currentLocation].youembed
is > 0
What am I doing wrong? I have an alert(youembed)
placed in the code, so I can see the length and it does show me that one youembed is 0, the other on page 2 is 145, but it doesn't run the if
-statement in that case.
Here's the complete Javascript code:
var currentLocation = 0;
window.printCurrentLocation = function(){
document.getElementById("question").innerHTML = db[currentLocation].question;
var youembed = db[currentLocation].youembed;
alert(youembed.length);
if (youembed > 0) {
document.getElementById("youembed").innerHTML = db[currentLocation].youembed;
}
else {
}
var answers = "";
for(var i=0,l=db[currentLocation].answers.length;i<l;i++){
answers += "<p><button onclick='setLocation("+db[currentLocation].answers[i].response+")'>"+db[currentLocation].answers[i].title+"</button></p>";
}
document.getElementById("answers").innerHTML = answers;
}
window.setLocation = function(num) {
currentLocation = num;
window.printCurrentLocation();
}
window.printCurrentLocation();
Upvotes: 0
Views: 173
Reputation: 6333
You are not comparing the length, this right here
if (youembed > 0) { ... }
should be
if (youembed.length > 0) { ... }
Example code: http://jsfiddle.net/f7cedqrf/
Upvotes: 1