If condition on event listeners - javascript

I would like to use the addEventListener as a condition
so that if the condition is true by the clicking of the
image, the code executes, but it doesn't seem to work.
HTML
<div class = "content">
<img src = "dog.png" alt = "" id = "firstImage" >
<img src = "coatOfArm.png" alt = "" id = "second
Image" >
<p id = "score" >0</p>
</div>
JavaScript
var firstImage =
document.getElementById("firstImage");
var secondImage =
document.getElementById("secondImage");
var score= document.getElementById("score");
var totalScore_1 = 0;
var totalScore_2 = 0;
firstImage.addEventListeners("click",function() {
totalScore_1++;
score.innerHTML = totalScore_1;
})
secondImage.addEventListeners("click", function() {
totalScore_2++;
score.innerHTML = totalScore_2;
})
function increScore() {
if(first Image clicked == true){
firstImage. append(score) ;
} else{
secondImage. append(score) ;
}
} ;
increScore() ;

Related

Shopping Cart Update Total Function doesnt work

I am building an eCommerce store website, and I am facing an issue. The function updateCartTotal doesn't work at all. The script is also added to the bottom of the HTML body.
Thanks in advance.
HTML:
<span class="material-symbols-outlined" id="cart-icon">
shopping_cart
</span>
<div class="cart">
<h2 class="cart-title">Your Shopping Cart</h2>
<div class="cart-content">
<div class="cart-box">
<img src="/Monn-Homme/images/tie1.jpg" class="cart-image">
<div class="detail-box">
<div class="cart-product-title">
Tie
</div>
<div class="cart-price"> £10.99</div>
<input type="number" value="1" class="cart-qty">
</div>
<span class="material-symbols-outlined" id="cart-remove">
delete
</span>
</div>
</div>
<div class="total">
<div class="total-title">Total</div>
<div class="total-price">£10.99</div>
</div>
<button type="button" class="buy-btn">Buy Now</button>
<span class="material-symbols-outlined" id="close-cart">
close
</span>
</div>
</div>
Javascript:
let cartIcon = document.getElementById("cart-icon");
let cart = document.querySelector(".cart");
let CloseCart = document.querySelector("#close-cart");
cartIcon.onclick = () => {
cart.classList.add("active");
};
CloseCart.onclick = () => {
cart.classList.remove("active");
};
if (document.readyState == "loading") {
document.addEventListener("DOMContentLoaded", ready);
} else {
ready();
}
function ready() {
var removeCartButtons = document.getElementsByClassName("material-symbols-outlined");
for (var i = 0; i < removeCartButtons.length; i++) {
var button = removeCartButtons[i];
button.addEventListener("click", removeCartItem)
}
// Quantity Change //
var quantitInputs = document.getElementsByClassName("cart qty");
for (var i = 0; i < quantitInputs.length; i++) {
var input = quantitInputs[i];
input.addEventListener("change", quantityChanged);
}
}
function removeCartItem(event) {
var buttonClicked = event.target;
buttonClicked.parentElement.remove();
updateCartTotal();
}
quantityChanged = (event) => {
var input = event.target;
if (isNaN(input.value) || input.value <= 0) {
input.value = 1;
}
updateCartTotal();
}
function updateCartTotal() {
var cartContainer = document.getElementsByClassName("cart-content")[0];
var cartBox = cartContainer.getElementsByClassName("cart-box");
var total = 0
for (var i = 0; i < cartBox.length; i++) {
var cartBox = cartBox[i]
var priceElement = cartBox.getElementsByClassName("cart-price")[0]
var quantityElement = cartBox.getElementsByClassName("cart-qty")[0]
price = parseFloat(priceElement.innerText.replace("£", ""))
quantity = quantityElement.value
total = total + (price * quantity)
}
document.getElementsByClassName("total-price")[0].innerText = total
}
i am expecting the total to update as the quantity changes, and the function to work
You have the following mistakes-
There is no element with the class name cart qty.
var quantitInputs = document.getElementsByClassName("cart qty");
quantityChanged function should have a function keyword.
You are using the same name variable cartBox in updateCartTotal function which is creating confusion-
var cartBox = cartContainer.getElementsByClassName("cart-box");
for (var i = 0; i < cartBox.length; i++) {
var cartBox = cartBox[i]
}
Now, after fixing these mistakes, your code will look like the below which is working.
Note- I moved all the declarations to the top and I replaced those two methods-
getElementsByClassName() = querySelectorAll()
getElementsByClassName()[0] = querySelector()
let cartIcon = document.querySelector("#cart-icon");
let cart = document.querySelector(".cart");
let CloseCart = document.querySelector("#close-cart");
var quantitInputs = document.querySelectorAll(".cart-qty");
var removeCartButtons = document.querySelectorAll(".material-symbols-outlined");
var cartContainer = document.querySelector(".cart-content");
var cartBox = cartContainer.querySelectorAll(".cart-box");
var totalEl = document.querySelector(".total-price")
cartIcon.onclick = () => {
cart.classList.add("active");
};
CloseCart.onclick = () => {
cart.classList.remove("active");
};
if (document.readyState == "loading") {
document.addEventListener("DOMContentLoaded", ready);
} else {
ready();
}
function ready() {
for (var i = 0; i < removeCartButtons.length; i++) {
var button = removeCartButtons[i];
button.addEventListener("click", removeCartItem);
}
// Quantity Change //
for (var i = 0; i < quantitInputs.length; i++) {
var input = quantitInputs[i];
input.addEventListener("change", quantityChanged);
}
}
function removeCartItem(event) {
var buttonClicked = event.target;
buttonClicked.parentElement.remove();
updateCartTotal();
}
function quantityChanged(event) {
var input = event.target;
if (isNaN(input.value) || input.value <= 0) {
input.value = 1;
}
updateCartTotal();
};
function updateCartTotal() {
var total = 0;
for (var i = 0; i < cartBox.length; i++) {
var cartBoxEl = cartBox[i];
var priceElement = cartBoxEl.querySelector(".cart-price");
var quantityElement = cartBoxEl.querySelector(".cart-qty");
price = parseFloat(priceElement.innerText.replace("£", ""));
quantity = quantityElement.value;
total = total + price * quantity;
}
if (totalEl) {
totalEl.innerText = total;
}
}
<div>
<span class="material-symbols-outlined" id="cart-icon">
shopping_cart
</span>
<div class="cart">
<h2 class="cart-title">Your Shopping Cart</h2>
<div class="cart-content">
<div class="cart-box">
<img src="/Monn-Homme/images/tie1.jpg" class="cart-image">
<div class="detail-box">
<div class="cart-product-title">
Tie
</div>
<div class="cart-price"> £10.99</div>
<input type="number" value="1" class="cart-qty">
</div>
<span class="material-symbols-outlined" id="cart-remove">
delete
</span>
</div>
</div>
<div class="total">
<div class="total-title">Total</div>
<div class="total-price">£10.99</div>
</div>
<button type="button" class="buy-btn">Buy Now</button>
<span class="material-symbols-outlined" id="close-cart">
close
</span>
</div>
</div>

html not appending to the carousel on popover

I Am Trying to make a popover with a bootstrap carousel and where the carousel items are to be generated and appended from a script but I get the carousel but I am unable to append the item. I tried hard but I didn't come up with a solution.
the HTML initialized is as below
HTML:
<div class="popup" data-popup="popup-1">
<div class="popup-inner">
<i class="fas fa-bars"></i>
<div class="frame">
<div id='carousel' class='carousel slide' data-bs-ride='carousel'>
<div class='carousel-inner items-slider1'>
</div>
</div>
</div>
</div>
</div>
the script I have tried was
Javascript:
function findallchord(currentchord , currenttype) {
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord ,currenttype,i)) {
Raphael.chord("div3", Raphael.chord.find(currentchord , currenttype,i), currentchord +' ' +currenttype).element.setSize(75, 75);
}
}
}
var getChordRoots = function (input) {
if (input.length > 1 && (input.charAt(1) == "b" || input.charAt(1) == "#"))
return input.substr(0, 2);
else
return input.substr(0, 1);
};
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
});
I have also tried appendTo also as
$(theDiv).appendTo('.items-slider1');
Please Help to solve this
This is the output I get, the appended elements are not in the carousel
Note: I am using Bootstrap 5
Try instantiating the carousel after you've set it up
/*
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
*/
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
$('.carousel-inner').carousel();
});
It was needed to do call the click function first before popover as below
$('[data-bs-toggle="popover"]').click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
}).popover({
html: true,
content: function() {
return $('.popup').html();
}});

Having trouble with displaying an image through an array

I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>

how to change the css of the parent div in javascript not jquery

I want to change the CSS of a parent div if I click the child of its parent div, not, for example if I click href tag. I want to change the CSS of its class="changed_area".
How can I do this?
var up_btn = document.getElementsByClassName('up_btn');
var up_btn_length = up_btn.length;
var changed_area = document.getElementsByClassName('changed_area');
var changed_area_length = changed_area.length;
for (var i = 0; i < up_btn_length; i++) {
up_btn[i].addEventListener('click', function() {
//alert('welcome');
for (var i = 0; i < changed_area_length; i++) {
if (changed_area[i].style.top == '-100%') {
changed_area[i].style.top = '0%';
}
else {
changed_area[i].style.top = '-100%';
}
}
});
}
<?php foreach($questions As $question): ?>
<div class="changed_area" style="width: 100px;">
<div class="inside_ajax_part1">
<div id="inside_left">
<img src="<?php echo $Filter_customer->image; ?>" />
</div>
<div id="inside_right">
<a class="up_btn" href="#">Up</a>
</div>
</div>
<div class="inside_ajax_part2">
<p>mohammed</p>
</div>
</div>
<?php endforeach; ?>
I think you can do something like this : https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
EDIT : better way to do this
for (var i = 0; i < up_btn_length; i++) {
up_btn[i].addEventListener('click', function(){
var changed_area = up_btn[i].parentElement;
if ( changed_area.classList.contains('changed_area') ) {
changed_area.classList.remove('changed_area')
}
else {
changed_area.classList.add('changed_area')
}
if(changed_area.style.top == '-100%') {
changed_area.style.top = '0%';
}
else {
changed_area.style.top = '-100%';
}
});
}
Just add event listener on parent and use currentTarget
const parent = document.getElementsByClassName('changed_area');// select parent
for (var i = 0; i < parent.length; i++) {
parent[i].addEventListener('click', (ev) => ev.currentTarget.className = 'clicked');
}
Here is fiddle for it
Your code affects all of your divs with class "changed_area", That I don't think it is what you intend.
To access a parent element with javascript you can use parentElement. To get the parent of parent of parent.... that meets some condition (like having a class) you can do this:
function Get_changed_area(targetElement){
var parent = targetElement.parentElement;
if(parent.hasClass('changed_area'))
return parent;
else Get_changed_area(parent) //repeat the function for parent
}
for (var i = 0; i < up_btn_length; i++) {
up_btn[i].addEventListener('click', function() {
changed_area = Get_changed_area(up_btn[i]);
if (changed_area.style.top == '-100%') {
changed_area.style.top = '0%';
}
else {
changed_area.style.top = '-100%';
}
}
}

Javascript for loop not repeating strings

very new to Javascript here, and I think I'm having a logic issue. So basically for class I'm building a hangman game, and I am having trouble with double letters. for instance if the word is food, when I enter an "O" it will pass through the for loop, hit that first O, push it to the screen, and stop dead in its tracks. I can do whatever I want to that first "O" but a second one or any other repeated letter gets ignored. Now the alert I wrote directly under the start of the for() loop, will successfully print both "O's", as will logging it to the console, or even flat out writing document.write(splitWord[m]);
So to me, I think it has to be my if statement. I could be 100% wrong on this, but I assume that the if statement tells it to see the first "O", do what's in the bracket, and then move on to the next letter skipping any doubles. If I am right about this, what would be a better option to keep the loop going, so both "O's" would be filled. And if I am completely wrong, what would be a better course of action to accomplish this task. Any help would be very greatly appreciated.
Thanks
var remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var removedLetters =[];
var wordList = ["django", "the#good#the#bad#and#the#ugly", "a#fistful#of#dollars","for#a#few#dollars#more","once#upon#a#time#in#the#west","the#wild#bunch","pale#rider"];
var titleList =["django", "The Good The Bad And The Ugly", "A Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"];
var songList =["Jango", "The Good The Bad And The Ugly", "Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"]
var selectedWord;
console.log(selectedWord);
var livesRemaining = 12;
var score = 0;
var wordWorth = 0;
var wins = 0;
var losses = 0;
var gameOn = false;
function chooseAWord(){
selectedWord = wordList[Math.floor(Math.random() * wordList.length)];
console.log(selectedWord);
}
function printWord(){
document.getElementById("wordDisplayer").innerHTML = selectedWord;
}
function buildTiles(){
// create a new div element
// and give it some content
var splitWord = selectedWord.split("");
for(i = 0; i < splitWord.length; i++){
if (splitWord[i] != '#'){
// var newTile = document.createElement("div");
//var newContent = document.createTextNode("");
//newTile.appendChild(newContent); //add the text node to the newly created div.
document.getElementById("wordTiles").innerHTML += '<div class="tileStyle" id="' + splitWord[i] + '"></div>';
wordWorth++;
// add the newly created element and its content into the DOM
//var currentDiv = document.getElementById("wordTiles");
//currentDiv.appendChild(newTile, currentDiv);
// newTile.setAttribute("class", "tileStyle");
}else if(splitWord[i] == '#'){
var blankTile = document.createElement("div");
var spaceContent = document.createTextNode("");
blankTile.appendChild(spaceContent);
document.getElementById("wordTiles").innerHTML += '<div class="blankStyle" id="' + splitWord[i] + '"></div>';
}
}
}
function clearTiles(){
var myNode = document.getElementById("wordTiles");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
function refreshAlphabet(){
remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
displayAvailableLetters();
}
function keyPressed(){
checkPlayerChoiceNew();
}
var playerGuess = document.onkeyup = function myKeyDown(event){
playerGuess = event.key;
if(gameOn==true){
keyPressed();
}else{
}
}
function checkPlayerGuess(){
document.getElementById("isThisWorking").innerHTML = playerGuess;
}
// function myFunction() {
// var str = "Tha bast things in lifa ara free";
// var patt = new RegExp(playerGuess);
// var res = patt.test(selectedWord.toLowerCase());
// document.getElementById("demo").innerHTML = res;
//}
function displayAvailableLetters(){
document.getElementById("lettersStillAvailable").innerHTML = remainingLetters;
console.log(remainingLetters);
}
function displayRemovedLetters(){
document.getElementById("lettersUsed").innerHTML = removedLetters;
}
function updateScore(){
document.getElementById("scoreTotal").innerHTML = score;
}
function updateWins(){
document.getElementById("winTotals").innerHTML = wins;
}
function updateLosses(){
document.getElementById("lossTotals").innerHTML = losses;
}
function checkScore(){
if(score == selectedWord.length && livesRemaining > 0){
document.getElementById("gameOver").innerHTML = "WINNER! Congratulations!!!";
wins++;
updateWins();
gameOn=false;
}else if (livesRemaining == 0){
livesRemaining == -1;
document.getElementById("gameOver").innerHTML = "You have failed!";
losses++;
updateLosses();
gameOn=false;
}else{
document.getElementById("gameOver").innerHTML = "Good Luck!";
}
}
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = playerGuess;
}
}
}
//check playerGuess against selectedWord
function checkPlayerChoice(){
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
if(compareWord == true && compareAlphabet == true ){
document.getElementById("demo").innerHTML = playerGuess;
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
displayAvailableLetters();
displayRemovedLetters();
score++;
updateScore();
checkScore();
}else if(compareWord == true && compareAlphabet == false){
document.getElementById("demo").innerHTML = "Already tried that one";
}else if(compareWord == false && compareAlphabet == true){
livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
document.getElementById("demo").innerHTML = "Already tried that one ;)";
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
}else{
/*livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();*/
document.getElementById("demo").innerHTML = "Not a Valid Key";
}
}
//document.onkeyup = function myKeyDown(event){
// playerGuess = event.key;
//}
//start / Restart the game
function resetGame() {
livesRemaining = 12;
score =0;
wordWorth = 0;
clearTiles();
document.getElementById("lives").innerHTML = livesRemaining;
chooseAWord();
printWord();
buildTiles();
refreshAlphabet();
gameOn=true;
}
.tileStyle{
width:30px;
height:30px;
border:1px solid black;
background-color:green;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.blankStyle{
width:30px;
height:30px;
background-color:orange;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.fixer{
width:100%;
height:10px;
clear:both;
}
<body>
<button onclick="checkPlayerChoice()">Try it</button>
<p id="demo"></p>
<p> lives: </p>
<p id = "lives"> 0</p>
<p> Score: </p>
<p id = "scoreTotal">0</p>
<p>wins</p>
<p id ="winTotals">0</p>
<p>losses</p>
<p id ="lossTotals">0</p>
<p id ="gameOver"></p>
<button onclick ="resetGame()">New Game</button>
<p>Here is the word</p>
<p id = "wordDisplayer">Press New Game to Start</p>
<div id = "wordTiles"></div>
<div class ="fixer"></div>
<button onclick ="checkPlayerGuess()">What Key was Pressed?</button>
<p id ="isThisWorking">What will I say?</p>
<p>Letters Still Available</p>
<p id ="lettersStillAvailable"></p>
<p>Bad Guesses</p>
<p id ="lettersUsed"></p>
<br />
selectedWord ="food";
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = choice;
}
}
}
You can refer this below logic. In this example, I have given some inputs.
var selectedWord ="food";
var displayString = [];
for(var i = 0; i < selectedWord.length; i++){
displayString[i] = "-"
}
var outputEle = document.getElementById("output");
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
function checkPlayerChoiceNew(playerGuess){
var newWord = "";
var regExp = new RegExp(playerGuess,'ig')
selectedWord.replace(regExp, function(value, index){
displayString[index] = value;
return value;
});
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
newWord = displayString.join("");
if(selectedWord == newWord){ alert("You Won the game"); }
//outputEle.innerText = displayString.join(" ");
}
checkPlayerChoiceNew('o');
checkPlayerChoiceNew('g');
checkPlayerChoiceNew('d');
checkPlayerChoiceNew('f');
<div id="output">
</div>

Categories

Resources