Display items on web page using AJAX and DOM - javascript

For this challenge, I am using AJAX to load contents to my web page, the first problem I have is to display the projects on the page. I have DOM selected the and I am trying to append as required but they still won't display. What am I missing? Secondly, my edit button is not behaving as I want it to.
const today = new Date();
const thisYear = today.getFullYear()
const footer = document.querySelector('footer');
const copyright = document.createElement('p');
copyright.innerHTML = `<span> © Erick Odero ${thisYear}</span> `;
footer.appendChild(copyright);
let skills = ['html', 'CSS', 'JavaScript'];
const skillsSection = document.getElementById('skills');
const skillsList = document.getElementById('skills').children[1];
for (let i = 0; i < skills.length; i++) {
const skill = document.createElement('li');
skill.textContent = skills[i];
skillsList.appendChild(skill);
}
// Create and handle edit button
const editMessage = document.querySelector('#text_message');
const editButton = document.createElement('button');
editButton.innerText = 'Edit';
editButton.type = 'button';
editButton.classList.add('btn');
editMessage.appendChild(editButton);
editMessage.addEventListener('click', (e) => {
const button = e.target;
const span = document.createElement('span');
const editedMessage = document.createElement('input');
input.type = 'text';
console.log(newMessage);
})
// Handle message form submit button
const messageForm = document.querySelector('form[name="leave_message"]')
messageForm.addEventListener('submit', (e) => {
// prevent default refreshing behavior
e.preventDefault();
// create variables for each form field
// const user_name = messageForm.name.value;
// const user_email = messageForm.email.value;
// const user_message = messageForm.message.value;
const user_name = e.target.name;
const user_email = e.target.email;
const user_message = e.target.message;
// Display messages in list
const messageSection = document.getElementById('messages');
const messageList = messageSection.children[1];
const newMessage = document.createElement('li');
newMessage.innerHTML = `${user_name.value}<span> wrote: ${user_message.value}</span>`;
// create button element
const removeButton = document.createElement('button');
removeButton.innerText = 'remove';
removeButton.type = 'button';
// handle the removeButton
removeButton.addEventListener('click', (e) => {
const entry = e.target.parentNode;
entry.remove();
})
// reset the form
messageForm.reset();
newMessage.appendChild(removeButton);
messageList.appendChild(newMessage);
})
const header = document.getElementById('header');
header.classList.add('sticky');
var gitHubRequest = new XMLHttpRequest();
gitHubRequest.onreadystatechange = function() {
if (gitHubRequest.readyState === 4 && gitHubRequest.status === 200) {
gitHubRequest.responseText;
}
};
gitHubRequest.open('GET', 'https://api.github.com/users/eodero/repos');
gitHubRequest.send();
gitHubRequest.addEventListener('load', (event) => {
let repositories = JSON.parse(gitHubRequest.response);
console.log(repositories);
});
const projectSection = document.getElementById('projects');
const projectList = projectSection.lastElementChild;
for (let i = 0; i < projectList.length; i++) {
const project = document.createElement('li');
project.innerText += project[i];
projectList.appendChild(project);
console.log(projectSection);
}
<!DOCTYPE html>
<html>
<head>
<title>erick_odero-portfolio</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edgev">
<link rel="stylesheet" href="index.css">
<script src="https://kit.fontawesome.com/631b2dc748.js" crossorigin="anonymous"></script>
</head>
<body>
<section class="list">
<header id="header">
<h1 id="my-name">Erick O Odero</h1>
<img src="https://avatars.githubusercontent.com/u/84427589?v=4" alt="Author's profile picture" width="60" height="60">
<nav class="main-menu">
<ul>
<li>Home</li>
<li>About</li>
<li>Projects</li>
<li>Connect</li>
</ul>
</nav>
</header>
</section>
<main>
<section id="about">
<h1>About</h1>
<p> I am healthcare worker in the field of clinical research residing in Memphis Tennessee and now an aspiring
<br> Software Developer. I am currently a student with Code The Dream taking Javascript, HTML, AJAX and <br> Fetch API lessons. When I learnt of the immense potential that technology has to improve health outcomes<br> of our communities, my interest
in coding was conjured and I hope to immerse myself full time in the industry.
</p>
</section>
<section class="list">
<h1>Experience</h1>
<ul id="exp">
<li>clinical Research Associate - United States</li>
<li>HIV program coordinator - Kenya</li>
<li>Health program coordinator - Kenya</li>
<li>Health Worker Training and Capacity building(volunteer) - Vanuatu</li>
</ul>
</section>
<section class="list">
<h1>My tools</h1>
<ul class="tools">
<li>Visual Studio Code</li>
<li><a href="https://www.apple.com/macbook-air/?afid=p238%7CsS5GAoNB9-dc_mtid_1870765e38482_pcrid_569734191494_pgrid_110391415659_&cid=aos-us-kwgo-mac--slid---product-">Mac
Bookair</a></li>
<li>Windows 10</li>
<li>Slack</li>
<li>Freecodecamp</li>
<li>Whimsical
</li>
<li>github</li>
</ul>
</section>
<section class="section">
<h1>My resume</h1>
<nav>
<ul>
<li>resume</li>
</ul>
</nav>
</section>
<section id="skills">
<h2 class="list">Skills</h2>
<ul id="skillz"></ul>
</section>
<section id="projects">
<h2>Projects</h2>
<ul>
</ul>
</section>
</main>
<!--Create leave message section and add form-->
<section class="section">
<h2>Leave a Message</h2>
<form name="leave_message">
<fieldset id="details">
<legend>1 Your details</legend>
<label for="name">Name:</label><br>
<input type="text" name="name" required="true"><br>
<label for="email">Email:</label><br>
<input type="email" name="email" required="true"><br>
</fieldset>
<fieldset id="text_message">
<legend>2 Your Message</legend>
<label for="message">Message:</label><br>
<textarea id="textMessage" name="message" required="true"></textarea><br>
</fieldset>
<button id="submit" class="btn" type="submit">Submit</button>
</form>
</section>
<!-- Add message list section-->
<section id="messages">
<h2>Messages</h2>
<ul>
</ul>
</section>
<footer></footer>
<script src="index.js"></script>
</body>
</html>

Related

navigation bar contents lose all styling after translation

I have ran into a problem, I have managed to translate nav bar. Right now, I have managed to translate all the content of the page but I have a problem which I cannot figure out myself. The problem: When I switch the language of the page from "English" to "Latvian" all <a hrefs> leading to other pages and css styling disappears. After the translation the latvian version becomes a plain text in the navbar, but it stays the same in heading and paragraph. Can anyone help me solve the problem?
const langEl = document.querySelector('.langWrap');
const link = document.querySelectorAll('a');
const titleEl = document.querySelector('.headings');
const descrEl = document.querySelector('.description');
const aboutUsEl = document.querySelector('.aboutus');
const newsEl = document.querySelector('.news');
const resultsEl = document.querySelector('.results');
const leaguesEl = document.querySelector('.leagues');
const loginEl = document.querySelector('.login');
link.forEach(el => {
el.addEventListener('click', () => {
langEl.querySelector('.active').classList.remove('active');
el.classList.add('active');
const attr = el.getAttribute('language');
titleEl.textContent = data[attr].headings;
descrEl.textContent = data[attr].description;
aboutUsEl.textContent = data[attr].aboutus;
newsEl.textContent = data[attr].news;
resultsEl.textContent = data[attr].results;
leaguesEl.textContent = data[attr].leagues;
loginEl.textContent = data[attr].login;
});
});
var data = {
"english":
{
"aboutus":"About Us",
"news":"News",
"results":"Results",
"leagues":"Leagues",
"login":"Profile",
"headings": "News",
"description":
"Last weekend there were a lot of great games."
},
"latvian":
{
"Aboutus":"Par mums",
"news":"Jaunumi",
"results":"Rezultāti",
"leagues":"līgas",
"login":"profils",
"headings": "Jaunumi",
"description":
"Pagājušajā nedēļā bija ļoti daudz labu spēļu"
}
}
<div class="langWrap">
EN
<a href='#' language='latvian'>LV</a>
</div>
<div class="content">
<header id="up">
<img src="/img/logo.png" alt="QuickSportScoresLogo" class="logo">
<div class="container">
<nav>
<ul>
<li class="aboutus">About Us</li>
<li class="news">News</li>
<li class="results">Results</li>
<li class="leagues">Leagues</li>
<li class="login">Profile</li>
</ul>
</nav>
</div>
</header>
<h1 class="headings"> News</h1>
<p class="description">Last weekend there were a lot of great games.
</p>
</div>
here's just change selector to a tag
const langEl = document.querySelector('.langWrap');
const link = document.querySelectorAll('a');
const titleEl = document.querySelector('.headings');
const descrEl = document.querySelector('.description');
const aboutUsEl = document.querySelector('.aboutus a');
const newsEl = document.querySelector('.news a');
const resultsEl = document.querySelector('.results a');
const leaguesEl = document.querySelector('.leagues a');
const loginEl = document.querySelector('.login a');
link.forEach(el => {
el.addEventListener('click', () => {
langEl.querySelector('.active').classList.remove('active');
el.classList.add('active');
const attr = el.getAttribute('language');
titleEl.textContent = data[attr].headings;
descrEl.textContent = data[attr].description;
aboutUsEl.textContent = data[attr].aboutus;
newsEl.textContent = data[attr].news;
resultsEl.textContent = data[attr].results;
leaguesEl.textContent = data[attr].leagues;
loginEl.textContent = data[attr].login;
});
});
var data = {
"english":
{
"aboutus":"About Us",
"news":"News",
"results":"Results",
"leagues":"Leagues",
"login":"Profile",
"headings": "News",
"description":
"Last weekend there were a lot of great games."
},
"latvian":
{
"aboutus":"Par mums",
"news":"Jaunumi",
"results":"Rezultāti",
"leagues":"līgas",
"login":"profils",
"headings": "Jaunumi",
"description":
"Pagājušajā nedēļā bija ļoti daudz labu spēļu"
}
}
<div class="langWrap">
EN
<a href='#' language='latvian'>LV</a>
</div>
<div class="content">
<header id="up">
<img src="/img/logo.png" alt="QuickSportScoresLogo" class="logo">
<div class="container">
<nav>
<ul>
<li class="aboutus">About Us</li>
<li class="news">News</li>
<li class="results">Results</li>
<li class="leagues">Leagues</li>
<li class="login">Profile</li>
</ul>
</nav>
</div>
</header>
<h1 class="headings"> News</h1>
<p class="description">Last weekend there were a lot of great games.
</p>
</div>

How to listen multiple button clicks in javascript

I have a products.html site where all the product are listed in a container and where you can add them to cart by using "Add to cart" button. My sites body looks like this
<body>
<header>
<nav class="navbar">
<ul class="nav-links">
<li>Front Page</li>
<li>Register</li>
<li>List Users</li>
<li>List Products</li>
<li>Shopping Cart</li>
</ul>
</nav>
</header>
<main>
<h1>Products</h1>
<div id="notifications-container"></div>
<div id="products-container"></div>
</main>
<footer>
<p>Copyright © 2020 diipadaa etc etc.</p>
</footer>
<template id="product-template">
<div class="item-row">
<h3 class="product-name"></h3>
<p class="product-description"></p>
<p class="product-price"></p>
<button>Add to cart</button>
</div>
</template>
<script src="js/utils.js"></script>
<script src="js/products.js"></script>
I have multiple product which i read and place them into the site by using the clone method.
const baseContainer = document.querySelector('#products-container');
const productTemplate = document.querySelector('#product-template');
products.forEach(product => {
const { name, description, price, _id } = product;
const productContainer = productTemplate.content.cloneNode(true);
productContainer.querySelector('.product-name').id = `name-${_id}`;
productContainer.querySelector('.product-name').textContent = name;
productContainer.querySelector('.product-description').id = `description-${_id}`
productContainer.querySelector('.product-description').textContent = description;
productContainer.querySelector('.product-price').id = `price-${_id}`;
productContainer.querySelector('.product-price').textContent = price;
document.getElementsByTagName('button').forEach(elem => {
console.log(elem);
});
baseContainer.append(productContainer);
});
If i have for example 15 products on the site how can i listen to every "Add to cart" button click and call a function to it. the buttons have no id or class. forEach doesnt work for me so it doesnt regonize that there is multiple buttons?
After you clone the button, you should give it an attribute to define what product it is associated with. Something like
products.forEach(product => {
const { name, description, price, _id } = product;
const productContainer = productTemplate.content.cloneNode(true);
//add a reference to the product ID in the button
productContainer.setAttribute("data-productID", _id);
...
Change
document.getElementsByTagName('button')
to
productContainer.getElementsByTagName('button')
Before you append, it does not exist in the document.

Why is text in between bold tags not rendered bold?

I am building a web tool for authors that follows a format we need for our backend. I didn't like a number of pre-made solutions for rich text editors as they were having way more features than I would need so I decided to parse my text through a function to detect bold using ** in the text.
I came across a regex solution here and when I used it, it detected the bold text and substituted * for <b> but displayed the tags instead of making the text between <b> and </b> bold.
I am new to HTML, CSS and JS so probably this is a simple error, but I couldn't find out how to deal with it myself...
// Tracks number of current textareas i.e. paragraphs
var element_counter = 0;
// Add Paragraph on button press
document.getElementById("addParagraph").addEventListener("click", function() {
var textarea = document.createElement("textarea");
var text = "Here goes your new paragraph.";
var node = document.createTextNode(text);
textarea.setAttribute("id", element_counter);
//textarea.setAttribute("class", "flow-text");
//textarea.setAttribute("oninput", "this.style.height = '';this.style.height = this.scrollHeight + 'px'");
textarea.append(node);
var section = document.getElementById("editor");
section.appendChild(textarea);
element_counter++;
reloadPreview();
});
// Add Image on button press
document.getElementById("addImage").addEventListener("click", function() {
var image = document.createElement("input");
image.setAttribute("type", "file");
image.setAttribute("id", element_counter);
image.setAttribute("accept", "image/*");
image.setAttribute("class", "file-field input-field");
var section = document.getElementById("editor");
section.appendChild(image);
element_counter++;
});
// Remove paragraph with confirmation step on button press
var confirm = false;
document.getElementById("removeLastItem").addEventListener("click", function() {
// Ensure there is an object to remove and wait for confirmation
if (document.getElementById(element_counter-1) != null) {
if (confirm === false) {
confirm = true;
document.getElementById("removeLastItem").innerHTML = "Confirm";
} else {
document.getElementById("removeLastItem").innerHTML = "Remove last item";
var element = document.getElementById(element_counter-1);
element.parentNode.removeChild(element);
confirm = false;
element_counter--;
reloadPreview();
}
}
});
// Remove all with confirmation step on button press
var confirmRemoveAll = false;
document.getElementById("removeAll").addEventListener("click", function() {
// Ensure there is an object to remove and wait for confirmation
if (document.getElementById(element_counter-1) != null) {
if (confirmRemoveAll === false) {
confirmRemoveAll = true;
document.getElementById("removeAll").innerHTML = "Confirm";
} else {
document.getElementById("removeAll").innerHTML = "Remove all";
var element = document.getElementById("editor").innerHTML = ""
confirmRemoveAll = false;
element_counter = 0;
reloadPreview();
}
}
});
// Preview on button press
document.getElementById("previewButton").addEventListener("click", reloadPreview);
// Preview current document status
function reloadPreview() {
// Clear previous preview
document.getElementById("preview").innerHTML = "";
// Add elements iteratively
var section = document.getElementById("preview");
const id = "preview";
for (var counter = 0; counter < element_counter; counter++) {
var type = document.getElementById(counter).nodeName;
// If text element
if (type === "TEXTAREA") {
var paragraph = document.createElement("p");
var text = document.getElementById(counter).value;
var richtext = boldText(text);
paragraph.setAttribute("id", id + counter);
paragraph.setAttribute("class", "flow-text");
paragraph.innerHTML = richtext;
section.appendChild(paragraph);
}
// If image element
if (type === "INPUT") {
// This weird structure allows to render item by item into preview and not mix up the order as onload is otherwise too slow
(function() {
var file = document.getElementById(counter).files[0];
var reader = new FileReader();
var image = document.createElement("img");
image.setAttribute("id", id + counter);
image.setAttribute("class", "materialboxed responsive-img");
section.appendChild(image);
reader.onload = function(e) {
image.setAttribute("src", e.target.result);
}
reader.readAsDataURL(file);
}())
}
}
}
function boldText(text){
var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
var richtext = text.replace(bold, '<b>$1</b>');
return richtext;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Climate Science</title>
<!--Used to unify web page appearance and this preview appearance-->
<link type="text/css" href="/css/materialize.css" rel="stylesheet">
<link type="text/css" href="/css/styles.css" rel="stylesheet">
<link type="text/css" href="/css/mystyles.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons&display=swap" rel="stylesheet">
<script href="text/javascript" src="/js/materialize.js"></script>
<link rel="manifest" href="/manifest.json">
<!-- IOS Support -->
<link rel="apple-touch-icon" href="/img/icons/icon-96x96.png">
<link rel="apple-touch-icon" href="/img/icons/icon-152x152.png">
<meta name="apple-mobile-web-app-status-bar" content="#5368ff">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="theme-color" content="#5368ff">
</head>
<body class="grey lighten-5">
<header>
<!-- top nav -->
<div class="navbar-fixed">
<nav class="z-depth-2">
<div class="nav-wrapper">
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>Log out</li> <!--TODO needed?-->
</ul>
</div>
</nav>
</div>
</header>
<div class="container">
<h3>Editor Area</h3>
<p><b>Linebreaks</b> within paragraphs are currently <b>ignored</b> to follow our internal database format.</p> <!--TODO check if accurate, \n possible integratable?-->
<!--
<h6>Safety switch</h6>
<div id="safetyswitch" class="switch">
<label>
Off
<input type="checkbox">
<span class="lever"></span>
On
</label>
</div>
<p>You can only remove paragraphs while the switch is deactivated!</p>
<h6>Auto-preview</h6>
<div id="safetyswitch" class="switch">
<label>
Off
<input type="checkbox">
<span class="lever"></span>
On
</label>
</div>
<p>The preview will load automatically while you edit your text</p>
<br>
-->
<button id="addParagraph" class="waves-effect waves-light btn">Add new paragraph</button>
<button id="addImage" class="waves-effect waves-light btn">Add new image</button>
<button id="removeLastItem" class="waves-effect waves-light btn">Remove last item</button>
<button id="removeAll" class="waves-effect waves-light btn">Remove all</button>
<div id="editor">
<!-- Here go all the content the author creates-->
</div>
<button id="previewButton" class="waves-effect waves-light btn">Update Preview</button>
<h3>Preview</h3>
<div id="preview">
<!-- Here will be the preview elements when clicking the button -->
<!--
<form action="#">
<p class="flow-text">What changes do you think we're already experiencing? Tap as many that apply</p>
<p>
<label>
<input type="checkbox" />
<span>Raising Sea Levels</span>
</label>
</p>
<p>
<label>
<input type="checkbox" />
<span>Fewer Heat Waves</span>
</label>
</p>
<p>
<label>
<input type="checkbox" />
<span>Worse Droughts</span>
</label>
</p>
<p>
<label>
<input type="checkbox" />
<span>Hotter heat waves</span>
</label>
</p>
<button class="btn waves-effect waves-light btn-large" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</form>
-->
</div>
</div>
<script href="text/javascript" src="js/preview.js"></script>
<script href="text/javascript" src="js/ui.js"></script>
</body>
</html>
Hi so perhaps use innerHTML to insert HTML into the tag body? So instead of paragraph.append:
paragraph.innerHTML = richtext;

Need to card images on cards for a memory game in JavaScript

I am working on a memory game, still. I have 36 images and an array of 36 numbers. I am randomly having numbers picked from the array that make up the 18 numbers for the cards. I need to create the cards and I am trying to append li's to a ul I have in the HTML.
Here is my HTML:
<!DOCTYPE html>
<!-- Group 5 CSD 122 The Holodeck - Games-->
<html>
<head>
<title>Games</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/all.js" integrity="sha384-xymdQtn1n3lH2wcu0qhcdaOpQwyoarkgLVxC/wZ5q7h9gHtxICrpcaSUfygqZGOe" crossorigin="anonymous"></script>
<link rel = "stylesheet" type = "text/css" href = "LCARSremake.css">
<link rel = "stylesheet" type = "text/css" href = "matchingGame.css">
<script src = "javascript/matchingGame.js"></script>
</head>
<body>
<div class = "recFrame">
<header>
<div id = "header" class = "lcars-row header">
<div class="lcars-elbow left-bottom"></div>
<div class="lcars-bar horizontal">
<div><h1 class = "title right"> Matching Game </h1></div>
</div>
<div class="lcars-bar horizontal right-end decorated"></div>
</div>
</header>
<div id = "leftmenu" class = "lcars-column start-space lcars-u-1">
<ul style = "list-style-type: none" class = "leftmenu">
<li class = "lcars-u-1 blank1"></li>
<li class = "lcars-u-1 home"> Home </li>
<li class = "lcars-u-1 games"> Games </li>
<li class = "lcars-u-1 about"> About </li>
<li class = "lcars-u-1 blank2"></li>
<li class = "lcars-u-1 blank3"></li>
<li class = "lcars-u-1 blank4"></li>
<li class = "lcars-u-1 blank5"></li>
<li class = "lcars-u-1 blank6"></li>
<li class = "lcars-u-1 blank7"></li>
</ul>
<div class="lcars-bar lcars-u-1"></div>
</div>
<main>
<div id = "contentFrame">
<div class = "lcars-column lcars-u-5">
<section class = "score-panel">
<div id = "startGame">Start Game</div>
<ul class = "rank">
<li><i class="fas fa-circle"></i></li>
<li><i class="fas fa-circle"></i></li>
<li><i class="fas fa-circle"></i></li>
<li><i class="fas fa-circle"></i></li>
</ul>
<span class = "moves">0 </span> MOVES | TIME:
<div class = "timer"></div>
<div class = "restart">
<i class="fas fa-redo"></i>
</div>
</section>
<ul class = "deck">
</ul>
<div id="popup1" class="overlay">
<div class="popup">
<h2>Congratulations</h2>
<a class="close" href=# >×</a>
<div class="content-1">
Congratulations you won!
</div>
<div class="content-2">
<p>You made <span id=finalMove> </span> moves </p>
<p>in <span id=totalTime> </span> </p>
<p>Rating: <span id=starRating></span></p>
</div>
<button id="play-again"onclick="playAgain()">
Play again</a>
</button>
</div>
</div>
</div>
</div>
</main>
<footer>
<div id = "footer" class = "lcars-row">
<div class="lcars-elbow left-top"></div>
<div class="lcars-bar horizontal both-divider bottom"></div>
<span class = "footerContent"><p> LCARS © Michael Okuda </p></span>
<div class="lcars-bar horizontal right-end left-divider bottom"></div>
</div>
</footer>
</div>
</body>
</html>
Here is the javascript code I'm trying to use to get the images to be the list item:
// The function init() enables the game to begin
function init() {
// The shuffle function shuffles the objects array
let allCards = shuffle(cardList());
$deck.empty();
// The game starts with no matching cards and zero moves
match = 0;
moves = 0;
$moves.text('0');
// A for loop creates <li> tags with the class of card for every <i> tag
// A class of fa fa- and a name of each object from the objects=[] array
for (let i = 0; i < allCards.length; i++) {
var img = allCards[i] + '.png';
$deck.append(('<li class="card"><img src = "images/symbols/ ' + img + '/>/li>'))
}
addCardListener();
// Enables the timer to reset to 0 when the game is restarted
resetTimer(nowTime);
second = 0;
$timer.text(`${second}`)
initTime();
}
Using the debugger and I get to the part where it is supposed to append, I just get the content from here displayed:
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
I have no idea what $deck is since you did not provide that so I have to somewhat guess. Just a side note you apparently have a number of global variables, never a good idea.
This line is not producing valid HTML:
$deck.append(('<li class="card"><img src = "images/symbols/ ' + img + '/>/li>'))
Compare to
$deck.append('<li class="card"><img src = "images/symbols/' + img + '"/></li>');
Note it would be much better to create all the elements, then append them one time to the DOM instead of hitting it multiple times.
SO, assuming markup as such:
<ul id="deck"></ul>
Script such as:
var $deck = $('#deck');
var mycards = $('<div/>');
var li = $('<li class="card"><img /></li>');
for (let i = 0; i < allCards.length; i++) {
var imgsrc = 'images/symbols/'+ allCards[i] + '.png';
li.find('img').prop('src',imgsrc);
mycards.append(li);
}
$deck.append(mycards.find('li'));
$deck.append(('<li class="card"><img src = "images/symbols/ ' + img + '/>/li>'))
should be
$deck.append('<li class="card"><img src="images/symbols/' + img + '" /></li>'))

Var wont display [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
So I'm bored so I decided to learn javascript an I came across this weird bug where one of my variables wont display even though it is the same code for both of them.
var wheatFields = 0;
var numWheat = 0;
var wheat = 0;
window.onload = function() {
document.getElementById("wheatFarms").innerHTML = wheatFields;
document.getElementById("numWheat").innerHTML = numWheat;
document.getElementById("wheatNum").innerHTML = wheat;
};
function addWheatFarm() {
wheatFields++;
document.getElementById("wheatFarms").innerHTML = wheatFields;
//wheatHandler();
}
function wheatHandler() {
var lifespan = Math.floor(Math.Random() * 50) + 10;
for (var i = 0; i <= lifespan; i++) {
wheat++;
document.getElementById("wheatNum").innerHTML = wheat;
}
}
<div data-role="page" id="start">
<div class="header">
<h1>Farming Game</h1>
</div>
<div data-role="main" class="ui-content">
<button id="wheatButton" onclick="addWheatFarm()">
Add a wheat farm.
</button>
</br>
<br>
<div id="fieldContainer" class="containers">
<ul data-role="listview" id="farms" data-count-theme="b" data-insert="true">
<br>
<li id="fieldCounter">
<p>Wheat Fields
<var id="wheatFarms"></var>
</p>
</li>
</ul>
</br>
</br>
</div>
<div id="inventoryContainer" class="containers">
<ul data-role="listview" id="inventory" data-count-theme="b" data-insert="true">
<li id="wheatCounter">
<p>Wheat <span id="wheatNum"></span>
<!--<p id = "wheatNum"></p>-->
</p>
</li>
</ul>
</div>
</div>
</div>
I'm not quite sure where I am going wrong. I did the same thing for both of them and I don't know why it works for one and not the other. The number of wheat farms displays and will update when I click the button. but the number of wheat wont even show the 0 starting value.
You should check out the console, when it says on this line:
document.getElementById("numWheat").innerHTML = numWheat;
Throws this error because there's no element there with id="numWheat":
Uncaught TypeError: Cannot set property 'innerHTML' of null
So all the code after that got stopped working. Remove that line and everything works.
Also, Math.Random() is not right. It's Math.random().
Fully Corrected Code
var wheatFields = 0;
var numWheat = 0;
var wheat = 0;
window.onload = function(){
document.getElementById("wheatFarms").innerHTML = wheatFields;
document.getElementById("wheatNum").innerHTML = wheat;
};
function addWheatFarm() {
wheatFields++;
document.getElementById("wheatFarms").innerHTML = wheatFields;
wheatHandler();
}
function wheatHandler(){
var lifespan = Math.floor(Math.random() * 50) + 10;
for (var i = 0; i <= lifespan; i++) {
wheat++;
document.getElementById("wheatNum").innerHTML = wheat;
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="stylesheet.css">
<script type="text/javascript" src="Scripts.js"></script>
</head>
<body>
<div data-role = "page" id = "start">
<div class = "header">
<h1>Farming Game</h1>
</div>
<div data-role = "main" class = "ui-content">
<button id = "wheatButton" onclick = "addWheatFarm()">
Add a wheat farm.
</button>
</br>
<br>
<div id = "fieldContainer" class = "containers">
<ul data-role = "listview" id = "farms" data-count-theme = "b" data-insert = "true">
<br>
<li id = "fieldCounter">
<p>Wheat Fields
<var id = "wheatFarms"></var>
</p>
</li>
</ul>
</br>
</br>
</div>
<div id = "inventoryContainer" class = "containers">
<ul data-role = "listview" id = "inventory" data-count-theme = "b" data-insert = "true">
<li id = "wheatCounter">
<p>Wheat <span id = "wheatNum"></span>
<!-- <p id = "wheatNum"></p> -->
</p>
</li>
</ul>
</div>
</body>
</html>
Try this it will work
https://jsfiddle.net/debashishkumar/4mf1mvkc/
<div data-role="page" id="start">
<div class="header">
<h1>Farming Game</h1>
</div>
<div data-role="main" class="ui-content">
<button id="wheatButton" onclick="addWheatFarm(12)">
Add a wheat farm.
</button>
<br>
<div id="fieldContainer" class="containers">
<ul data-role="listview" id="farms" data-count-theme="b" data-insert="true">
<br>
<li id="fieldCounter">
<p>Wheat Fields
<var id="wheatFarms"></var>
</p>
</li>
</ul>
<div id="inventoryContainer" class="containers">
<ul data-role="listview" id="inventory" data-count-theme="b" data-insert="true">
<li id="wheatCounter">
<p>Wheat <span id="wheatNum"></span>
<p id = "wheatNum"></p>
</p>
</li>
</ul>
</div>
</div>
</div>
<script>
var wheatFields = 0;
var numWheat = 0;
var wheat = 0;
window.onload = function() {
document.getElementById("wheatFarms").innerHTML = wheatFields;
document.getElementById("numWheat").innerHTML = numWheat;
document.getElementById("wheatNum").innerHTML = wheat;
};
function addWheatFarm() {
wheatFields++;
document.getElementById("wheatFarms").innerHTML = wheatFields;
wheatHandler();
}
function wheatHandler() {
var lifespan = Math.floor(Math.random() * 50) + 10;
for (var i = 0; i <= lifespan; i++) {
wheat++;
document.getElementById("wheatNum").innerHTML = wheat;
}
}
</script>

Categories