how are you doing?
I am trying to build a quiz app, and i can't discover how I append the audio of a specific question to the screen.
Basically, the user sees a question, three answers, and an audio.
How would I point each audio to the current exercise?
It is recognizing the first audio, but when I jump to the second question, it shows two audio players aligned and then they disappear.
The HTML file:
<div id="navContent">
<div id="game1"></div>
<div id="game2"></div>
<div id="audioContainer"></div>
<div id="audioContainer2"></div>
</div>
The JS
$(document).ready(function () {
var questionNumber=0;
var audioNumber=0;
var questionBank=new Array();
var stage="#game1";
var stage2=new Object;
var evento = "#audioContainer";
var evento2 = new Object;
var questionLock=false;
var numberOfQuestions;
var score=0;
$.getJSON('../../core/part1.json', function(data){
numberOfQuestions = data.primeiro.length;
for(i = 0; i < numberOfQuestions; i++){
questionBank[i] = [];
questionBank[i].push(data.primeiro[i].question);
questionBank[i].push(data.primeiro[i].option1);
questionBank[i].push(data.primeiro[i].option2);
questionBank[i].push(data.primeiro[i].option3);
questionBank[i].push(data.primeiro[i].audio);
}
displayQuestion();
});
function displayQuestion(){
var q1;
var q2;
var q3;
var audioFile = questionBank[questionNumber][4];
var rnd=Math.random()*3;
rnd=Math.ceil(rnd);
var wordsShow = $('<li class= "center_txt"><div id="1" class="word-pt bluedark_txt">'+q5+'</div><div id="2" class="bluish_txt word-EN">'+q4+'</div></li>')
var audioShow = $('<audio controls id="audioPlayer"><source src='+audioFile+' type="audio/mp3"></audio>');
if(rnd==1){q1=questionBank[questionNumber][1];q2=questionBank[questionNumber][2];q3=questionBank[questionNumber][3];}
if(rnd==2){q2=questionBank[questionNumber][1];q3=questionBank[questionNumber][2];q1=questionBank[questionNumber][3];}
if(rnd==3){q3=questionBank[questionNumber][1];q1=questionBank[questionNumber][2];q2=questionBank[questionNumber][3];}
$(stage).append('<div class="questionText">'+questionBank[questionNumber][0]+'</div><div id="1" class="option">'+q1+'</div><div id="2" class="option">'+q2+'</div><div id="3" class="option">'+q3+'</div>');
//here is where I try to append the audio, not working
$("#audioContainer").append(audioShow);
$('.option').click(function(){
if(questionLock==false){questionLock=true;
//correct answer
if(this.id==rnd){
// $("#feedbackBox").append('<div class="feedback1">CORRECT</div>');
score++;
}
//wrong answer
if(this.id!=rnd){
// $("#feedbackBox").append('<div class="feedback2">WRONG</div>');
}
setTimeout(function(){changeQuestion()},1000);
}})
}//display question
function changeQuestion(){
questionNumber++;
wordNumber++;
audioNumber++;
if(stage=="#game1"){stage2="#game1";stage="#game2";}
else{stage2="#game2";stage="#game1";}
if(evento=="#audioContainer"){evento2="#audioContainer";evento="#audioContainer2";}
else{evento2="#audioContainer2";evento="#audioContainer";}
if(questionNumber<numberOfQuestions){displayQuestion();}else{displayFinalSlide();}
$(stage2).animate({"right": "+=800px"},"slow", function() {$(stage2).css('right','-800px');$(stage2).empty();});
$(stage).animate({"right": "+=800px"},"slow", function() {questionLock=false;});
$(evento2).animate({"right": "+=800px"},"slow", function() {
$(evento2).css('right','-800px');
$(evento2).empty();});
$(evento).animate({"right": "+=800px"},"slow", function() {questionLock=false;});
}//change question
THANK YOU!
Related
My goal is to load data from the appropriate file into div sections when I select any option.
I need to load <div> in one file from another (inside iframe). I'm stuck on how to get value and store it in variable. Everything works fine if I assign to variables (template_1, template_2, template_3) any static data but I want to load it from another files (template_one.html, template_2.html and so on).
template_1 has load() method but I know that this is wrong. Instead I want a path to appropriate file div. Same with other variables
I found a similar solution here with function load but I'm not sure if this will work and how add this to my function.
Array objects are random so please don't worry about it
jQuery(document).ready(function($) {
var template_1 = $('#section_one').load('template_one.html', '.section_one')
var template_2 = "<div><h1>template2</h1></div>"
var template_3 = "<div><h1>template3</h1></div>"
var templates_array = [
[template_1, template_1, template_1, template_1, template_1],
[template_2, template_2, template_2, template_2, template_2],
[template_3, template_3, template_3, template_3, template_3],
]
function load(url, element) {
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
document.getElementById('id_template').onchange = function(event) {
let get_val = event.target.selectedOptions[0].getAttribute("value");
if (get_val) {
for (let i = 0; i < templates_array.length; i++) {
var iframe = document.getElementsByTagName('iframe')[i].contentWindow.document;
var iframe_content = iframe.querySelector('body');
iframe_content.innerHTML = templates_array[get_val - 1][i];
};
} else {
for (let i = 0; i < templates_array.length; i++) {
var iframe = document.getElementsByTagName('iframe')[i].contentWindow.document;
var iframe_content = iframe.querySelector('body');
iframe_content.innerHTML = '';
};
};
};
});
project tree
Jquery Code
$(document).ready(function(){
$(document).on('click', '#button_1', function() {
$('#div_1').load('one.html')
});
$(document).on('click', '#button_2', function() {
$('#div_2').load('two.html')
})
});
HTML Code
Button_1
<BR>
<BR>
Button_2
<BR>
<BR>
<div id="div_1"></div>
<div id="div_2"></div>
I hope this one help you.
In the iframe:
<textarea id="ta"></textarea>
<script>
$(document).ready(function(){
$(document).on('change', '#ta', function() {
parent.textAreaChanged(this.value);
});
});
</script>
In the parent:
<div id="display"></div>
<script>
function textAreaChanged(value){
$('#display').text(value);
}
</script>
I'm trying to set a function in my application which allows the user to click on a button and then click the submit button which displays an image, but I want the buttons to hold more than one image and randomly select an image from the array.
How can I do this?
<div id='prefPage'>
<header id='header2pref'>
<div id='title2pref'>PREFERENCES</div>
</header>
<div id='body'>
<div id='leftAlign'>
<div id="foodpicloc">
</div>
</div><button id='myBtn2'>SET PREFRENCES</button>
<div id='rightAlignPref'>
<div id=fixed>
<div>
<button id="button1">BURGER</button>
<button id="button2">HOTDOG</button>
</div>
</div>
</div>
</div>
</div>
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var preference = document.getElementById("preference");
var foodpic = document.getElementById("foodpiclocation");
var foodpic;
button1.addEventListener('click', function() {
foodpicurl = 'burger.svg';
});
button2.addEventListener('click', function() {
foodpicurl = 'hotdog.svg';
});
preference.addEventListener('click', function() {
var foodpic = document.createElement('img');
foodpic.src = foodpicurl;
foodpiclocation.innerHTML = '';
foodpiclocation.appendChild(foodpic);
});
Clean solution using vanilla Javascript. NOTE: I suggest you add this to your HTML code <div id="foodpicloc"><img id="foodpic"></div> in your HTML first. Changing the image's src is quicker and cleaner than appending a new image element everytime the image changes.
Define
function mapClickToImage(imageSelector, updateBtnSelector, btnSectorToImageSrcMapping) {
var currentImageSrc = null;
var imageElement = document.querySelector(imageSelector);
for (var btnSelector in btnSectorToImageSrcMapping) {
var buttonElement = document.querySelector(btnSelector);
buttonElement.addEventListener('click', function() {
currentImageSrc = btnSectorToImageSrcMapping[btnSelector];
});
var updateButtonElement = document.querySelector(updateBtnSelector);
updateButtonElement.addEventListener('click', function() {
if (currentImageSrc) {
imageElement.src = currentImageSrc;
}
});
}
Usage
mapClickToImage('#foodpic', '#preference', {
'#button1': 'burger.svg',
'#button2': 'hotdog.svg'
});
So I'm in a bootcamp, bout to begin the 7th week. We have an API assignment, and I chose to use the Giphy API. Okay, I've made the ajax call, have the json object, am displaying gifs with a button click. Once the gifs load, you should be able to make image animate, then upon next click, the image becomes still again. the process should be able to repeat itself ad nauseam. I have it set up the way that makes sense; however, I cant seem to get the urls to change upon click the way it's currently written. I tried .splice url, and using concat to complete updated url; however, I cant seem to figure out how to get the image to revert back to still state upon next click... been working on this for sooooo many hours, will someone please lend me a fresh set of eyes?
here's my js and jquery
// $("#loadTimer, .buttonGallery, #btnGeneratingbtn").hide();
var topics = ["Brandon", "Biggie Smalls", "Dr. Seuss", "Paul McCartney", "John Lennon", "Will Ferrell", "Jimmy Fallon", "Chris Farley", "Dane Cook", "Eminem", "Nas", "Jay-Z", "Rakim", "William Shakespeare","Jim Morrison", "James Maynard", "Serj Tankian"];
var gifcount = 0;
var gifLocation;
var clickCount = 0;
var buttonFactory = function() {
$(".buttonGallery").empty();
for (i = 0; i < topics.length; i++) {
var imAbutton = $("<button>");
imAbutton.addClass("yup");
imAbutton.attr("data-name", topics[i]);
imAbutton.text(topics[i]);
$(".buttonGallery").append(imAbutton);
}};
buttonFactory();
$("#anotherButton").on("click", function(event) {
event.preventDefault();
// This line grabs the input from the textbox
var onemorebutton = $("#user-input").val().trim();
// Adding movie from the textbox to our array
topics.push(onemorebutton);
// Calling renderButtons which handles the processing of our movie array
buttonFactory();
});
$(".yup").on("click", function(){
$("#gif-Gallery").empty();
var searchTermUpdate;
var searchTerm = $(this).attr("data-name");
// removing white space between two-word strings, replacing with a "+" \\
searchTermUpdate = searchTerm.replace(/ +/g, "+");
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + searchTermUpdate + "&api_key=dc6zaTOxFJmzC&limit=10";
$.ajax({
url: queryURL,
method: 'GET'
}).done(function(response) {
console.log(response);
var results = response.data;
for (var i = 0; i < results.length; i++){
gifcount = gifLocation;
var gifDIV = $("<div class='unit' data-state='still'>");
var pRating = $("<p>").text("Rating: " + results[i].rating);
var gifImg = $("<img id='gifimg' class='col-md-4'>");
gifImg.attr("src", results[i].images.fixed_height_still.url);
gifImg.attr({'data-animate' : results[i].images.fixed_height.url});
gifImg.attr({'data-state' : "still"});
gifImg.attr({'data-still' : results[i].images.fixed_height_still.url});
gifDIV.append(pRating);
gifDIV.append(gifImg);
gifDIV.append(gifLocation);
gifcount++;
// appending gif div to DOM \\
if (results[i].rating !== "g" || "pg" || "pg-13" || "y"){
$("#gif-Gallery").append(gifDIV);
}}
$(".unit").on("click", function(){
var state = $(this).attr('data-state');
if (state === "still") {
$(this).attr("src", $(this).attr("data-animate"));
$(this).attr("data-state", "animate");
} else {
$(this).attr("src", $(this).attr("data-still"));
$(this).attr("data-state", "still");
}
// var imgPath = this.children[1].src;
clickCount++;
var a;
var b;
var c;
var d;
var f;
// if (clickCount % 2 === 0 ){
// for (i=0; i < imgPath.length; i++){
// // locating index of underscore, storing that value in var a\\
// var a = imgPath.indexOf("_");
// // removing all characters to the right of the underscore \\
// var b = imgPath.slice(0, a);
// f = b;
// // setting var c to a string value of .gif \\
// var c = ".gif";
// // combining var b and var c to complete updated image path \\
// var d = b.concat(c);
// }
// setting image url to animated url \\
// $(gifImg).attr("src", d);
// this.children[1].src = d;
});
});}); //
and here is the html if needed :
<body>
<div class="jumbotron">
<div class="container">
<div class="myHeader">
<h1>WordSmiths</h1>
<span class="text-muted" id="jtronText">
<div id="sometimeGone">Sometimes</div><div id="loadTimer">someone opens their mouth and you can't help but to be dazzled with the magic.</div>
</span>
<p class="text-success" id="instructionsOne">
Click a button, see what happens!
</p>
<p class="text-success" id="instructionsTwo">
Now you can create your own buttons!!!
</p>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="buttonGallery"></div>
<h4>Create buttons, find Gifs!: </h4>
<form id="btnGeneratingForm">
<label for="input">Anything: </label>
<input type="text" id="user-input">
<br>
<input type="submit" id="anotherButton" value="More buttons">
</form>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div id="gif-Gallery"></div>
</div>
</div>
again, thanks in advance!
Robert
I am actually doing the same project! I did it a pretty a similar way. I think the issue may be that you're appending the animated src to the image holder div instead of the child image itself. This line:
$(this).attr("src", $(this).attr("data-animate"));
Is what is giving you trouble I think.
Best of luck with the project, I hope that helps.
So, as I think, my title is not pretty understandable.
I have this jquery code:
$("img.slideimg").click(function(){
var id = $(this).attr('id');
$("img.previewimg." + id).css({"display": "block"});
$("div.imgpreview").css({"display": "flex"});
function slideDo(n) {
var i;
var aux = id - 1 + n;
var slidesp = document.getElementsByClassName("previewimg");
if (aux > slidesp.length) {aux = 1}
if (aux < 1) {aux = slidesp.length}
for (i = 0; i < slides.length; i++) {
slidesp[i].style.display = "none";
}
slidesp[aux-1].style.display = "block";
}
});
The problem is that the browser console output is this:
Uncaught ReferenceError: slideDo is not defined
at HTMLAnchorElement.onclick (index.html:85)
My problem is that I want to create a function that uses an variable from the $("img.slideimg").click event. This variable is id = $(this).attr('id'); so I thinked of creating the function inside it. Apparently it doesn't work like this so I need a little help.
Sorry if you don't understand me. I'm pretty new to this kind of coding :(
HTML where i use slideDo
<div class="middle">
<a class="prev" onclick="slideDo(-1)"> ❮ </a>
<div class="imglink">
<img src="img/dailyui/008.png" class="previewimg 1">
<img src="img/dailyui/007.jpg" class="previewimg 2">
<img src="img/dailyui/006.jpg" class="previewimg 3">
<img src="img/dailyui/003.jpg" class="previewimg 4">
</div>
<a class="next" onclick="slideDo(1)"> ❯ </a>
</div>
So what I want to do:
I have a slideshow and when I click on one of the pictures, a modal with the pictures will show up. Then here I have again another buttons for next / previous picture but they doesn't seems to work. Here is the demo website of my code: beta.eduardstefan.com
The scope of the name slideDo is just the click function, but it appears you're trying to call it from the global scope (the onclick attribute of an anchor). You need to assign the function to a global variable.
var slideDo = function() {}; // initially does nothing
$(document).ready(function() {
$("img.slideimg").click(function(){
var id = $(this).attr('id');
$("img.previewimg." + id).css({"display": "block"});
$("div.imgpreview").css({"display": "flex"});
slideDo = function(n) {
var i;
var aux = id - 1 + n;
var slidesp = document.getElementsByClassName("previewimg");
if (aux > slidesp.length) {aux = 1}
if (aux < 1) {aux = slidesp.length}
for (i = 0; i < slides.length; i++) {
slidesp[i].style.display = "none";
}
slidesp[aux-1].style.display = "block";
}
});
});
I'm developing a bird quiz in html5 using javascript and json. The user has to identify the bird by clicking the right picture.To reward the user, a youtube video of the given bird is automatically played. My problem here is that, the right video is not being played so for example even though the right answer for question one is a parrot, a video of a Quetzal is played. I want the right video to be played by the right question.
This is my json content.
{
"quizlist":[
{
"question":"Which picture shows a Parrot?",
"option1":"Parrot.png",
"option2":"Cardinal.png",
"option3":"Toucan.png",
"option4":"Owl.png",
"videoURL" : "https://www.youtube.com/watch?v=RfXxh0Eff_w"
},
{
"question":"Which picture shows a Peacock?",
"option1":"Peacock.png",
"option2":"Flamingo.png",
"option3":"Quetzal.png",
"option4":"Penguin.png",
"videoURL" : "https://www.youtube.com/watch?v=jz-tjJhFH1k"
},
{
"question":"Which picture shows a Cockatoo?",
"option1":"Cockatoo.png",
"option2":"Turkey.png",
"option3":"Duck.png",
"option4":"Penguin.png",
"videoURL" : "https://www.youtube.com/watch?v=TTb77syQjMg"
},
{
"question":"Which picture shows a Toucan?",
"option1":"Toucan.png",
"option2":"Falcon.png",
"option3":"Hummingbird.png",
"option4":"Penguin.png",
"videoURL" : "https://www.youtube.com/watch?v=WAYntcQTm5A"
},
{
"question":"Which picture shows a Quetzal?",
"option1":"Quetzal.png",
"option2":"Cardinal.png",
"option3":"Flamingo.png",
"option4":"Owl.png",
"videoURL" : "https://www.youtube.com/watch?v=IhSCnjr3-MY"
}
]
}
And this is my javascript code
$(document).ready(function () {
var questionNumber=0;
var questionBank=new Array();
var stage="#game1";
var stage2=new Object;
var questionLock=false;
var numberOfQuestions;
var score=0;
var vidURL;
$.getJSON('js/activity.json', function(data) {
console.log(data);
for(i=0;i<data.quizlist.length;i++){
questionBank[i] = new Array;
questionBank[i][0] = data.quizlist[i].question;
questionBank[i][1] = data.quizlist[i].option1;
questionBank[i][2] = data.quizlist[i].option2;
questionBank[i][3] = data.quizlist[i].option3;
questionBank[i][4] = data.quizlist[i].option4;
//questionBank[i][5] = data.quizlist[i].videoURL;
vidURL = data.quizlist[i].videoURL;
console.log(vidURL);
}
numberOfQuestions=questionBank.length;
displayQuestion();
console.log('Display Questions Ran');
})//gtjson
function displayQuestion(){
var rnd = Math.random()*4;
rnd = Math.ceil(rnd);
var q1;
var q2;
var q3;
var q4;
if(rnd==1){q1=questionBank[questionNumber][1]; q2=questionBank[questionNumber][2]; q3=questionBank[questionNumber][3]; q4=questionBank[questionNumber][4];}
if(rnd==2){q2=questionBank[questionNumber][1]; q3=questionBank[questionNumber][2]; q4=questionBank[questionNumber][3]; q1=questionBank[questionNumber][4];}
if(rnd==3){q3=questionBank[questionNumber][1]; q4=questionBank[questionNumber][2]; q1=questionBank[questionNumber][3]; q2=questionBank[questionNumber][4];}
if(rnd==4){q4=questionBank[questionNumber][1]; q1=questionBank[questionNumber][2]; q2=questionBank[questionNumber][3]; q3=questionBank[questionNumber][4];}
$(stage).append(
'<ul class="collection"> <li class="collection-item active black">' + questionBank[questionNumber][0] + '</li></ul>' +
'<hr style="margin-bottom: 20px">' +
'<div id="1" class="col s6 pix"><img src="img/'+q1+'" width="30%"></div>' +
'<div id="2" class="col s6 pix"><img src="img/'+q2+'" width="30%"></div>' +
'<div id="3" class="col s6 pix"><img src="img/'+q3+'" width="30%"></div>' +
'<div id="4" class="col s6 pix"><img src="img/'+q4+'" width="30%"></div>'
);
$('.pix').click(function(){
if(questionLock==false){questionLock=true;
//correct answer
if(this.id==rnd){
var $toastContent = $('<span>Correct</span>');
var myMedia = new Media("http://soundbible.com/grab.php?id=1974&type=mp3")
myMedia.play()
Materialize.toast($toastContent, 6000);
window.open(vidURL, '_system');
score++;
}
//wrong answer
if(this.id!=rnd){
var $toastContent = $('<div class="center-align"><span>Wrong</span></div>');
var myMedia = new Media("http://soundbible.com/grab.php?id=1495&type=mp3")
myMedia.play()
Materialize.toast($toastContent, 2000);
}
setTimeout(function(){changeQuestion()},3000);
}})
}//display question
function changeQuestion(){
questionNumber++;
if(stage=="#game1"){stage2="#game1";stage="#game2";}
else{stage2="#game2";stage="#game1";}
if(questionNumber<numberOfQuestions){displayQuestion();}else{displayFinalSlide();}
Materialize.fadeInImage(stage2);
$(stage2).empty();
Materialize.fadeInImage(stage);
$(stage).animate({"right": "+=800px"},"slow", function() {questionLock=false;});
}//change question
function displayFinalSlide(){
$(stage).append('<div class="questionText">You have finished the quiz!<br><br>Total questions: '+numberOfQuestions+'<br>Correct answers: '+score+'</div>');
}//display final slide
});
You open the video by window.open(vidURL, '_system'); but the global vidURL variable is initialized in the for loop of getJSON. So it always contains the last value of the data.quizlist[i].videoURL - which will always be the URL of the Quetzal video.
Here's one way on how to make this work:
[...]
var vidURL;
var videoBank = [];
$.getJSON(...) {
[...]
for(i=0;i<data.quizlist.length;i++){
[...]
videoBank[i] = data.quizlist[i].videoURL;
}
[...]
}
function displayQuestion(){
[...]
var vidURL = videoBank[questionNumber];
[...]
}