Change div background image with JavaScript - javascript

I have a button that when clicked should change its value, a gif image, and a div background at the same time. I have the value change and gif change working well.
However I'm having trouble changing the div background image. I thought that the code I have below would work, but the carousel__cell change just doesn't change.
I also copied a line of HTML that it would apply to so that you can see the gif is in a completely different div than the carousel__cell. I'm not sure if that is the reason, but I don't know what else to try.
function updateButton(btn, bk, i) {
var front = "../../../.img/sprites/gif-sprites/gen1/";
var temp = "unknown";
var end = document.getElementsByClassName("gif")[i].src;
var length = 9;
var endT = end.substring(end.length - length);
if (btn.value === 'U') {
btn.value = 'S';
temp = "seen";
document.getElementsByClassName("carousel__cell").src = "../../../.img/pokedex/seen.png";
document.getElementsByClassName("gif")[i].src = front + temp + endT;
} else {
if (btn.value === 'S') {
btn.value = 'C';
temp = "caught";
document.getElementsByClassName("carousel__cell").src = "../../../.img/pokedex/caught.png";
document.getElementsByClassName("gif")[i].src = front + temp + endT;
} else {
if (btn.value === 'C') {
btn.value = 'U';
temp = "unknown";
document.getElementsByClassName("carousel__cell").src = "../../../.img/pokedex/unknown.png";
document.getElementsByClassName("gif")[i].src = front + temp + endT;
}
}
}
}
const back = document.querySelectorAll('carousel__cell');
const inputs = document.querySelectorAll('input');
for (let i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('click', () => updateButton(inputs[i], back[i], i));
}
<div class="slideshow-container">
<div class="mySlides"><img class="gif" src="../../../.img/sprites/gif-sprites/gen1/unknown/0001.gif" alt="" onClick="location.href='../../dexentries/0001.html'"></div>
</div>
<div class="carousel">
<div class="carousel__scene">
<ol class="carousel__list">
<li class="carousel__cell"><input type="button" value="U"><img class="sprite" src="../../../.img/sprites/game-sprites/gen1/0001.png" alt="" /><span class="pkmname">Bulbasaur</span></li>
</ol>
</div>
</div>

I was actually able to figure this out after looking a little more. I was able to use jquery to add and remove classes.
$('input').on({
click: function() {
if ($('li.selected input:button').val() == 'S') {
$('li.selected').addClass('seen').removeClass('caught').removeClass('unknown')
}
if ($('li.selected input:button').val() == 'C') {
$('li.selected').addClass('caught').removeClass('unknown').removeClass('seen')
}
if ($('li.selected input:button').val() == 'U') {
$('li.selected').addClass('unknown').removeClass('seen').removeClass('caught')
}
}
})

Related

how to send 2 parameters from Javascript to controller

This might be a silly question...
In my website I have 3 types of images: TYPE A, TYPE B and TYPE C.
All images, no matter what type they are, if you click on them, it opens a lightbox as modal carrousel, and each image you could download them individually.
What's the problem? The problem is that each type of image are in different tables in a db, so I have 3 differents paths to search:
TYPE A images are in TABLE A
TYPE B images are in TABLE B
TYPE C images are in TABLE C
So, how can I send from Javascript, from the button Download Image, the type of image I'm actually showing? What I can do is to send the src of the image, but not the TYPE
The TYPE of each image is assigned by a name in each image:
<img alt="Image" class="imgPedido" id="#cont" src="#pd.getImagenes()" data-img-mostrar="#cont" name="A"/>
<img alt="Image" class="imgPedido" id="#cont" src="#pd.getImagenes()" data-img-mostrar="#cont" name="B"/>
<img alt="Image" class="imgPedido" id="#cont" src="#pd.getImagenes()" data-img-mostrar="#cont" name="C"/>
What I tried is to have a function where it receives the src (imageSelec) of the image selected and ask if A, B or C is null or empty:
public void DownloadImagen(string imageSelec, string A, string B, string C)
{
try
{
Logger.Debug("IMAGE SELECTED ---> " + imagenSelec);
Logger.Debug("IMAGE A ---> " + A);
Logger.Debug("IMAGE B ---> " + B);
Logger.Debug("IMAGE C ---> " + C);
if (A!= null || A!= "")
{
DownloadImageA(imagenSelec);
}
else if (B!= null || B!= "")
{
DownloadImageB(imagenSelec);
}
else if (C != null || C != "")
{
DownloadImageC(imagenSelec);
}
}
catch (Exception ex)
{
Logger.Error(ex.Message + " || Funcion: DescargarImagen()");
ViewData["ERROR"] = ex.Message;
throw new Exception(ex.Message);
}
}
I used Loggers to see what the function recieves and this is the result:
In this case it should be image A:
Here is my lightbox:
const galleryItem = document.getElementsByClassName("gallery-item");
const lightBoxContainer = document.createElement("div");
const lightBoxContent = document.createElement("div");
const lightBoxImg = document.createElement("img");
const lightBoxPrev = document.createElement("div");
const lightBoxNext = document.createElement("div");
const btnDownload = document.createElement("button");
const closeBtn = document.createElement("button");
const form = document.createElement("form");
const divBtnX = document.createElement("div")
const body = document.getElementById("bodyId")
const imgBtnDownload = document.createElement("img");
imgBtnDownload.setAttribute("src", "/Img/descargas.png");
imgBtnDownload.setAttribute("id", "imgBtnDownload")
imgBtnDownload.setAttribute("class", "mx-1")
form.setAttribute("action", "/Home/DownloadImagen");
form.setAttribute("class", "mb-3 position-relative")
lightBoxContainer.classList.add("lightbox");
lightBoxContent.classList.add("lightbox-content");
lightBoxPrev.classList.add("fa", "fa-angle-left", "lightbox-prev");
lightBoxNext.classList.add("fa", "fa-angle-right", "lightbox-next");
divBtnX.classList.add("d-flex", "justify-content-end")
closeBtn.classList.add("btn-close", "btn-close-white", "mt-4", "mx-4");
closeBtn.setAttribute("type", "button");
closeBtn.setAttribute("onclick", "closeLightBox()")
closeBtn.setAttribute("data-bs-dismiss", "gallery-item")
closeBtn.setAttribute("aria-label", "Close")
closeBtn.setAttribute("id", "btnCerrar")
btnDownload.classList.add("buttons", "btnDescargarImgs", "mt-3");
btnDownload.innerHTML = "Descargar Imágen";
btnDownload.setAttribute("type", "submit")
btnDownload.setAttribute("id", "btnDescargarImagen")
btnDownload.setAttribute("name", "imagenSelec");
btnDownload.appendChild(imgBtnDownload)
divBtnX.appendChild(closeBtn)
lightBoxContainer.appendChild(divBtnX);
lightBoxContent.appendChild(lightBoxPrev);
lightBoxContainer.appendChild(lightBoxContent);
lightBoxContent.appendChild(lightBoxImg);
lightBoxContent.appendChild(lightBoxNext);
form.appendChild(btnDownload);
lightBoxContent.appendChild(form);
document.body.appendChild(lightBoxContainer);
let index = 1;
function showLightBox(n) {
if (n > galleryItem.length) {
index = 1;
} else if (n < 1) {
index = galleryItem.length;
}
let imageLocation = galleryItem[index - 1].children[0].getAttribute("src");
lightBoxImg.setAttribute("src", imageLocation);
btnDownload.setAttribute("src", imageLocation);
btnDownload.setAttribute("value", imageLocation)
body.style.overflow = "hidden";
}
function currentImage() {
lightBoxContainer.style.display = "block";
lightBoxContainer.style.opacity = "1";
let imageIndex = parseInt(this.getAttribute("data-index"));
showLightBox(index = imageIndex);
}
for (let i = 0; i < galleryItem.length; i++) {
galleryItem[i].addEventListener("click", currentImage);
}
function slideImage(n) {
showLightBox(index += n);
}
function prevImage() {
slideImage(-1);
}
function nextImage() {
slideImage(1);
}
lightBoxPrev.addEventListener("click", prevImage);
lightBoxNext.addEventListener("click", nextImage);
function closeLightBox() {
body.style.overflow = "auto";
lightBoxContainer.style.display = "none";
}
The functions DownloadImageA, DownloadImageB and DownloadImageC are already done, I used them individually and works fine, so I don't have to change them
So, how can I send the name of the images to the function DownloadImagen?
I hope you understood this..

how to onclick for pairs of images randomly in javascript?

/* egg & broke egg pair1 lite & broke lite pair2 pot & frys pair3 */
I would like to know how to make the images pair up or team up. So when you click the egg image it disappears and the broken egg appears. Then this image should also disappear then and one of the other two teams appear randomly lite click lite broke lite appears and disappears randomly and click pot it turns into frys then frys disappears and turns into a random team.
</head>
<body onLoad="setRandomImage()">
<img id="egg.png" src= "http//"onClick="setRandomImage();"/>
<img id="brokeEgg.png" src= "https://" style="display:none"/>
<img id="lite.png" src= "http://" style="display:none"/>
<img id="brokeLite.png" src= "http://" style="display:none"/>
<img id="pot.jpg" src= "https://style="display:none"/>
<img id="frys.jpg" src= "http://style="display:none"/>
<script type="text/javascript">
var myShapes= ["egg.png","brokeEgg.png","lite.png","brokeLite.png","pot.jpg","frys.jpg" ];
function setRandomImage() {
var imgElem = document.getElementById("egg.png")
imgElem.setAttribute('src',myShapes[Math.floor(Math.random()*6)]);
};
</script>
Here's a very simplified one by making use of HTML data-* attributes, but take in consideration:
The value data-image-seq attribute must be img followed by a number.
These numbers must be sequenced
Updated
jsFiddle
var imgs = document.querySelectorAll('.imgs-wrapper img'),
currentIMG = 1;
// attach click events on odd images only, egg, lite, pot, hi1, hello1
for (var i = 0; i < imgs.length; i += 2) {
addEvent(imgs[i], 'click');
}
function addEvent(element, event) {
element.addEventListener(event, function() {
var imgSeq = element.getAttribute('data-image-seq'),
nextImgSeq, nextImg, shownIMG;
imgSeq = parseInt(imgSeq.replace('img', ''), 10);
nextImgSeq = (imgSeq < imgs.length) ? (imgSeq + 1) : 1;
nextImg = 'img[data-image-seq=img' + nextImgSeq + ']';
element.style.display = 'none';
shownIMG = document.querySelector(nextImg);
shownIMG.style.display = 'block';
setTimeout(function() {
shownIMG.style.display = 'none';
showRandomImg();
}, 1000);
});
}
function showRandomImg() {
var randomIMG = returnRandomOddNum();
randomIMG = (randomIMG !== currentIMG) ? randomIMG : returnRandomOddNum();
currentIMG = randomIMG;
randomIMG = 'img[data-image-seq=img' + randomIMG + ']';
document.querySelector(randomIMG).style.display = 'block';
}
function returnRandomOddNum() {
var randomNum = Math.floor(Math.random() * imgs.length);
randomNum = (randomNum % 2 != 0) ? randomNum : randomNum + 1;
return randomNum;
}
.imgs-wrapper { position: relative; }
.imgs-wrapper { cursor: pointer; }
.hide-me { display: none; }
<div class="imgs-wrapper">
<img data-image-seq="img1" src="//dummyimage.com/150x50?text=egg">
<img data-image-seq="img2" src="//dummyimage.com/150x50?text=broke egg" class="hide-me">
<img data-image-seq="img3" src="//dummyimage.com/150x50?text=lite" class="hide-me">
<img data-image-seq="img4" src="//dummyimage.com/150x50?text=broke light" class="hide-me">
<img data-image-seq="img5" src="//dummyimage.com/150x50?text=pot" class="hide-me">
<img data-image-seq="img6" src="//dummyimage.com/150x50?text=frys" class="hide-me">
<img data-image-seq="img7" src="//dummyimage.com/150x50?text=Hi1" class="hide-me">
<img data-image-seq="img8" src="//dummyimage.com/150x50?text=Hi2" class="hide-me">
<img data-image-seq="img9" src="//dummyimage.com/150x50?text=Hello1" class="hide-me">
<img data-image-seq="img10" src="//dummyimage.com/150x50?text=Hello2" class="hide-me">
</div>
Use this function to toggle the visibility of two elements on click:
function bindToggleVisibilityOnClick(firstElemId, secondElemId) {
var firstElement = document.getElementById(firstElemId);
var secondElement = document.getElementById(secondElemId);
firstElement.onclick = function() { toggleVisibility(firstElement, secondElement); };
secondElement.onclick = function() { toggleVisibility(secondElement, firstElement); };
}
function toggleVisibility(checkElem, otherElem){
// If target is invisible
if (checkElem.style.display == "none"
//|| checkElem.style.visibility == "hidden"
) {
checkElem.style.display = "block";
// checkElem.style.visibility = "visible";
otherElem.style.display = "none"
// otherElem.style.visibility = "hidden";
}
else {
otherElem.style.display = "block";
checkElem.style.display = "none"
// checkElem.style.visibility = "hidden";
}
};
bindToggleVisibilityOnClick("egg", "brokenEgg");
#egg { display: block; }
#brokenEgg { display: none; }
<div id="egg"><p>hi</p></div>
<div id="brokenEgg"><p>hi2</p></div>
Use as such:
// Should now toggle visibility on click
bindToggleVisibilityOnClick("egg", "brokenEgg");
Also note I've left lines to toggle visibility instead of display, which will hide the element but leave the space that it takes up.
EDIT: If you want it to change once and not revert, comment out that second binding in the function as follows:
function bindToggleVisibilityOnClick(firstElemId, secondElemId) {
var firstElement = document.getElementById(firstElemId);
var secondElement = document.getElementById(secondElemId);
firstElement.onclick = function() { toggleVisibility(firstElement, secondElement); };
//secondElement.onclick = function() { toggleVisibility(secondElement, firstElement); };
}
function toggleVisibility(checkElem, otherElem){
// If target is invisible
if (checkElem.style.display == "none"
//|| checkElem.style.visibility == "hidden"
) {
checkElem.style.display = "block";
// checkElem.style.visibility = "visible";
otherElem.style.display = "none"
// otherElem.style.visibility = "hidden";
}
else {
otherElem.style.display = "block";
checkElem.style.display = "none"
// checkElem.style.visibility = "hidden";
}
};
bindToggleVisibilityOnClick("egg", "brokenEgg");
#egg { display: block; }
#brokenEgg { display: none; }
<div id="egg"><p>hi</p></div>
<div id="brokenEgg"><p>hi2</p></div>
If I understood the question correctly you ca use an object instead of an array for myShapes.
var myShapes = {
"egg.png": "brokeEgg.png",
...
}
so when you click an image you can find the paired one.

Why doesn't this mouseover/rollover work?

I have 3 images (pic1, pic2, pic3) that on click of the div ID change to (pic4, pic5, pic6). All this works fine but I need to put in a mouseover command that when hovering over pic2, it changes to pic 7 and on mouseout it goes back to pic 2. I am unsure as to why this part of my code isn't working, is it a syntax error? The two functions I am trying to use to do this are "rolloverImage" and "init".
HTML
<div id="content1">
<img src="pic1.jpg" alt="pic1"/>
<img src="pic2.jpg" alt="pic2" id="pic2"/>
<img src="pic3.jpg" alt="pic3"/>
</div>
Javascript
var g = {};
//Change background colors every 20 seconds
function changebackground() {
var backColors = ["#6AAFF7", "#3AFC98", "#FC9B3A", "#FF3030", "#DEDEDE"];
var indexChange = 0;
setInterval(function() {
var selectedcolor = backColors[indexChange];
document.body.style.background = selectedcolor;
indexChange = (indexChange + 1) % backColors.length;
}, 20000);
}
function rolloverImage(){
if (g.imgCtr == 0){
g.pic2.src = g.img[++g.imgCtr];
}
else {
g.pic2.src = g.img[--g.imgCtr];
}
}
function init(){
g.img = ["pic2.jpg", "pic7.jpg"];
g.imgCtr = 0;
g.pic2 = document.getElementById('pic2');
g.pic2.onmouseover = rolloverImage;
g.pic2.onmouseout = rolloverImage;
}
window.onload = function() {
var picSets = [
["pic1.jpg", "pic2.jpg", "pic3.jpg"],
["pic4.jpg", "pic5.jpg", "pic6.jpg"],
];
var currentSetIdx = 0;
var contentDiv = document.getElementById("content1");
var images = contentDiv.querySelectorAll("img");
refreshPics();
contentDiv.addEventListener("click", function() {
currentSetIdx = (currentSetIdx + 1) % picSets.length;
refreshPics();
});
function refreshPics() {
var currentSet = picSets[currentSetIdx];
var i;
for(i = 0; i < currentSet.length; i++) {
images[i].src = currentSet[i];
}
}
changebackground();
init();
}

javascript not working on button as expected

I'm trying to connect previous and fwd buttons to a gallery and I want the previous button to be hidden on first image of the gallery but javascript doesn't seem to be working at all.
Javascript
var imageGallery = new Array();
imageGallery[0] = '1.png';
imageGallery[1] = '2.png';
imageGallery[2] = '3.png';
imageGallery[3] = '4.png';
imageGallery[4] = '5.png';
var imgCount = 0;
function next() {
imgCount++ ;
document.getElementById("gallery").src = imageGallery[imgCount] ;
}
function previous() {
imgCount--;
document.getElementById("gallery").src = imageGallery[imgCount] ;
}
if(document.getElementById("gallery").getAttribute("src") == "1.png")
{
document.getElementById("previous").style.visibility = 'hidden';
}
else
{
document.getElementById("previous").style.visibility = 'visible';
}
HTML
<div id="img">
<img id="gallery" src="1.png" style="height:420px; width:744px" >
<div id="imgNav">
<a id="previous" href onclick="previous(); return false;">previous</a>
<span style="color:#666; font-size:0.9em"> | </Span>
<a id="next" href onclick="next(); return false;">next</a>
</div>
</div>
Actually the logic is if 'src' attribute of id 'gallery' is '1.png' then 'visibility' of element with id 'previous' is 'hidden' else not but doesn't seem to be working. Can anyone help figuring it out.
You're probably trying to check on an image that's not totally loaded yet. Did you remember to place your code to run just when the page is fully loaded (in case it's placed in the page headers - you didn't mention whether it is or not)?
UPDATED
var imageGallery = new Array();
imageGallery[0] = '1.png';
imageGallery[1] = '2.png';
imageGallery[2] = '3.png';
imageGallery[3] = '4.png';
imageGallery[4] = '5.png';
var imgCount = 0;
function checkNav() {
var previousLnk = document.getElementById("previous");
var nextLnk = document.getElementById("next");
previousLnk.style.visibility = imgCount == 0 ? 'hidden' : 'visible';
nextLnk.style.visibility = imgCount >= (imageGallery.length - 1) ? 'hidden' : 'visible';
}
function setImg() {
var gallery = document.getElementById("gallery");
gallery.src = imageGallery[imgCount];
}
function next() {
imgCount++;
setImg();
checkNav();
}
function previous() {
imgCount--;
setImg();
checkNav();
}
window.onload = function () {
checkNav();
}
Demo: http://jsfiddle.net/N7V9E/

Taking var with JS prompt - how can I make it through HTML form?

I've been learning HTML/CSS/JavaScript for a couple of weeks now, and I am currently practicing on a mini project, which consists of letting people answer math questions, and validating their answers.
My current progress can be seen at http://dany.faceflow.com
I know I am probably not using the best strategy to develop this mini game, so any advice would be useful on that. However right now, the problem is that I am taking the user answer with a variable through JS prompt, and I want to do it via an HTML form (less annoying).
In my source code you can see this line within the function:
var userInput = prompt(numb1 + symbol + numb2);
Then, still in the same function, I have an if/else structure to compare the user's answer with the right answer. The code works, I just don't know how to make the prompt HTML-based instead. I've tried an html form with an ID and in the JS using getElementById, document.write and some other stuff but I never got it to work for that part.
(Here's all the JS)
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
var userAnswer = function() {
var numb1 = number1();
var numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
// Prompts the user to give an answer. Change this to HTML.
var userInput = prompt(numb1 + symbol + numb2);
//var userInput = document.getElementById('tw').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
return userInput;
}
(The HTML)
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<script src="js/script.js"></script>
<title>Improve Your Math Skills!</title>
</head>
<body>
<center>
<button onclick="userAnswer()">PLAY NOW!</button>
<div id="bubble"></div>
<div id="feedback"></div>
<!-- <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> -->
</center>
</body>
</html>
Thank you
You can use an input tag instead of the prompt. Change the HTML just as in Dinesh's answer;
<div id="bubble"></div>
<div id="inp" style="display: none;">
<input type="text" id="ans"></input> <button id="subBtn">Submit</button>
</div>
<div id="feedback"></div>
Now, for the JavaScript, there a few things to consider. Firstly, you have
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
Both functions do exactly the same thing; you don't need two separate functions to get two separate random numbers. So, only one function will suffice.
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
Secondly, now we have two functions. userAnswer to post a new question when 'Play Now!' is clicked and, say, evalAnswer to evaluate the answer written in the input field when 'Submit' is clicked.
In userAnswer, you generate two new random numbers and figure out which operation will be conducted on them. At this point, you can simply evaluate the answer yourself and store it in a global variable. This makes things easier when you evaluate the answer, you only need to do a simple comparison.
Other than that, you update innerHTML for bubble and display the div inp.
In evalAnswer, you get the value from ans and compare it with the previously computed value of the current answer, and then accordingly update feedback.innerHTML.
Here's the code;
//variable to maintain the current answer
var curAns = 0;
//Here, I get all the DOMElements I will use
var playBtn = document.getElementById('playBtn');
var bubble = document.getElementById('bubble');
var inp = document.getElementById('inp');
var ans = document.getElementById('ans');
var subBtn = document.getElementById('subBtn');
var feedback = document.getElementById('feedback');
//I add the event listeners
//This is equivalent to using 'onclick'
//in the HTML, and doing it this way is only
//my personal preference
playBtn.addEventListener('click', function() {userAnswer();}, false);
subBtn.addEventListener('click', function() {evalAnswer();}, false);
//Function to get random number
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
//This function will be executed when 'Play Now!' is clicked.
var userAnswer = function() {
//Get two separate random numbers in
//numb1 and numb2
var numb1 = number();
var numb2 = number();
var symbol = '';
var randomSymbol = Math.random();
//Determine the operation to be used
//and compute the corresponding correct answer for the current
//question
if (randomSymbol > 0.5) {
symbol = "+";
curAns = numb1+numb2;
} else {
symbol = "-";
curAns = numb1-numb2;
}
//Add math question to bubble
bubble.innerHTML = 'What is ' + numb1 + ' ' + symbol + ' ' + numb2 + '?';
feedback.innerHTML = '';
//Make inp div visible
inp.style.display = 'block';
//Reset input value to ''
ans.value = '';
};
//This function will be executed when 'Submit' is clicked
var evalAnswer = function() {
//Simply compare input value with computed
//answer and update feedback
if(parseInt(ans.value) !== curAns) {
feedback.innerHTML = 'Wrong answer, try again!';
}
else {
feedback.innerHTML = 'You got it right, congratulations!';
}
};
Here's a working example.
Hope that helped!
What I understand from your question is that you need the same functionality in HTML itself rather than driven by JS in a prompt box, if so,the below additions to your code should help:
HTML adition:
<div id="bubble"></div>
<div id="check_ans_div" style="display:none;">
<input type="text" id="txt_answer" />
<input type="submit" value="Check Answer" onclick="checkanswer()" />
</div>
<div id="feedback"></div>
JS changes:
var number1 = function() {
var numbx = Math.floor(Math.random() * 41) + 10;
return numbx;
}
var number2 = function() {
var numby = Math.floor(Math.random() * 41) + 10;
return numby;
}
var numb1=0; var numb2=0;
var userAnswer = function() {
numb1 = number1();
numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
if(document.getElementById('check_ans_div').style.display=='none')
document.getElementById('check_ans_div').style.display='block';
document.getElementById('txt_answer').value='';
}
function checkanswer(){
var userInput= document.getElementById('txt_answer').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
}

Categories