This is a simple issue that I am having. I am new to javascript and trying to create a BMI calculator with a color code to indicate the BMI result. I am adding a class to the color based on the BMI result. for eg. I am adding "active" class to the "normal" div when the BMI is normal. Same for others. But if a class is added I can not remove it when other is selected.
How can I fix it?
const hFeet = document.querySelector("#hFeet");
const hInch = document.querySelector("#hInch");
const wKg = document.querySelector("#wKg");
const submit = document.querySelector("#submit");
const result = document.querySelector("#result_area");
const wStatus = document.querySelector("#wst");
submit.addEventListener("click", bmiFunc);
function bmiFunc(event) {
event.preventDefault();
const height = hFeet.value * 0.3048 + hInch.value * 0.0254;
const weight = wKg.value;
const calculation = weight / Math.pow(height, 2);
const final = calculation.toFixed(2);
result.innerHTML = final;
if (final < 16) {
wStatus.innerHTML = "Severe Thinness";
document.querySelector(".thin1").classList.add("active");
} else if (final >= 16 && final < 17) {
wStatus.innerHTML = "Moderate Thinness";
document.querySelector(".thin2").classList.add("active");
} else if (final >= 17 && final < 18.5) {
wStatus.innerHTML = "Mild Thinness";
document.querySelector(".thin3").classList.add("active");
} else if (final > 18.5 && final <= 25) {
wStatus.innerHTML = "Normal";
document.querySelector(".norm1").classList.add("active");
} else if (final > 25 && final <= 30) {
wStatus.innerHTML = "Overweight";
document.querySelector(".ow1").classList.add("active");
} else if (final > 30 && final <= 35) {
wStatus.innerHTML = "Obese Class I";
document.querySelector(".obs1").classList.add("active");
} else if (final >= 35 && final <= 40) {
wStatus.innerHTML = "Mild Thinness";
document.querySelector(".obs2").classList.add("active");
} else if (final > 40) {
wStatus.innerHTML = "Mild Thinness";
document.querySelector(".obs3").classList.add("active");
}
}
.color .column {
height: 30px;
transition: all 0.2s ease-in;
}
.clm_thin .thin1 {
background: #ff9595;
}
.clm_thin .thin2 {
background: #ffafaf;
}
.clm_thin .thin3 {
background: #ffdab6;
}
.clm_normal .norm1 {
background: #4e9b00;
}
.clm_overWeight .ow1 {
background: #f5f500;
}
.clm_obesity .obs1 {
background: #ff7474;
}
.clm_obesity .obs2 {
background: #ff3e3e;
}
.clm_obesity .obs3 {
background: #db0000;
}
.active {
transform: scale(1.5);
}
.bmi_scale {
margin-top: 30px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Google Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic" />
<!-- CSS Reset -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.css" />
<!-- Milligram CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.4.1/milligram.css" />
<!-- You should properly set the path from the main file. -->
<link rel="stylesheet" href="assets/css/style.css" />
<title>BMI calculator</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="column">
<div class="bmi_wrapper">
<div class="bmi_form">
<form action="">
<div class="bmi_height">
<h3>Your Height:</h3>
<div class="row">
<div class="column">
<input type="text" name="hFeet" id="hFeet" />
<label for="hFeet">feet</label>
</div>
<div class="column">
<input type="text" name="hInch" id="hInch" />
<label for="hInch">inchs</label>
</div>
</div>
</div>
<!-- bmi_height -->
<div class="bmi_weight">
<h3>Your weight:</h3>
<div class="row">
<div class="column">
<input type="text" name="wKg" id="wKg" />
<label for="wKg">Kg</label>
</div>
</div>
</div>
<!-- bmi_weight -->
<div class="bmi_btn">
<input type="submit" value="Calculate BMI" id="submit" />
</div>
<!-- bmi_btn -->
</form>
</div>
<!-- bmi_form -->
<div class="bmi_result">
<div class="bmi">Your BMI is: <span id="result_area">0</span> kg/m<sup>2</sup></div>
<div class="wStatus">Weight Status: <span id="wst"></span></div>
</div>
<!-- bmi_result -->
<div class="bmi_scale">
<div class="row">
<div class="column clm_thin">
<div class="row color">
<div class="column thin1 column-50"></div>
<div class="column thin2 column-25"></div>
<div class="column thin3 column-25"></div>
</div>
</div>
<!-- column_thin -->
<div class="column clm_normal">
<div class="row color">
<div class="column norm1"></div>
</div>
</div>
<!-- column_normal -->
<div class="column clm_overWeight">
<div class="row color">
<div class="column ow1"></div>
</div>
</div>
<div class="column clm_obesity">
<div class="row color">
<div class="column obs1"></div>
<div class="column obs2"></div>
<div class="column obs3"></div>
</div>
</div>
</div>
</div>
<!-- bmi_scale -->
</div>
<!-- bmi_wrapper -->
</div>
<!-- column -->
</div>
<!-- row -->
</div>
<!-- container -->
</body>
</html>
Here is the jsfiddle link
jsfiddle
The simplest you can do is reset beforehand the class from your ".active":
In the lack of a more descriptive className - use .bmi_scale .column to target the "columns"
document.querySelector(".bmi_scale .column.active").classList.remove("active");
// if (final < 16) { etc.....
Or, if needed for some case - from all:
document.querySelectorAll(".bmi_scale .column").forEach(el => {
el.classList.remove("active")
});
// if (final < 16) { etc.....
Related
(Sorry for poor english, it is not my first language)
The digital queue management i made for a paper needs to be updated manually by every device, i imagine i will need to enter back-end territory so the program is already running in a server, but i'm not well versed in any back-end tecnology and dont know how they can comunicate with the work i have done. my objective is to have the token to update in every machine automaticaly
This is what i managed to do, a friend of mine recomended me the jquery-3.3.1.min package to help
Thank you for your help
<!DOCTYPE html>
<html>
<head>
<title>Queue</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/jquery-3.3.1.min.js"></script>
<script src="lib/scripts.js"></script>
</head>
<body>
<div class="barraTop"> </div>
<div class="container page">
<div class="row barraSuperior">
<div class="col-xs-11" style="text-align: right;"><p></p>
<span class="uespiTexto">Waiting queue</span><br>
</div>
</div>
<div class="row">
<div class="senhaAtual">
<div class="row">
<div class="col-xs-5 col-xs-offset-1" style="text-align: right;"><br><br>
<span class="senhaAtualTexto">TOKEN </span>
</div>
<div class="col-xs-5" style="text-align: left;">
<span id="senhaAtualNumero">0000</span>
</div>
<input type="hidden" id="senhaNormal" value="0000">
<input type="hidden" id="senhaPrioridade" value="P000">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-4 col-xs-offset-4 ultimaSenha">
<br>
<span id="ultimaSenhaTexto">LAST TOKEN</span><br>
<span>Token </span>
<span id="ultimaSenhaNumero">0000</span>
</div>
</div>
</div>
<audio id="audioChamada" src="audio/chamada.wav"></audio>
</body>
</html>
let filename = "senhas.txt";
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
jQuery(document).ready(function($) {
$("body").on('keydown', function(e) {
var senhaAtual = $("#senhaAtualNumero");
var senhaNormal = $("#senhaNormal");
var senhaPrior = $("#senhaPrioridade");
var ultimaSenha = $("#ultimaSenhaNumero");
var audioChamada = $("#audioChamada");
if(e.keyCode == 39){
ultimaSenha.html(senhaAtual.html());
senha = parseInt(senhaNormal.val()) + 1;
senhaAtual.html(pad(senha, 4));
senhaNormal.val(pad(senha, 4));
audioChamada.trigger("play");
}
if(e.keyCode == 65){
senha = parseInt(senhaNormal.val()) - 1;
senhaAtual.html(pad(senha, 4));
senhaNormal.val(pad(senha, 4));
}
if(e.keyCode == 38){
ultimaSenha.html(senhaAtual.html());
senha = parseInt(senhaPrior.val().replace("P","")) + 1;
senhaAtual.html("P" + pad(senha, 3));
senhaPrior.val("P" + pad(senha, 3));
audioChamada.trigger("play");
}
if(e.keyCode == 83){
senha = parseInt(senhaPrior.val().replace("P","")) - 1;
senhaAtual.html("P" + pad(senha, 3));
senhaPrior.val("P" + pad(senha, 3));
}
});
});
In this code I can't make the "All" filter button show me the whole menu!
When the product category filters are placed, they display properly, but once the "All" button is clicked, all the products in the DOM disappear.
I tried everything, inserting and removing elements and structures outside some of the functions, in case it was something out of scope, but nothing.
I believe that between line 66 and 84 the error should be but I have not been able to find what it is.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title></title>
</head>
<body>
<h3>Cheeky Chooks</h3>
<hr>
<div id="divFilterButtons" class="row justify-content-between">
</div>
<div class="m-2">
Serch by ingredient
<input id="searchIngredient">
</div>
<hr>
<div id="menu" class="d-flex flex-row flex-wrap justify-content-center">
</div>
<div id="cartSection" class="bg-warning">
<h3 class="text-center m-2 p-3">
THIS IS YOUR CART
</h3>
<form>
<input id="inputName" class="contactInfo" type="text" placeholder="Enter your name">
<input id="inputAddress" class="contactInfo" type="text" placeholder="Enter your address">
<input id="inputPhone" class="contactInfo" type="number" placeholder="Enter your phone number">
<input id="saveContactBtn" class="" type="submit" value="Save contact info">
</form>
<hr>
<div class="d-flex">
<p class="fs-4 col-1">Quantity</p>
<p class="fs-4 col-2">Name</p>
<p class="fs-4 col-2">Price</p>
<p class="fs-4 col-2">Subtotal</p>`
</div>
<div id="divCart">
</div>
<div id="divCartTotal">
<input type="submit" id="btnPayConfirm" value="Pay & confirm">
</div>
</div>
<div>
FOOTER
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html>
class Dish {
constructor(id,type,name,principal,otherIngredients,price,img,q){
this.id=id
this.type=type
this.name=name
this.principal=principal
this.otherIngredients=otherIngredients
this.price=parseFloat(price)
this.img=img
this.q=parseInt(q)
}
addq(){
this.q++
}
};
const menuType = [`Chicken`,`Burguers`,`Wraps`,`Meals`,`Sides`];
const menuAll = [];
const cart=[];
let contactDetails =[]
userDetails()
menuAll.push(new Dish(`C-W`,menuType[0],`Whole chicken`,`BBQ chicken`,`free garlic sause`,16.90,`img/ChickenWholeChicken.png`,1));
menuAll.push(new Dish(`C-1/2`,menuType[0],`1/2 chicken`,`BBQ chicken`,`free garlic sause`,9.90,`img/Chicken12.png`,1));
menuAll.push(new Dish(`C-1/4`,menuType[0],`1/4 chicken`,`BBQ chicken`,`free garlic sause`,5.90,`img/Chicken14.png`,1));
menuAll.push(new Dish(`B-CHE`,menuType[1],`Cheeky Burguer`,`Flame grilled chicken`,`cheese - lettuce - Cheeky sauce`,10.90,`img/BurguerCheekyChookBurguer.png`,1));
menuAll.push(new Dish(`B-CHI`,menuType[1],`Chilli Chook Burguer`,`Flame grilled chicken`,`cheese - lettuce - Chilli sauce`,10.90,`img/BurguerChilliChookBurguer.png`,1));
menuAll.push(new Dish(`W-CHE`,menuType[2],`Cheeky Wrap`,`Shredded chicken`,`tomatoe - onion - parsley - pickles - turnip - garlic sause`,11.90,`img/WrapsCheekyWrap.png`,1));
menuAll.push(new Dish(`W-FAL`,menuType[2],`Falafel Wrap`,`Falafel`,`tomatoe - onion - parsley - pickles - turnip - hummus`,11.90,`img/WrapsFalafelWrap.png`,1));
menuAll.push(new Dish(`M-BOX`,menuType[3],`Cheeky Box`,`1/4 Chicken`,`chips - salad - garlic - pickles - turnips`,14.90,`img/MealCheekyBox.png`,1));
menuAll.push(new Dish(`M-PLA`,menuType[3],`Cheeky Plate`,`1/2 Chicken`,`chips - salad - garlic - hummus - baba ghannouj - pickles - turnips - bred`,23.90,`img/MealsCheekyPlate.png`,1));
menuAll.push(new Dish(`S-LFR`,menuType[4],`Cheeky Loades Fries`,`Chips`,`cheese - tabouli - chilli & cheeky sause`,10.90,`img/SidesCheekyLoadesFries.png`,1));
menuAll.push(new Dish(`S-SFR`,menuType[4],`Small chips`,`Chips`,`chicken salt`,4.50,`img/SidesSmallChips.png`,1));
let divMenu = document.getElementById(`menu`);
let divFilterButtons= document.getElementById(`divFilterButtons`);
let searchIngredient= document.getElementById(`searchIngredient`);
let divCart= document.getElementById(`divCart`);
let divCartTotal= document.getElementById(`divCartTotal`);
const saveContactBtn = document.getElementById(`saveContactBtn`);
const btnPayConfirm = document.getElementById(`btnPayConfirm`);
let filterButtons= document.getElementsByClassName(`filterButton`)
//UI
function buttonsUI (list){
divFilterButtons.innerHTML += `<div class="col-2 d-flex justify-content-center"> <button id="All" class="filterButton col-6">All</button> </div>`
for (const type of list) {
divFilterButtons.innerHTML += `<div class="col-2 d-flex justify-content-center"> <button id="${type}" class="filterButton col-6">${type}</button> </div>`
}
}
buttonsUI(menuType);
function menuUI(list) {
divMenu.innerHTML=''
for (const dish of list) {
let div=document.createElement(`div`);
div.className="card col-3 m-3"
div.innerHTML= `<img src="${dish.img}" class="card-img-top" alt="${dish.name}">
<h3>${dish.name}</h3>
<h4>${dish.principal}</h2>
<p>WITH: ${dish.otherIngredients}</p>
<h3>$ ${dish.price}-</h3>
<button id="${dish.id}"class="btnBuyDish btn btn-primary col-3">Buy</button>`
divMenu.append(div);
}
buyBtnClick ()
}
menuUI(menuAll);
//Filters
for (const button of filterButtons) {
if (this.id!="All") {
button.addEventListener('click',function(){
const results= menuAll.filter(dish => dish.type == this.id);
menuUI(results);
})
}else {
menuUI(menuAll);
}
}
searchIngredient.addEventListener(`input`,function(){
const results = menuAll.filter(dish=> dish.otherIngredients.includes(this.value)|| dish.name.includes(this.value) || dish.principal.includes(this.value))
if (results.length >0) {
menuUI(results);
}else{
divMenu.innerHTML='We dont have any dish with it'
}
});
//Contact details
saveContactBtn.addEventListener('click', saveContactDetails);
function saveContactDetails() {
contactDetails=[]
localStorage.removeItem('Contact');
let name = document.getElementById(`inputName`).value
let address = document.getElementById(`inputAddress`).value
let phone = document.getElementById(`inputPhone`).value
if (name!="" && address!="" &&phone!="") {
contactDetails.push(name);
contactDetails.push(address);
contactDetails.push(phone);
localStorage.setItem('Contact',contactDetails)
}
}
function userDetails() {
if ('Contact' in localStorage) {
contactDetails = localStorage.getItem('Contact').split(',')
document.getElementById(`inputName`).value=contactDetails[0]
document.getElementById(`inputAddress`).value=contactDetails[1]
document.getElementById(`inputPhone`).value=contactDetails[2]
}
}
//Cart
function buyBtnClick (){
let btnsBuyDish= document.getElementsByClassName(`btnBuyDish`);
for (const button of btnsBuyDish) {
button.addEventListener(`click`,function(){
let dishChoosed=cart.find(dish=>dish.id == this.id);
if (dishChoosed){
dishChoosed.addq();
}else{
dishChoosed=menuAll.find(dish=>dish.id == this.id);
cart.push(dishChoosed);
}
cartUI(cart)
localStorage.setItem('cart',JSON.stringify(cart));
});
}
}
function cartUI(list){
divCart.innerHTML=""
for (const item of list) {
let div= document.createElement(`div`);
div.className="d-flex"
div.innerHTML=` <p class="col-1">${item.q}</p>
<p class="col-2">${item.name}</p>
<p class="col-2">$${item.price}-</p>
<p id="subtotal" class="col-2">${item.price*item.q}</p>`
divCart.append(div);
}
}
if ('cart' in localStorage) {
const cartList=JSON.parse(localStorage.getItem('cart'))
for (const objet of cartList) {
cart.push(new Dish(objet.id,objet.type,objet.name,objet.principal,objet.otherIngredients,objet.price,objet.img,objet.q))
}
cartUI(cart);
}
btnPayConfirm.addEventListener('click', payConfirm);
function payConfirm() {
localStorage.removeItem('cart')
divCart.innerHTML=`<h4 class="text-center m-5">Thanks for your order. It will arrive soon</h4>`
}
Modify your button eventListener code to this.
for (const button of filterButtons) {
button.addEventListener('click',function(){
if(this.id !== "All" ){
const results= menuAll.filter(dish => dish.type == this.id);
menuUI(results);
}
else{
menuUI(menuAll);
}
})
}
Whenever I am writing apple or samsung, It is showing results, but if I don't refresh the page for the second time, it gives me error. However, If I reload the website, then it is showing me the results of samsung or oppo or whatever. Can you please tell me where I made the mistake ? I am attaching the HTML and JS below :
// error handle
const displayHandle = (direction, id) => {
const errorMessage = document.getElementById(id);
errorMessage.style.display = direction;
}
// clear previous result
const clearSearchResult = (direction) => {
const searchResult = document.getElementById(direction);
searchResult.innerHTML = '';
}
// details button action form
const allDetails = (id) => {
// console.log(id)
fetch(`https://openapi.programming-hero.com/api/phone/${id}`)
.then(response => response.json())
.then(data => {
const sensorName = data.data.mainFeatures.sensors;
let storeSensorName = '';
for (const sensor of sensorName) {
storeSensorName = `${storeSensorName} ${sensor}, `
}
const mobileDetails = document.getElementById('show-details');
mobileDetails.innerHTML = `
<div class=" row row-cols-1 row-cols-md-3 g-4">
<div class="col">
<div class="card">
<img src=${data.data.image} class="card-img-top w-50 h-50" alt="...">
<div id="details-body" class="card-body">
<h5 class="card-title">Brand: ${data.data.brand}</h5>
<p class="card-text">Storage: ${data.data.mainFeatures.storage}</p>
<p class="card-text">ChipSet: ${data.data.mainFeatures.chipSet}</p>
<p class="card-text">DisplaySize: ${data.data.mainFeatures.displaySize}</p>
<p class="card-text">Sensors : ${storeSensorName}</p>
</div>
</div>
</div>
</div>
`;
// inject release Date
const container = document.getElementById('details-body');
const p = document.createElement('p');
if (data.data.releaseDate) {
p.innerText = `Release Information:${data.data.releaseDate}`;
container.appendChild(p);
} else {
p.innerText = `Release Information Not Found`;
container.appendChild(p);
}
});
}
//search button action form
document.getElementById('search-btn').addEventListener('click', function() {
clearSearchResult('show-details');
clearSearchResult('show-mobile');
displayHandle('none', 'error-message');
displayHandle('none', 'show-all-Button')
// get search field
const searchBox = document.getElementById('search-box');
const searchData = searchBox.value;
fetch(`https://openapi.programming-hero.com/api/phones?search=${searchData}`)
.then(res => res.json())
.then(data => {
if (data.data.length != 0) {
displayMobile(data.data)
} else {
displayHandle('block', 'error-message');
}
})
// clear search field
searchBox.value = ' ';
})
const displayMobile = (mobiles) => {
// console.log(phones);
const showMobile = document.getElementById('show-mobile');
let count = 0;
for (const mobile of mobiles) {
if (count < 20) {
const div = document.createElement('div');
div.classList.add("col");
div.innerHTML = `
<div class="card d-flex align-items-center">
<img src=${mobile.image} class="card-img-top w-50 h-50" alt="...">
<div class="card-body">
<h5 class="card-title">Model : ${mobile.phone_name}</h5>
<p class="card-text">Brand : ${mobile.brand}</p>
<button class="card-button" onclick="allDetails('${mobile.slug}')">Details</button>
</div>
</div>
`;
showMobile.appendChild(div);
} else {
displayHandle('block', 'show-all-Button');
}
count++;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- connection with bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
.display-handle {
display: none;
color: rgb(231, 49, 49);
}
.card-button {
color: white;
background-color: brown;
border-radius: 10px;
}
</style>
</head>
<body>
<!-- search box section
----------------->
<section class="container w-75 mx-auto pt-5">
<h5 id="error-message" class="display-handle text-center">Not found..! Press authentic data...</h5>
<h3 class="text-center bg-dark text-white">Mobile Maya</h3>
<div class="input-group mb-3">
<input id="search-box" type="text" class="form-control" placeholder="Enter your desired mobile " aria-label="" aria-describedby="button-addon2">
<button class="btn btn-success" type="button" id="search-btn">Search</button>
</div>
</section>
<!-- display products details -->
<section id="show-details" class="container">
<!-- inject details here -->
</section>
<!-- search result display section
---------------------------------->
<section class="container pt-5">
<div id="show-mobile" class=" row row-cols-1 row-cols-md-3 g-4">
</div>
</section>
<!-- show all button -->
<section class="container">
<div class="d-flex justify-content-center">
<button style="color: white; background-color:tomato; border-radius: 8px;" id="show-all-Button" class="display-handle" type="button" class="btn btn-primary">Show All</button>
</div>
</section>
<!-- connection with js
----------- -->
<script src="js/app.js"></script>
<!-- connection with bootstrap script -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
It is because of this line, you don't really clear the search field :
// clear search field
searchBox.value = ' ';
You should either assign the empty string value '' or call the method trim() on searchData.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Please help!
My html body tag appears blank in the browser console while it's not empty. This is happening after I added some javascript tags in the head of my html. It is behaving strange as when I remove all the javascript tags from the head of my html and run my html page in the browser, the javascript code (now removed from the html) appears inside the body tag while it's not even in the entire html. I'm getting frustrated now. Look at my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; 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" type="text/javascript"></script>
<link rel="stylesheet" href="res/styles/w3.css">
<link rel="stylesheet" href="res/fonts/icomoon/style.css">
<link rel="stylesheet" href="res/styles/searchform.css">
<link href="res/styles/easy-autocomplete.min.css" rel="stylesheet" type="text/css">
<link href="res/styles/easy-autocomplete.themes.min.css" rel="stylesheet" type="text/css">
<script src="res/js/jquery.easy-autocomplete.min.js" type="text/javascript" ></script>
<link href="res/styles/floats.css" rel="stylesheet" type="text/css">
<link href="res/styles/main.css" rel="stylesheet" type="text/css">
<script src="res/js/getMedia.js" type="text/javascript"></script>
<script src="res/js/jsQR.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
// hide #back-top first
$("#go-to-top").hide();
// fade in #back-top
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('#go-to-top').fadeIn();
} else {
$('#go-to-top').fadeOut();
}
});
// scroll body to 0px on click
$('#go-to-top').click(function () {
$('#content-base').animate({
scrollTop: 0
}, 800);
return false;
});
});
});
</script>
<script type="text/javascript">
var client;
var camStream;
var QRtarget;
function w3_open() {
document.getElementById("nav-menu").style.width = "100%";
document.getElementById("nav-menu").style.opacity = "0.8";
}
function w3_close() {
document.getElementById("nav-menu").style.width = "0";
document.getElementById("nav-menu").style.opacity = "0";
}
function w3_open_cart() {
document.getElementById("nav-cart").style.width = "100%";
document.getElementById("nav-cart").style.opacity = "0.85";
}
function w3_close_cart() {
document.getElementById("nav-cart").style.width = "0";
document.getElementById("nav-cart").style.opacity = "0";
}
</script>
<script type="text/javascript">
function showDialog(wbtn){
switch(wbtn){
case 1:
$('#div-dialog-cover').fadeIn();
$('#div-dialog-back').slideDown();
trackNum();
dialogCmd = 'tracknum';
break;
case 2:
break;
case 3:
break;
case 4:
$('#div-dialog-cover').fadeIn();
$('#div-dialog-back').slideDown();
genQR();
dialogCmd = 'genqr';
break;
case 5:
$('#div-dialog-cover').fadeIn();
$('#div-dialog-back').slideDown();
scanQR();
dialogCmd = 'scanqr';
break;
case 6:
$('#div-dialog-cover').fadeIn();
$('#div-dialog-back').slideDown();
loginForm();
dialogCmd = 'login';
}
}
function QRfound(QRdata){
setTimeout(function() {
closeDialog(QRdata); // You used `el`, not `element`?
}, 1000);
}
function closeDialog(QRdata = ''){
if (dialogCmd == 'genqr'){
} else if (dialogCmd == 'scanqr') {
$('#scanning').hide();
camStream.getTracks().forEach(track => track.stop());
if (QRdata){
alert(QRdata);
}
readingQR = 0;
$('#canvas').hide();
}
$('#dialog-content').html('');
$('#div-dialog-cover').fadeOut();
$('#div-dialog-back').slideUp();
}
</script>
<script type="text/javascript">
var dialogCmd;
function initVars(){
client = "c";
}
function trackNum(){
document.getElementById('dialog-label').innerHTML = 'Enter tracking number';
$('#div-tracker').css('margin-top', '20px');
$('#dialog-label').css('font-size', '0.8em');
$('#div-dialog-body').css('max-height', '300px');
$('#dialog-content').html('<div id="div-tracker"><form id="form-tracker"><label for="tracking-num">Enter tracking Number:</label><input id="tracking-input" type="text" name="tracking-num" /><br><br><button id="submit-track" onclick="submitTrack()">Track now!</button><br><br><div>OR</div><br><button id="btn-QR-track" onclick="trackQR()">Scan a QR to track</button></form></div>');
}
function scanQR(){
document.getElementById('dialog-label').innerHTML = 'Aim at a QR';
$('#div-dialog-body').css('max-height', '350px');
$('#dialog-content').html('<div id="reader"><div id="scanning"></div><canvas id="canvas" style="width:266px" hidden></canvas></div>');
getCamReady();
}
function genQR(){
$('#dialog-label').css('font-size', '0.7em');
$('#dialog-label').css('padding', '0 2px');
document.getElementById('dialog-label').innerHTML = 'Click to regenerate';
$('#div-dialog-body').css('max-height', '350px');
$('#dialog-content').html('<div id="qrview" onclick="regenQR()"></div>');
if (QRtarget == 1){
$('#qrview').css('background', 'url(<?php require('api/getqr.php?t=1') ?>) no-repeat center center');
} else if (QRtarget == 2){
$('#qrview').css('background', 'url(<?php require('api/getqr.php?t=2') ?>) no-repeat center center');
}
$('#qrview').css('background-size', '100%');
}
function regenQR() {
$('#qrview').css('background', '');
if (QRtarget == 1){
$('#qrview').css('background', 'url(<?php require('api/getqr.php?t=1') ?>) no-repeat center center');
} else if (QRtarget == 2){
$('#qrview').css('background', 'url(<?php require('api/getqr.php?t=2') ?>) no-repeat center center');
}
$('#qrview').css('background-size', '100%');
}
</script>
<script type="text/javascript">
function loginForm(){
document.getElementById('dialog-label').innerHTML = 'Login here';
$('#div-dialog-body').css('max-height', '270px');
$('#dialog-content').html('<div id="form-container"><form id="login-form"><label for="username">Username/Email :</label><br><input id="username" style="width: 220px;margin-left:25px"/><br><br><label for="password">Password :</label><br><input id="password" type="password" style="width: 220px;margin-left:25px;"/><br><br>Not registered? Click to sign up.</form></div><br><div id="btn-login" onclick="submitLogin()">Submit</div>');
}
function submitLogin(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username.length == 0) {
alert('Please enter a username');
return false;
}
if (username.length < 8) {
alert('Username should be at least 8 characters long.');
return false;
}
if (password.length == 0) {
alert('Please enter a password');
return false;
}
if (password.length < 6) {
alert('Password should be at least 6 characters long.');
return false;
}
var usernameType;
if (ValidateEmail(username)){
usernameType = 'email';
} else {
if (ValidatePhone(username)){
usernameType = 'phone';
} else {
if (ValidateUsername(username)){
usernameType = 'username';
} else {
alert('Invalid username! Please enter a valid e-mail address, phone number or username.');
return false;
}
}
}
if (ValidatePassword(password)){
return submit(usernameType, username, password);
} else {
alert('Invalid password! Please enter a valid password. Valid password is minimum 6 characters long and contains alphabets, digits and special characters e.g. \"##$%!?\/*-_.|\"');
return false;
}
}
function submit(usernameType, username, password){
}
function ValidateUsername(username){
return true;
}
function ValidatePassword(password){
return false;
}
function ValidatePhone(phone){
return false;
}
function ValidateEmail(mail) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)){
return true;
}
return false;
}
function trackQR(){
closeDialog();
showDialog(5);
}
function connectQR(target){
QRtarget = target;
w3_close();
showDialog(4);
}
</script>
<title>cart</title>
</head>
<body>
<!-- Sidebar -->
<div class="w3-sidebar w3-bar-block" id="nav-menu" style="z-index:1006;">
<button onclick="w3_close()" class="w3-bar-item w3-button" style="background-color:#430032;font-size:0.9em;">Close ×</button>
My Account
My cart
Track my order
Feedback & Dispute
Invite a Friend
About
Contact
</div>
<!-- -->
<!-- cart -->
<div class="w3-sidebar w3-bar-block" id="nav-cart" style="z-index:1006;">
<button onclick="w3_close_cart()" class="w3-bar-item w3-button" style="background-color:#430032;font-size:0.9em;">Close ×</button>
<div style="width: 100%; height: 5%; background-color:red;font-size:0.7em;padding-left:40px;">My cart</div>
My Account
My cart
Link 3
</div>
<!------------>
<!-- dialog new -->
<div id="div-dialog-cover">
</div>
<div id="div-dialog-back">
<div id="div-dialog-close-back">
<div id="dialog-close-btn">
<span class="icon-cancel-circle" onclick="closeDialog()"></span>
</div>
</div>
<div id="div-dialog-body">
<div id="dialog-label"></div>
<div id="dialog-content" style="text-align:center">
</div>
</div>
</div>
<!------------>
<div id="header" class="header">
<div id="h-top-p">
<div id="h-top-menu" class="button" onclick="w3_open()">
<div class="icons">
<i class="icon-menu"></i>
</div>
</div>
<div id="div-wallet">
<div class="assets-main-div">
<span id="wallet" class="icon-coin-dollar" style="font-size: 1.5em"></span>
<div class="assets-vals-out">
<div class="asset-val-div">
1300
<div class="asset-add-div">
+
</div>
</div>
</div>
</div>
</div>
<div id="div-orders-left">
<div class="assets-main-div">
<span id="price-tag" class="icon-price-tags"></span>
<div class="assets-vals-out">
<div class="asset-val-div">
100
<div class="asset-add-div">
+
</div>
</div>
</div>
</div>
</div>
</div>
<div id="h-middle">
<div id="h-middle-logo">
<img id="main-logo" src="res/imgs/title.png">
</div>
</div>
<div id="h-bottom">
<div id="w-button-container">
<div id="w-button-1" class="w-button" onclick="showDialog(1)">
<div class="w-icons">
<span id="w1" class="icon-target2"></span>
</div>
</div>
<div id="w-button-2" class="w-button">
<div class="w-icons">
<span id="w2" class="icon-document-add"></span>
</div>
</div>
<div id="w-button-3" class="w-button">
<div class="w-icons">
<span id="w3" class="icon-star-full"></span>
</div>
</div>
<div id="w-button-4" class="w-button" onclick="showDialog(4)">
<div class="w-icons">
<span id="w4" class="icon-qrcode"></span>
</div>
</div>
<div id="w-button-5" class="w-button" onclick="showDialog(5)">
<div class="w-icons">
<span id="w5" class="icon-camera"></span>
</div>
</div>
</div>
</div>
</div>
<div id="content-base" class="content-base">
</div>
<div id="footer" class="float-footer">
<div class="footer-part">
<span class="icon-bell"></span>
</div>
<div class="footer-part">
<span class="icon-envelope"></span>
</div>
<div class="footer-part">
<span class="icon-gift"></span>
</div>
</div>
<div id="go-to-top" onclick="scroll2top()">
^
</div>
<a href="#" class="float" id="menu-share">
<i class="icon-chat-bubble-dots"></i>
</a>
<ul>
<li><a href="#">
<i class="icon-phone"></i>
</a></li>
<li><a href="#">
<i class="icon-bubbles3"></i>
</a></li>
</ul>
</body>
</html>
The problem is arising because of JavaScript code between line 123-163. Ensure proper parenthesis and syntax.Hope this helps.
This is the site in question: driglight.com/Learn5.html
The purpose of this site is to click the audio and then choose which image you believe to be the correct representation of the note that was played.
I want to randomize the audio and answers every time the page is refreshed.
When the audio is randomized I need to make sure that the audio that is chosen has it's matching correct answer of an image also chosen and placed randomly among the answers. Also,when any possible answer image is clicked, a div will appear that says 'Good Job!' or 'incorrect'. So when the correct answer is randomized it will need to have the 'Good Job' div to follow it.
Here is the code in html:
<!DOCTYPE html>
<head>
<title>Learn</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/custom-styles.css">
<link rel="stylesheet" href="css/font-awesome.css">
<link rel="stylesheet" href="css/component.css">
<link rel="stylesheet" href="css/font-awesome-ie7.css">
<script src="js/stuff.js"></script>
<!-- <script src="js/Timhasnoinput.js"></script> -->
</head>
<body>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please upgrade your browser or activate Google Chrome Frame to improve your experience.</p>
<![endif]-->
<!-- This code is taken from http://twitter.github.com/bootstrap/examples/hero.html -->
<div class="header-wrapper">
<div class="container">
<div class="row-fluid">
<div class="site-name">
<h1>Music Website</h1>
</div>
</div>
</div>
</div>
<div class="container">
<div class="menu">
<div class="navbar">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<i class="fw-icon-th-list"></i>
</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active">Home</li>
<li>Learn</li>
<li>Contact</li>
</ul>
</div><!--/.nav-collapse -->
</div>
<div class="mini-menu">
<label>
<select class="selectnav">
<option value="#" selected="">Home</option>
<option value="#">→ Hello</option>
<option value="#">→ Something else here</option>
<option value="#">→ Another action</option>
<option value="#">→ Something else here</option>
<option value="#">About</option>
<option value="#">Learn</option>
<option value="#">Contact</option>
</select>
</label>
</div>
</div>
</div>
<div class="container bg-white">
<div class="row-fluid">
<div class="span12 ">
<div class="main-caption">
<h1>Music Website</h1>
<h6>Learning Music</h6>
</div>
<div class="Timmy2">
<h4>< Lesson 2</h4>
<h6></h6>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container bg-white">
<div class="row-fluid">
<div class="span12">
<div class="banner">
<div class="audiobuttonholder">
<div class="audioholder" style="padding-bottom:24px;">
<audio controls id="audio1">
hello
</audio>
</div>
<div class="buttonholder"; style="position: absolute; left: 10px; top: 40px;">
</div>
<div class = "numberPage">
Pg. 3 Trebble Cleff
</div>
<div class = "control">
<ul>
<div id="div1" style="display:none; float: right; margin-right: 120px;
margin-top: 40px;" >
<img id=div1image imageC="incorrect.png" src="incorrect.png"></img>
</div>
<input type="image" id="myimage1" style="height:200px;width:200px;
onclick="showDivOne()" />
</ul>
<ul>
<div id="div2" style="display:none; float: right; margin-right: 120px;" >
<img id=div2image imageC="incorrect.png" src="incorrect.png" />
</div>
<input type="image" id="myimage2" style="height:200px;width:200px; padding-
top:24px;" onclick="showDivTwo()"/>
</ul>
<ul>
<div id="div3" style="display:none; float: right; margin-right: 120px;
padding-top: 40px;" >
<img id=div3image imageC="incorrect.png" src="incorrect.png"></img>
</div>
<input type="image" id="myimage3" style="height:200px;width:200px;padding-
top:24px;" onclick="showDivThree()"/>
</ul>
<ul>
<div id="div4" style="display:none; float: right; margin-right: 120px;
margin-top: 40px;" >
<img id=div4image imageC="incorrect.png" src="incorrect.png"></img>
</div>
<input type="image" id="myimage4" style="height:200px;width:200px;"
onclick="showDivFour()" />
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="featured-images">
<ul class="grid effect-8" id="grid">
<li>
<div class="block">
<div class="Timmy2">
<h4>< Lesson 2</h4>
<h6></h6>
</div>
</div>
</li>
</ul>
<div class="block-content">
<div class="user-info">
<h4>Home</h4>
<h6> </h6>
</div>
<div class="user-info">
<h4>Learn</h4>
<h6> </h6>
</div>
<div class="user-info">
<h4>Contact</h4>
<h6> </h6>
</div>
</div>
</div>
</div>
</div>
<script src="js/jquery-1.9.1.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/masonry.pkgd.min.js"></script>
<script src="js/imagesloaded.js"></script>
<script src="js/classie.js"></script>
<script src="js/AnimOnScroll.js"></script>
<script>
new AnimOnScroll( document.getElementById( 'grid' ), {
minDuration : 0.4,
maxDuration : 0.7,
viewportFactor : 0.2
} );
</script>
<script>
$('#myCarousel').carousel({
interval: 1800
});
</script>
</body>
</html>
And here is the code in Javascript:
function showDivFour() {
document.getElementById('div4').style.display = "block";
}
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
function showDivOne() {
document.getElementById('div1').style.display = "block";
}
function showDivTwo() {
document.getElementById('div2').style.display = "block";
}
function showDivThree() {
document.getElementById('div3').style.display = "block";
}
// THIS SHOULD BE THE BETTER ONE
var correctFileC = $('#div1image').attr("div_answer");
var correctFileC = $('#div2image').attr("div_answer");
var correctFileC = $('#div3image').attr("div_answer");
var correctFileC = $('#div4image').attr("div_answer");
var correctFile1 = $('#myimage1').attr("div_if");
var correctFile2 = $('#myimage2').attr("div_if");
var correctFile3 = $('#myimage3').attr("div_if");
var correctFile4 = $('#myimage4').attr("div_if");
var audio_1 = ["LowATrebbleCleffPianoVC.mp3","LowETrebbleCleffPianoVC.mp3",
"LowGTrebbleCleffPianoVC.mp3","MidBTrebbleCleffPianoVC.mp3",
"MidCTrebbleCleffPianoVC.mp3","MidDTrebbleCleffPianoVC.mp3"];
var rand_audio_1 =
audio_1[Math.floor(Math.random()*audio_1.length)].getElementByName.
(audioholder.innerHTML(rand_audio_1);
function div_if(){
if(audio_1[0]){
var R1 = ["myimage1","TrebbleCleffLowA.gif"],["myimage2","TrebbleCleffLowA.gif"],["myimage3","TrebbleCleffLowA.gif"],["myimage4","TrebbleCleffLowA.gif"];
if[R1(var i=0; i<R1.length;i++).length=4];
} else if(audio_1[1]){
var R2 = ["myimage1","LowE.gif"],["myimage2","LowE.gif"],["myimage3","LowE.gif"],["myimage4","LowE.gif"];
if[R2(var i=0; i<R2.length;i++).length=4];
do nothing
} else if(audio_1[2]){
var R3 = ["myimage1","LowG.gif"],["myimage2","LowG.gif"],["myimage3","LowG.gif"],["myimage4","LowG.gif"];
if[R3(var i=0; i<R3.length;i++).length=4];
do nothing
} else if(audio_1[3]){
var R4 = ["myimage1","MidB.gif"],["myimage2","MidB.gif"],["myimage3","MidB.gif"],["myimage4","MidB.gif"];
if[R4(var i=0; i<R4.length;i++).length=4];
do nothing
} else if(audio_1[4]){
var R5 = ["myimage1","MidC.gif"],["myimage2","MidC.gif"],["myimage3","MidC.gif"],["myimage4","MidC.gif"];
if[R5(var i=0; i<R5.length;i++).length=4];
do nothing
{ else if(audio_1[5]){
var R6 = ["myimage1","MidD.gif"],["myimage2","MidD.gif"],["myimage3","MidD.gif"],["myimage4","MidD.gif"];
if[R6(var i=0; i<R6.length;i++).length=4];
do nothing
} else if{
L1.Push(R);
} else if{
L1.Push(R1)
} else if{
L1.Push(R2)
} else if{
L1.Push(R3)
} else if{
L1.Push(R4)
}
function div_answer(){
if(R[0]){
document.getElementById(div1).innerHTML(divC);
divC.src='GoodJob.png'{
else if(R[1]){
document.getElementById(div2).innerHTML(divC);
divC.src='GoodJob.png'
}
else if(R[2]){
document.getElementById(div3).innerHTML(divC);
divC.src='GoodJob.png'
}
else {
document.getElementById(div4).innerHTML(divC);
divC.src='GoodJob.png'
}
}
}
I assume every audio fragment will have an image? So with that in mind, you create a random index to select an audio fragment (which you already do). Why don't you store that index in a variable and associate the image fragment with it?
Another option would be to create an object. So you make your array with audiofragments and then you initialize a new JS object, and assign the names of the images to 'properties' with your audiofragment as key. Like this:
var images = {};
images[audioname] = image-name;
***Do this for each audiofragment of course***
That way you can just ask the image from your images-object, using the property audioname.
When the page renders, place some value inside the attributes for the images or div:
<img id=myimage data-audio-file="xyz123.mp3" src="...." />
<div data-audio-file="xyz123.mp3" src="...." >My Content</div>
Read the attribute out when it's time to take some action:
var correctFile = $('#myimage').attr("data-audio-file");