so i'm currently trying to build search icon on the header clickable where you're able to search for, in this case, pokemon names, however i keep getting a console error
searchQuery.value undefined
Not sure why because the code looks valid.
Also, when you click on the search icon the icon goes above it and once you hit submit on the input it duplicates. I'm sure it's all connected the bug.
No sure why this is happening and would greatly appreciate any advice to fix this.
let pokemonRepository = (function() {
let pokemonList = [];
// API
let apiUrl = "https://pokeapi.co/api/v2/pokemon/?limit=150";
let searchIcon = $(".btn-outline-secondary");
let modalContainer = $(".modal");
let modalDialog = $(".modal-dialog");
let modalContent = $(".modal-content");
let modalBody = $(".modal-body");
let modalTitle = $(".modal-title");
let modalHeader = $(".modal-header");
let modalClose = $(".btn-close");
let listItemArray = $("li");
function add(pokemon) {
if (
typeof pokemon === "object" &&
"name" in pokemon &&
"detailsUrl" in pokemon
) {
pokemonList.push(pokemon);
} else {
console.error("pokemon is not correct");
}
}
function getAll() {
return pokemonList;
}
// filters through pokemon names
function search(pokemonName) {
return pokemonList.filter((pokemon) => pokemon.name === pokemonName);
}
// Function adds a list of pokemon
function addListItem(pokemon) {
let pokemonDisplay = $(".list-group-horizontal");
// Creates li element
let listItem = $("<li>");
listItem.addClass(
"list-group-item text-center col-sm-6 col-md-4 border border-secondary bg-image img-fluid"
);
// Creates h1 for Pokemon Name
let listTitle = $("<h1>");
listTitle.html(`${pokemon.name}`);
listTitle.addClass("display-6");
// Creates div which holds sprites
let listImg = $("<div>");
loadDetails(pokemon).then(function() {
listImg.append(
`<img src=${pokemon.imageUrlFront} alt="${pokemon.name} sprite"/>`
);
});
let listButton = $("<button>");
listButton.text("show More");
// Added Bootstrap Utility Class
listButton.addClass("mp-2 btn btn-secondary");
listButton.attr("type", "button");
listButton.attr("data-bs-toggle", "modal");
listButton.attr("data-bs-toggle", "#pokemonModal");
listItem.append(listTitle);
listItem.append(listImg);
listItem.append(listButton);
pokemonDisplay.append(listItem);
buttonEvent(listButton, pokemon);
}
function buttonEvent(listButton, pokemon) {
listButton.on("click", () => {
showDetails(pokemon);
});
}
function showDetails(pokemon) {
loadDetails(pokemon).then(() => {
// Clears existing content
modalContainer.empty();
modalTitle.addClass("modal-title h5 col-sml-3");
let pokemonType = {
fire: "text-danger",
grass: "text-success",
water: "text-primary",
electric: "text-warning",
flying: "text-info",
poison: "text-secondary",
};
pokemon.types.forEach((type) =>
modalTitle.addClass(pokemonType[type.type.name])
);
modalTitle.html(`${pokemon.name}`);
modalBody.html(`
Entry: ${pokemon.id}<br>
Height: ${pokemon.height}<br>
Weight: ${pokemon.weight}<br>
Types: ${pokemon.types[0].type.name}`);
if (pokemon.types.length === 2) {
modalBody.innerHTML += `, ${pokemon.types[1].type.name}`;
}
modalBody.innerHTML += `<br>Abilities: ${pokemon.abilities[0]}.ability.name}`;
if (pokemon.abilities.length === 2) {
modalBody.innerHTML += `, ${pokemon.abilities[1]}.ability.name}`;
}
modalBody.append(`<br>
<img src=${pokemon.imageUrlFront} alt="${pokemon.name} front sprite">
<img src=${pokemon.imageUrlBack} alt="${pokemon.name} back sprite">
<br>
`);
modalDialog.append(modalContent);
modalContent.append(modalHeader);
modalHeader.append(modalTitle);
modalHeader.append(modalClose);
modalContent.append(modalBody);
modalContainer.append(modalDialog);
});
modalContainer.modal("show");
}
modalContainer.on("shown.bs.modal", () => {
// Jquery eventlistener
modalClose.on("click", () => {
modalContainer.removeClass("fade");
modalContainer.modal("hide");
listItemArray[0].children().click();
});
});
searchIcon.on("click", () => {
// fetching .d-flex class in form
let bodyHeader = $(".d-flex");
// returns the number of child elements
if (bodyHeader.length === 1) {
//creates input element
let searchQuery = $("<input>");
searchQuery.attr("placeholder", "Pokemon Name");
searchQuery.attr("type", "search");
searchQuery.attr("aria-label", "search Pokemon Name");
searchQuery.addClass("form-control my-3 ps-2 col-sm");
searchIcon.blur();
searchQuery.focus();
bodyHeader.append(searchQuery);
searchQuery.on("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
searchQuery.value =
searchQuery.value.charAt(0).toUpperCase() +
searchQuery.value.slice(1);
for (let i = 0; i < listItemArray.length; i++) {
if (
902 >
listItemArray[i].children().last().getBoundingClientRect()[
"top"
] &&
listItemArray[i].children().last().getBoundingClientRect()[
"top"
] > 42
) {
listItemArray[i].children().last().click();
}
}
for (let i = 0; i < listItemArray.length; i++) {
if (listItemArray[i].text().split("\n")[0] === searchQuery.value) {
setTimeout(function() {
listItemArray[i].children().last().click();
}, 5);
}
}
}
});
}
});
// Fetches data from API
function loadList() {
return fetch(apiUrl)
.then(function(response) {
return response.json();
})
.then(function(json) {
json.results.forEach((item) => {
let pokemon = {
name: item.name.charAt(0).toUpperCase() + item.name.slice(1),
detailsUrl: item.url,
};
add(pokemon);
});
})
.catch(function(error) {
console.error(error);
});
}
function loadDetails(item) {
let url = item.detailsUrl;
return fetch(url)
.then(function(response) {
return response.json();
})
.then(function(details) {
item.imageUrlFront = details.sprites.front_default;
item.imageUrlBack = details.sprites.back_default;
item.id = details.id;
item.height = details.height;
item.weight = details.weight;
item.types = details.types;
item.abilities = details.abilities;
})
.catch(function(error) {
console.error(error);
});
}
return {
add: add,
getAll: getAll,
addListItem: addListItem,
search: search,
showDetails: showDetails,
loadList: loadList,
loadDetails: loadDetails,
buttonEvent: buttonEvent,
};
})();
pokemonRepository.loadList().then(function() {
pokemonRepository.getAll().forEach(function(pokemon) {
pokemonRepository.addListItem(pokemon);
});
});
<!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" />
<meta name="description" content="The Pokédex is a simple encyclopedia of Pokémon and their characteristics." />
<link rel="shortcut icon" href="img/favicon.png" type="image/x-icon" />
<title>Pokédex App</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.8.3/font/bootstrap-icons.css" />
<link rel="stylesheet" href="/dist/style.production.css" />
</head>
<body>
<nav class="navbar navbar-expand-lg sticky-top navbar-light bg-light">
<div class="container-fluid">
<a href="#home" class="navbar-brand">
<img src="img/ball.png" width="30" height="24" alt="" class="d-inline-block align-text-top" /><span class="text-uppercase font-weight-bold text-secondary">Pokèdex</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#home">Home</a
>
</li>
<li class="nav-item">
<a class="nav-link" href="#about">About</a>
</li>
</ul>
</li>
</ul>
<form class="d-flex row" role="search">
<!-- <input
class="form-control me-2"
placeholder="Pokemon Name"
aria-label="Search"
/> -->
<button class="btn btn-outline-secondary" type="submit">
<i class="bi bi-search"></i>
</button>
</form>
</div>
</div>
</nav>
<p class="fw-bold position-absolute top-10 start-50 text-center text-danger"></p>
<!-- Pokemon Display -->
<div class="container">
<ul class="list-group list-group-horizontal flex-fill row mt-4"></ul>
</div>
<!-- Display Ends Here -->
<div class="modal fade" id="pokemonModal" tabindex="-1" role="dialog" aria-labelledby="pokemonModalLabel" aria-hidden="true">
<div class="modal-dialog pt-5 text-center" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title col-sm-3" id="pokemonModalLabel"></h5>
<button type="button" class="btn-close me-3" data-dismiss="modal" aria-label="Close" aria-hidden="true"></button>
</div>
<!-- Content is dynamically created using jquery -->
<div class="modal-body"></div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.11.5/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script>
<script src="/src/js/scripts.js"></script>
<script src="/src/js/promise-polyfill.js"></script>
<script src="/src/js/fetch-pollyfill.js"></script>
</body>
</html>
Since searchQuery is a jQuery object, you need to use its .val() method to set and get the value. So change.
searchQuery.value =
searchQuery.value.charAt(0).toUpperCase() +
searchQuery.value.slice(1);
to
searchQuery.val((i, value) => value[0].toUpperCase() + value.slice(1));
function httpGet(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false); // false for synchronous request
xmlHttp.send(null);
return xmlHttp.responseText;
}
var videosT = httpGet("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=abcxyz&maxResults=6&order=date&type=video&key=abcxyz");
const videos = JSON.parse(videosT);
for (let step = 0; step < 6; step++) {
fetch('js/videos.html')
.then(res => res.text())
.then(text => {
let oldelem = document.getElementById("vid_" + step);
let newelem = document.createElement("div");
newelem.innerHTML = text;
oldelem.parentNode.replaceChild(newelem, oldelem);
})
}
html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ashk3000</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body class="d-flex flex-column" viewport-fit=cover>
<!-- Navbar -->
<script id="navbar_placeholder" src="js/nav.js" page="home"></script>
<!-- Headers -->
<div
class="d-none d-lg-block shadow bg-body border border-5 border-top-0 rounded-bottom w-75 position-relative start-50 translate-middle-x mb-5">
<div class="container-fluid py-5">
<h1 class="display-5 fw-bold">Home</h1>
</div>
</div>
<div class="d-lg-none shadow-sm bg-body border-bottom border-5 w-100 position-relative mb-3">
<div class="container-fluid py-5">
<h1 class="display-5 fw-bold">Home</h1>
</div>
</div>
<!-- Start -->
<div class="container">
<div class="row">
<div id="vid_0"></div>
<div id="vid_1"></div>
<div id="vid_2"></div>
<div class="w-100"></div>
<div id="vid_3"></div>
<div id="vid_4"></div>
<div id="vid_5"></div>
</div>
</div>
<script src="js/videos.js"></script>
<!-- Footer -->
<div class="mt-auto"></div>
<script id="footer_placeholder" src="js/footer.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa"
crossorigin="anonymous"></script>
</body>
</html>
videos.html:
<div class="card col" style="width: 18rem;">
<img src="" id="thumbnail" class="card-img-top" alt="">
<div class="card-body">
<h5 id="title" class="card-title">Title</h5>
Watch
</div>
</div>
Hello, I am getting the replit "Not Found" screen when I try this code. I think it has to do with replaceChild. I am new to java script and dont know what it happening. A lot of it is from the internet. I am trying to make it show recent youtube uploads. It wants me to add more text. sorry this is rushed.
When you replace the element, you need to give it the ID of the element that it's replacing, so you will be able to find it the next time.
for (let step = 0; step < 6; step++) {
fetch('js/videos.html')
.then(res => res.text())
.then(text => {
let oldelem = document.getElementById("vid_" + step);
let newelem = document.createElement("div");
newelem.id = oldelem.id; // copy the ID.
newelem.innerHTML = text;
oldelem.parentNode.replaceChild(newelem, oldelem);
var pic = document.getElementById('thumbnail');
pic.classList.add('thumbnail_' + step);
pic.id = "thumbnail_" + step;
pic.setAttribute('src', videos.items[step].snippet.thumbnails.high.url);
})
}
Or instead of replacing the element, you could just update the innerHTML of the old element.
for (let step = 0; step < 6; step++) {
fetch('js/videos.html')
.then(res => res.text())
.then(text => {
let oldelem = document.getElementById("vid_" + step);
oldelem.innerHTML = text;
var pic = document.getElementById('thumbnail');
pic.classList.add('thumbnail_' + step);
pic.id = "thumbnail_" + step;
pic.setAttribute('src', videos.items[step].snippet.thumbnails.high.url);
})
}
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);
}
})
}
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.....
I'm trying to make a movie searching site using TMDb and axios npm. What am I doing wrong?
Search works fine, but I can't access the movies themselves.
$(document).ready(() => {
$('#searchForm').on('submit', (e) => {
let searchText = $('#searchText').val();
getMovies(searchText);
e.preventDefault();
});
});
function getMovies(searchText) {
axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
.then((response) => {
console.log(response);
let movies = response.data.Search;
let output = '';
$.each(movies, (index, movie) => {
output += `
<div class="col-md-3">
<div class="well text-center">
<img src="${movie.poster_path}">
<h5>${movie.original_title}</h5>
<a onclick="https://www.themoviedb.org/movie/('${movie.id}')" class="btn btn-primary" href="#">Movie Details</a>
</div>
</div>
`;
});
$('#movies').html(output);
})
.catch((err) => {
console.log(err);
});
}
function movieSelected(id) {
sessionStorage.setItem('id', id);
window.location = 'movie.html';
return false;
}
function getMovie() {
let id = sessionStorage.getItem('id');
axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
.then((response) => {
console.log(response);
let movie = response.data;
let output = `
<div class="row">
<div class="col-md-4">
<img src="${movie.Poster}" class="thumbnail">
</div>
<div class="col-md-8">
<h2>${movie.Title}</h2>
<ul class="list-group">
<li class="list-group-item"><strong>Genre:</strong> ${movie.genres.Name}</li>
<li class="list-group-item"><strong>Released:</strong> ${movie.release_date}</li>
<li class="list-group-item"><strong>Rated:</strong> ${movie.vote_average}</li>
<li class="list-group-item"><strong>Review:</strong> ${movie.overview}</li>
</ul>
</div>
</div>
<div class="row">
<div class="well">
<h3>Plot</h3>
${movie.Plot}
<hr>
View TMDb
Go Back To Search
</div>
</div>
`;
$('#movie').html(output);
})
.catch((err) => {
console.log(err);
});
}
#movies img,
#movie img {
width: 100%;
}
#media(min-width:960px) {
#movies .col-md-3 .well {
height: 390px;
}
#movies .col-md-3 img {
height: 240px;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MovieInfo</title>
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">MovieInfo</a>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h3 class="text-center">Search For Any Movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
</form>
</div>
</div>
<div class="container">
<div id="movies" class="row"></div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
--More details, because I have more code:
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
This will help you click here, Now it is working. There was very small bug, which I mentioned to you.
And also fixed the image not showing issue.
Just replace response.data.Search by response.data.results
$(document).ready(() => {
$('#searchForm').on('submit', (e) => {
let searchText = $('#searchText').val();
getMovies(searchText);
e.preventDefault();
});
});
function getMovies(searchText) {
axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
.then((response) => {
console.log(response);
let movies = response.data.results;
let output = '';
$.each(movies, (index, movie) => {
output += `
<div class="col-md-3">
<div class="well text-center">
<img src="${movie.poster_path}">
<h5>${movie.original_title}</h5>
<a onclick="https://www.themoviedb.org/movie/('${movie.id}')" class="btn btn-primary" href="#">Movie Details</a>
</div>
</div>
`;
});
$('#movies').html(output);
})
.catch((err) => {
console.log(err);
});
}
function movieSelected(id) {
sessionStorage.setItem('id', id);
window.location = 'movie.html';
return false;
}
function getMovie() {
let id = sessionStorage.getItem('id');
axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
.then((response) => {
console.log(response);
let movie = response.data;
let output = `
<div class="row">
<div class="col-md-4">
<img src="${movie.Poster}" class="thumbnail">
</div>
<div class="col-md-8">
<h2>${movie.Title}</h2>
<ul class="list-group">
<li class="list-group-item"><strong>Genre:</strong> ${movie.genres.Name}</li>
<li class="list-group-item"><strong>Released:</strong> ${movie.release_date}</li>
<li class="list-group-item"><strong>Rated:</strong> ${movie.vote_average}</li>
<li class="list-group-item"><strong>Review:</strong> ${movie.overview}</li>
</ul>
</div>
</div>
<div class="row">
<div class="well">
<h3>Plot</h3>
${movie.Plot}
<hr>
View TMDb
Go Back To Search
</div>
</div>
`;
$('#movie').html(output);
})
.catch((err) => {
console.log(err);
});
}
#movies img,
#movie img {
width: 100%;
}
#media(min-width:960px) {
#movies .col-md-3 .well {
height: 390px;
}
#movies .col-md-3 img {
height: 240px;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MovieInfo</title>
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">MovieInfo</a>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h3 class="text-center">Search For Any Movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
</form>
</div>
</div>
<div class="container">
<div id="movies" class="row"></div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>