Reputation: 339
Beginner In js. I am creating a pokedex using pokeapi and want to change the background of pokecards using the colors according to their type stored in an object by using the .style in js
Currently I have written this code
const typecolor = {
bug: "#26de81",
dragon: "#ffeaa7",
electric: "#fed330",
fairy: "#FF0069",
fighting: "#30336b",
fire: "#f0932b",
flying: "#81ecec",
grass: "#00b894",
ground: "#EFB549",
ghost: "#a55eea",
ice: "#74b9ff",
normal: "#95afc0",
poison: "#6c5ce7",
psychic: "#a29bfe",
rock: "#2d3436",
water: "#0190FF",
};
const abilities = document.querySelector(".power1 p");//ptag inside pokecard
function generatehtml(result) {
const card = document.createElement("div");
card.classList.add("pokecard");
let newhtml = `
<div class=pokecard>
.
.
.
</div>`
themecolor = typecolor[result.types[0].type.name]; //getting poketype from api
card.style.background = `radial-gradient(circle at 50% 0%, ${themecolor} 36%, #ffffff 36%)`;
abilities.style.backgroundColor = `${themecolor}`;//a <p> tag to be colored
}
Though the themecolor gets console logged out but there is no visible change working version:https://megahedron69.github.io/Pokedex/ js file:https://github.com/Megahedron69/Pokedex/blob/main/app.js
Upvotes: 1
Views: 87
Reputation: 606
First thing you creating card element but not appending to dom.
secondly, you are trying to get element const abilities = document.querySelector(".power1 p");
which doesn't exist in DOM.
why not add styles to HTML itself while you are creating card DOM.
optimized code
function generatehtml(result, appendToList) {
const themecolor = typecolor[result.types[0].type.name];
const name = result.name[0].toUpperCase() + result.name.slice(1);
const newhtml = `
<div class=pokecard style="background: radial-gradient(circle at 50% 0%, ${themecolor} 36%, #ffffff 36%)">
.
.
.
<div class="power1">
<p style="background: ${themecolor}">
${result.types[0].type.name}
<img src="Grass.png" />
</p>
</div>
.
.
.
</div>
`;
if (appendToList)
searchcont.innerHTML += newhtml;
else
searchcont.innerHTML = newhtml;
}
Upvotes: 1