I got 2 radio buttons and each one have a function (change the weather from celsius to fahrenheit)
The wearher data is from an API.
<p>
<label>
Celsius
<input
type="radio"
name="weather"
value="celsius"
class="celsius"
onclick="weatherC()"
/>
</label>
</p>
<p>
<label>
Fahrenheit
<input
type="radio"
name="weather"
value="fahrenheit"
class="fahrenheit"
onclick="weatherF()"
/>
</label>
</p>
Those are the functions in JavaScript:
function weatherC() {
fetch("http://api.openweathermap.org/data/2.5/weather?q=Azuga&units=metric&appid=cbf24ef0d0428af6ca69c8320756cbf5")
.then(handleResponse)
.then((data) => {
const maxTemp = document.querySelector(".max-temp");
maxTemp.innerText = Math.ceil(data.main["temp_max"]) + "\u2103";
const minTemp = document.querySelector(".min-temp");
minTemp.innerText = Math.ceil(data.main["temp_min"]) + "\u2103";
const currentTemp = document.querySelector(".current-temp");
currentTemp.innerText = Math.ceil(data.main["temp"]) + "\u2103";
const feelsLike = document.querySelector(".feels-like");
feelsLike.innerText = Math.ceil(data.main["feels_like"]) + "\u2103";
const city = document.querySelector(".city");
city.innerText = data["name"];
const statusIcon = document.querySelector(".iconClass");
const iconFromApi = data.weather[0].icon;
const icon = `http://openweathermap.org/img/wn/${iconFromApi}#2x.png`;
statusIcon.innerHTML = `<img src="${icon}">`;
});
}
function weatherF() {
fetch("http://api.openweathermap.org/data/2.5/weather?q=Azuga&units=fehrenheit&appid=cbf24ef0d0428af6ca69c8320756cbf5")
.then(handleResponse)
.then((data) => {
const maxTemp = document.querySelector(".max-temp");
maxTemp.innerText = Math.ceil(data.main["temp_max"]) + "\u2109";
const minTemp = document.querySelector(".min-temp");
minTemp.innerText = Math.ceil(data.main["temp_min"]) + "\u2109";
const currentTemp = document.querySelector(".current-temp");
currentTemp.innerText = Math.ceil(data.main["temp"]) + "\u2109";
const feelsLike = document.querySelector(".feels-like");
feelsLike.innerText = Math.ceil(data.main["feels_like"]) + "\u2109";
const city = document.querySelector(".city");
city.innerText = data["name"];
const statusIcon = document.querySelector(".iconClass");
const iconFromApi = data.weather[0].icon;
const icon = `http://openweathermap.org/img/wn/${iconFromApi}#2x.png`;
statusIcon.innerHTML = `<img src="${icon}">`;
});
}
weatherC();
how can i make it that when i refresh the page the selected radio button to remain the same?(I m new to js so an example would be awesome :D)
In the weatherF and the weatherC functions you need to put in a localStorage.setItem call
And then in the page load you need to do a check if localStorage.getItem() return null
If local storage is new to you set up a few small apps where you test out the locaStorage.setItem(key, value) and localStorage.getItem(key)
If you set up the localStorage functions and you can’t get it to work post again and can take a look at it. You really should do a bit more of the code though before positing.
Related
I know local storage is not a secure solution for this, but for now, I am doing it this way for practice.
I think I am on the right track here, I want my created list for the budget app to store, this method seems to store the first created list.
/*----Store Stored budget list----*/
function storedEntry(){
const saveData = makeNewBudget();
const myJSON = JSON.stringify(saveData);
window.localStorage.setItem(STORAGE_KEY, myJSON);
}
I think what needs to happen is get that same method to work for the array.
let budgetArray = [];
I tried this method, but gives a JSON error, sop for some reason it's not converted to JSON
let budgetArray = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? "[]");
End result should be set local storage for array in its own function and get the stored information when checking the array.
I put the entire JS code so you can see what is going on
/*----Generate ID----*/
const createId = () =>`${Math.floor(Math.random() * 10000)}$(new Date().getTime())}`;
/*----Get current Date----*/
function createdDate() {
let currentDate = new Date();
let day = String(currentDate.getDate()).padStart(2, '0');
let month = String(currentDate.getMonth() + 1).padStart(2, '0');
let year = currentDate.getFullYear();
currentDate = month + '/' + day + '/' + year;
console.log(currentDate)
return currentDate;
}
/*----Variable Objects----*/
const el = {
list: document.querySelector(".list"),
cashflow: document.querySelector("#cashflow"),
catagory: document.querySelector(".catagory"),
label: document.querySelector(".label"),
number: document.querySelector(".number"),
};
/*----Array with local Storage----*/
let budgetArray = [];
/*----Budget list Object----*/
function makeNewBudget(){
const data = {
id: createId(),
cashflowNew: el.cashflow.value,
catagoryNew: el.catagory.value,
labelNew: el.label.value,
dateNew: createdDate(),
numberNew: el.number.value,
};
return data;
}
/*----Render Budget List----*/
function renderList(){
el.list.innerHTML = budgetArray.map(function (data,i) {
return `<div class="entry">
<div class="list">
<button onclick="deleteItem(event, ${i})" class="Archive" data-id="${data.id}">
<img src="../resources/Images/archive.png" alt="Archive">
</button>
<button onclick="editItem(event, ${i})" class = "edit" data-id="${data.id}" class = "edit" data-id="${data.id}">
<img src="../resources/Images/edit.png" alt="Edit">
</button>
<div class="input" data-id="${data.id}"></div>
<label class="dateNew">${data.dateNew}</label>
<label class="cashflowNew">${data.cashflowNew}</label>
<label class="catagoryNew">${data.catagoryNew}</label>
<label class="labelNew">${data.labelNew}</label>
<label class="numberNew">${data.numberNew}</label>
</div>
</div>
<label class="total"></label>`;
});
}
/*----form validation----*/
let budgetButton = document.querySelector(".budget-button");
let label = document.querySelector(".label");
let num = document.querySelector(".number");
let entry = document.querySelector(".entry")
budgetButton.addEventListener("click", () => {
if (!label.value || !num.value) {
alert("please make sure all inputs are filled");
}
budgetArray.push(makeNewBudget())
renderList();
storedEntry();
});
/*----Archive list----*/
function deleteItem(event, i){
}
/*----Store Stored budget list----*/
function storedEntry(){
const saveData = makeNewBudget();
const myJSON = JSON.stringify(saveData);
window.localStorage.setItem(STORAGE_KEY, myJSON);
}
I was working on a code where I fetch and display data from an API. I used to store it in Localstorage of browser's port.But now I wish to connect it to mongoDB.
When I import mongoclient my HTML elements become unused and their reference points nowhere.
This is the Script.js file
const searchInput = document.getElementById('searchInput')
const searchBtn = document.getElementById('searchBtn')
const moviesList = document.getElementById('moviesList')
const watchlist = document.getElementById('watchlist')
const removeWatchlistBtn = document.getElementsByClassName('remove-watchlist-btn')
const cardWatchlistBtn = document.getElementsByClassName('watchlist-btn')
const readMore = document.getElementsByClassName('read-more')
const readMorePlot = document.getElementsByClassName('read-more-plot')
const movieKey = document.getElementsByClassName('movie-key')
const localStorageKeys = Object.keys(localStorage)
if (searchBtn) {
searchBtn.addEventListener('click', searchMovies)
}
async function searchMovies() {
// Hide default elements
if (moviesList.children) {
let children = moviesList.children
let childrenArr = Array.prototype.slice.call(children)
childrenArr.forEach((child) => child.remove())
}
let res = await fetch(`https://www.omdbapi.com/?s=${searchInput.value.trim()}&apikey=e668e570`)
let data = await res.json()
const movies = data.Search
// Get and display search results
movies.forEach(async (movie) => {
let response = await fetch(`https://www.omdbapi.com/?i=${movie.imdbID}&apikey=e668e570`)
let moviesListData = await response.json()
console.log(moviesListData)
const readMoreMovieID = moviesListData.imdbID + 'more'
const hideReadMore = moviesListData.imdbID + 'hide'
const summaryPlot = `${moviesListData.Plot.substring(0, 110)}<span id=${hideReadMore}>...<button class="black read-more" onclick="showCompletePlot(${readMoreMovieID}, ${hideReadMore})">Read more</button></span>`
const readMorePlot = `<span class="read-more-plot" id=${readMoreMovieID} >${moviesListData.Plot.substring(110, moviesListData.Plot.length)}</span>`
const completePlot = moviesListData.Plot
const longPlot = summaryPlot + readMorePlot
const movieID = moviesListData.imdbID
const movieIDkey = moviesListData.imdbID + 'key'
const watchlistBtnKey = moviesListData.imdbID + 'watchlistBtn'
const removeBtnKey = moviesListData.imdbID + 'removeBtn'
moviesList.innerHTML += `
<div class="cards">
<div class="card" id=${movieID}>
<span id=${movieIDkey} class="hide movie-key">${movieIDkey}</span>
<img src=${moviesListData.Poster} class="card-poster" />
<div class="card-header">
<h2 class="card-title">${moviesListData.Title}</h2>
<img src="images/star-icon.svg" class="star-icon" />
<span class="card-rating">${moviesListData.imdbRating}</span>
</div>
<div class="card-meta">
<span class="card-runtime">${moviesListData.Runtime}</span>
<span>${moviesListData.Genre}</span>
<button class="card-btn card-watchlist watchlist-btn" id="${watchlistBtnKey}" onclick="addToWatchlist(${movieIDkey}, ${movieID}, ${watchlistBtnKey}, ${removeBtnKey})"><img src="images/watchlist-icon.svg" alt="Add film to watchlist" class="card-watchlist-plus-icon" /> Watchlist</button>
<button class="card-btn card-watchlist remove-watchlist-btn" id="${removeBtnKey}" onclick="removeFromWatchlist(${movieIDkey}, ${removeBtnKey}, ${watchlistBtnKey}, ${removeBtnKey})"><img src="images/remove-icon.svg" alt="Remove film to watchlist" class="card-watchlist-plus-icon" /> Remove</button>
</div>
<p class="card-plot">${completePlot.length < 110 ? completePlot : longPlot}</p>
</div>
</div>
`
displayWatchlistOrRemoveBtn()
})
}
function displayWatchlistOrRemoveBtn() {
for (let movie of movieKey) {
const removeBtnID = movie.id.slice(0, 9) + 'removeBtn'
const removeBtn = document.getElementById(removeBtnID)
const watchlistBtnID = movie.id.slice(0, 9) + 'watchlistBtn'
const watchlistBtn = document.getElementById(watchlistBtnID)
localStorageKeys.forEach((key) => {
if (movie.id === key) {
removeBtn.style.display = 'inline'
watchlistBtn.style.display = 'none'
}
})
}
}
function showCompletePlot(readMoreMovieID, hideReadMore) {
readMoreMovieID.style.display = 'inline'
hideReadMore.style.display = 'none'
}
async function addToWatchlist(movieIDkey, movieID, watchlistBtnKey, removeBtnKey) {
console.log(movieID.id)
const a = movieID.id
const b= movieID.Title
let sanket = await fetch(`https://www.omdbapi.com/?i=${movieID.id}&apikey=e668e570`)
const ab = await sanket.json()
console.log(ab)
localStorage.setItem(movieIDkey.innerHTML, movieID.innerHTML)
watchlistBtnKey.style.display = 'none'
removeBtnKey.style.display = 'inline'
}
function removeFromWatchlist(movieIDkey, watchlistBtnKey, removeBtnKey) {
localStorage.removeItem(movieIDkey.innerHTML)
// Get parent element (the movie card div) and remove it
if (watchlist) {
localStorage.removeItem(movieIDkey.innerHTML)
const parentEl = document.getElementById(movieIDkey.innerHTML).parentElement
parentEl.remove()
}
watchlistBtnKey.style.display = 'inline'
removeBtnKey.style.display = 'none'
// Display default elements if local storage empty
if (watchlist && localStorage.length === 0) {
if (watchlist.children) {
const children = watchlist.children
const childrenArr = Array.prototype.slice.call(children)
childrenArr.forEach((child) => (child.style.display = 'flex'))
}
}
}
// Hide default elements if data is in local storage
if (watchlist && localStorage.length > 0) {
if (watchlist.children) {
const children = watchlist.children
const childrenArr = Array.prototype.slice.call(children)
childrenArr.forEach((child) => (child.style.display = 'none'))
}
}
for (let i = 0; i < localStorage.length; i++) {
const getLocalStorage = localStorage.getItem(localStorage.key(i))
// Display every key's value to the watchlist
if (watchlist) {
watchlist.innerHTML += `<div class="card">${getLocalStorage}</div>`
// Hide the 'add to watchlist' button
for (let button of cardWatchlistBtn) {
button.style.display = 'none'
}
// Display the 'remove from watchlist' button
for (let button of removeWatchlistBtn) {
button.style.display = 'inline'
}
}
}
Here when I use const { MongoClient } = require("mongodb"); the elements readMore and readMorePlot (Line no.7 and 8) become unused.
I tried exporting my addToWatchlist function but problem persists.
I also have tried adding Type=Module in html file but that doesn't work.
I'm trying to access and delete the child in a div generated when I press the "submit" button, the individual divs inside will be generated because there are some functions running with the click, but when I press refresh to delete them nothing happened.
For more clarification here's the src: https://github.com/espnal/wdd230-final-project/blob/main/javascript/js.js
(This is my first post here if you have any suggestions I'm open)
const refresh = document.querySelector("#refresh");
const form = document.querySelector("#form-1");
const contentDiv = document.querySelector(".contentdiv");
const input = document.querySelector("#form-1 input");
//There're another two function like this one below
function firstItemF(list, city) {
let firstItem = list[0]
let dayweather = "Sunday"
const icon = `https://openweathermap.org/img/wn/${firstItem.weather[0]["icon"]}#2x.png`;
let individualDiv = document.createElement("Div")
individualDiv.className = "individual"
let description = document.createElement("p")
description.innerHTML = firstItem.weather[0].description;
let day = document.createElement("h4")
day.innerHTML = dayweather
let temperature = document.createElement("p")
let kelvin = firstItem.main.temp.toFixed(0);
let f = 9 / 5 * (kelvin - 273) + 32;
temperature.innerHTML = `Current temperature: ${f}℉`
let hum = document.createElement("p")
hum.innerHTML = `${firstItem.main.humidity}%`
let img = document.createElement('img');
img.setAttribute('src', icon);
img.setAttribute('alt', "icon");
img.setAttribute('loading', 'lazy');
individualDiv.appendChild(img);
individualDiv.appendChild(day);
individualDiv.appendChild(description);
individualDiv.appendChild(temperature);
individualDiv.appendChild(hum);
contentDiv.appendChild(individualDiv);
}
form.addEventListener("submit", e => {
e.preventDefault();
const inputVal = input.value;
const urlForecast = `https://api.openweathermap.org/data/2.5/forecast?q=${inputVal}&appid=${myKey}`;
fetch(urlForecast)
.then((response) => response.json())
.then((object) => {
console.log(object);
const {
city,
list
} = object;
let title = document.createElement("h3");
title.innerHTML = `${city.name}, ${city.country}`
titleDiv.appendChild(title);
//im using this one for the example
firstItemF(list, city)
SecondItemF(list, city)
ThirdItemF(list, city)
})
});
//Here is the problem
refresh.addEventListener("click", (e) => {
contentDiv.classList.remove("individual");
})
<form id="form-1">
<button type="submit">SUBMIT</button>
<i id="refresh" class="fa-solid fa-arrow-rotate-right"></i>
<input id="input-s2" type="text" placeholder="Search for a city" autofocus>
<div class="cards-container">
<div class="contentdiv">
</div>
</div>
</form>
You need to use a linter like this one: https://jshint.com Your code needs a ton of semi-colons and you're missing a bracket and parenthesis }) that .fetch() or submit handler needs. I edited your question just so it doesn't irritate anyone trying to answer the question. You'll see the comment at the bottom of this example showing where I added it, but I guessed because there's no way to test it since there's no key for the API (but not expecting one, so worries there).
Besides that problem, the solution for the problem addressed in the question is the following:
Remove:
contentDiv.classList.remove("individual");
And add:
contentDiv.replaceChildren();
Removing a class doesn't remove the actual elements (well normally unless there's some very convoluted logic going on). .replaceChildren(); without a parameter will remove everything within contentDiv, but if you nee to just remove .individual do the following:
document.querySelector('.individual').remove();
const refresh = document.querySelector("#refresh");
const form = document.querySelector("#form-1");
const contentDiv = document.querySelector(".contentdiv");
const input = document.querySelector("#form-1 input");
//There're another two function like this one below
function firstItemF(list, city) {
let firstItem = list[0];
let dayweather = "Sunday";
const icon = `https://openweathermap.org/img/wn/${firstItem.weather[0].icon}#2x.png`;
let individualDiv = document.createElement("Div");
individualDiv.className = "individual";
let description = document.createElement("p");
description.innerHTML = firstItem.weather[0].description;
let day = document.createElement("h4");
day.innerHTML = dayweather;
let temperature = document.createElement("p");
let kelvin = firstItem.main.temp.toFixed(0);
let f = 9 / 5 * (kelvin - 273) + 32;
temperature.innerHTML = `Current temperature: ${f}℉`;
let hum = document.createElement("p");
hum.innerHTML = `${firstItem.main.humidity}%`;
let img = document.createElement('img');
img.setAttribute('src', icon);
img.setAttribute('alt', "icon");
img.setAttribute('loading', 'lazy');
individualDiv.appendChild(img);
individualDiv.appendChild(day);
individualDiv.appendChild(description);
individualDiv.appendChild(temperature);
individualDiv.appendChild(hum);
contentDiv.appendChild(individualDiv);
}
form.addEventListener("submit", e => {
e.preventDefault();
const inputVal = input.value;
const urlForecast = `https://api.openweathermap.org/data/2.5/forecast?q=${inputVal}&appid=${myKey}`;
fetch(urlForecast)
.then((response) => response.json())
.then((object) => {
console.log(object);
const {
city,
list
} = object;
let title = document.createElement("h3");
title.innerHTML = `${city.name}, ${city.country}`;
titleDiv.appendChild(title);
//im using this one for the example
firstItemF(list, city);
SecondItemF(list, city);
ThirdItemF(list, city);
});
});// <= This is missing
//Here is the problem
refresh.addEventListener("click", (e) => {
contentDiv.replaceChildren();
});
<form id="form-1">
<button type="submit">SUBMIT</button>
<i id="refresh" class="fa-solid fa-arrow-rotate-right"></i>
<input id="input-s2" type="text" placeholder="Search for a city" autofocus>
<div class="cards-container">
<div class="contentdiv">
</div>
</div>
</form>
smarters! I'm working on a weather app and I'm failing to get user input. I tried creating a variable and assigning the input value to it and changing the part of the url that it's supposed to be dynamic. Sorry if I'm not being very clear, I'm a beginner. But here's my code and my attempt
HTML
<form class="search">
<input type="text" name="search-city" id="search-city" />
<button class="search-btn">Search</button>
</form>
<div class="container">
<div class="box">
<span class="main"></span>
<span class="name"></span>
<span class="temp"></span>
<span class="desc"></span>
<span class="feel"></span>
<span class="min"></span>
<span class="max"></span>
</div>
<div class="toggle">
<input type="checkbox" name="toggle" class="checkbox" id="checkbox" />
<label for="checkbox" class="label">
<div class="ball"></div>
<p>C</p>
<p>F</p>
</label>
</div>
</div>
JS
const name = document.querySelector('.name');
const temperature = document.querySelector('.temp');
const main = document.querySelector('.main');
const desc = document.querySelector('.desc');
const feel = document.querySelector('.feel');
const minTemp = document.querySelector('.min');
const maxTemp = document.querySelector('.max');
const searchBtn = document.querySelector('.search-btn');
let api = 'http://api.openweathermap.org/data/2.5/weather?q=';
let city = 'Los Angeles';
const API_KEY = '&appid=78f46276c074c96c7cc3e739da828101';
const getWeather = async () => {
const unit = document.querySelector('.checkbox').value;
const searchCity = document.querySelector('.search-city');
let units = `${unit}`;
let url = api + city + '&units=' + units + API_KEY;
const response = await fetch(url, { mode: 'cors' });
const data = await response.json();
displayWeather(data);
};
searchBtn.addEventListener('click', (e) => {
e.preventDefault();
});
const displayWeather = async (data) => {
name.textContent = data.name;
temperature.textContent = parseInt(data.main.temp) + '°';
main.textContent = data.weather[0].main;
desc.textContent = 'Description: ' + data.weather[0].description;
feel.textContent = 'Feels like: ' + parseInt(data.main.feels_like) + '°';
console.log(data);
minTemp.textContent = 'Min: ' + parseInt(data.main.temp_min) + '°';
maxTemp.textContent = 'Max: ' + parseInt(data.main.temp_max) + '°';
};
const toggleUnit = document.querySelector('.checkbox');
toggleUnit.addEventListener('click', (e) => {
if (e.target.value === 'imperial') {
e.target.value = 'metric';
getWeather();
} else {
e.target.value = 'imperial';
getWeather();
}
});
getWeather();
My Attempt
const getWeather = async () => {
const unit = document.querySelector('.checkbox').value;
const searchCity = document.querySelector('.search-city');
let searchTem = searchCity.value; // created a variable and assigned the user input to it
if (!searchTem) {
searchTerm = 'Detroit';
}
let units = `${unit}`;
let url = api + searchTerm + '&units=' + units + API_KEY; // here I replaced city for that variable I just created
const response = await fetch(url, { mode: 'cors' });
const data = await response.json();
displayWeather(data);
};
searchBtn.addEventListener('click', (e) => {
e.preventDefault();
});
I appreciate any help. I've been struggling with this for a day already :/
Thanks
You are querying the the input node from the document incorrectly.
As per your code
const searchCity = document.querySelector('.search-city');
will try to get a node with class search-city. Whereas, in your shared code, you are passing an id called search-city on the input element.
To fix this update your query statement
const searchCity = document.querySelector('#search-city');
Also, there is a typo in the naming of searchTerm variable. You are trying to assign input value to variable named searchTem and in your dynamic url referencing variable named searchTerm.
/**
* query all your required element once since this is costly
*
**/
const searchBtn = document.querySelector('.search-btn');
const unit = document.querySelector('.checkbox')
const searchCity = document.querySelector('#search-city');
const api = 'http://api.openweathermap.org/data/2.5/weather?q=';
const city = 'Los Angeles';
const API_KEY = '&appid=78f46276c074c96c7cc3e739da828101';
const getWeather = async () => {
let searchTerm = searchCity.value;
if (!searchTerm) {
searchTerm = 'Detroit';
}
let units = `${unit.value}`;
// here I replaced city for that variable I just created
let url = api + searchTerm + '&units=' + units + API_KEY;
const response = await fetch(url, { mode: 'cors' });
const data = await response.json();
displayWeather(data);
};
searchBtn.addEventListener('click', (e) => {
e.preventDefault();
// call the fetch handling method on submit click
getWeather();
});
<form class="search">
<input type="text" name="search-city" id="search-city" />
<button class="search-btn">Search</button>
</form>
<div class="container">
<div class="box">
<span class="main"></span>
<span class="name"></span>
<span class="temp"></span>
<span class="desc"></span>
<span class="feel"></span>
<span class="min"></span>
<span class="max"></span>
</div>
<div class="toggle">
<input type="checkbox" name="toggle" class="checkbox" id="checkbox" />
<label for="checkbox" class="label">
<div class="ball"></div>
<p>C</p>
<p>F</p>
</label>
</div>
</div>
I'm trying to change the color of the product(object) title based on the current year.
I mean if the product's year is the same as the current year it should change the title color.
Whenever I save, I get an Error in DevTools:
" Uncaught TypeError: Cannot set property 'color' of undefined ".
<form id="theForm">
<div>
<input type="text" id="title" placeholder="Type title...">
</div>
<div>
<input type="date" id="date">
</div>
<button type="submit" id="sub">Add</button>
</form>
<section class="result">
<div id="addedProducts"></div>
</section>
const theForm = document.getElementById("theForm");
theForm.addEventListener("submit", saveProduct);
function saveProduct(evt){
const proTitle = document.getElementById("title").value;
const proDate = document.getElementById("date").value;
const product = {
title: proTitle,
date: proDate
}
if(localStorage.getItem("products") === null){
const products = []; //initialized
products.push(product);// add a new Product
//to local localStorage
localStorage.setItem("products", JSON.stringify(products));
} else {
// get products from localStorage
const products = JSON.parse(localStorage.getItem("products"));
// add product to products
products.push(product);
// set again to localStorage
localStorage.setItem("products", JSON.stringify(products));
}
theForm.reset();
fetchProducts();
evt.preventDefault()
}
function fetchProducts(){
const products = JSON.parse(localStorage.getItem("products"));
const addedProducts = document.getElementById("addedProducts");
addedProducts.innerHTML = "";
products.forEach(addProduct);
function addProduct(product) {
const title = product.title;
const date = product.date;
const splitDate = date.split("");
const splittedYear = splitDate.slice(0, 4);
const splittedMonth = splitDate.slice(5, 7);
const splittedDay = splitDate.slice(8);
const jYear = splittedYear.join("");
const jMonth = splittedMonth.join("");
const jDay = splittedDay.join("");
const jDate = jMonth +"/"+ jDay +"/"+
jYear;
// Parsed Date attributes
const pYear = parseInt(jYear, 10);
const pMonth = parseInt(jMonth, 10);
const pDay = parseInt(jDay, 10);
// current Date
const cDate = new Date();
const cDay = cDate.getDate();
const cMonth = cDate.getMonth() + 1;
const cYear = cDate.getFullYear();
//Here's the problem!!!
if(pYear == cYear){
// The next line broke every thing
/* Uncaught TypeError: Cannot
set property 'color' of undefined*/
title.style.color = "#159";
console.log("yes");//that works fine
} else {
console.log("not");// So da that one
}
addedProducts.innerHTML += '<div class="res">'+
'<span class="title">' + title +'</span>' +
" " + '<span class="dateClass">' + jDate +'</span>'+
'<button onclick="deletePro(\'' + title + '\',\'' + date + '\')" id="remove">Delete</button>' +
'</div>';
}
}
Sorry if it's a long code. I've been so confused!