Star Rating based on Avg. Number - Vanilla JS - javascript

I can't seem to find the solution.
I need only to display the stars, based on the fixed average number. So half star for a decimal above 0.5, while star for an integer and outline star for a value below 0.5.
Based on the data
const shirt = {
name: "White Shirt",
newPrice: 10.99,
oldPrice: 29.99,
avgRating: 4.3
}
const productDetail = document.querySelector('.product-detail')
productDetail.innerHTML = `
<h2>${shirt.name}</h2>
<div class="sale-perc">
<span>33% OFF</span>
</div>
<div class="price-review">
<div class="price">
<span class="new-price">${shirt.newPrice}</span>
<span class="old-price">${shirt.oldPrice}</span>
</div>
<div class="review-rating">
<div class="review-stars">
<p>
${(() => {
let rating = ''
const avgRating = shirt.avgRating
for (let i = 0; i < 5; i++) {
if (i < avgRating) {
rating += `<i class="fa-solid fa-star"></i>`
} else if (i === avgRating && avgRating % 1 !== 0) {
rating += `<i class="fa-solid fa-star-half-alt"></i>`
} else {
rating += `<i class="fa-regular fa-star"></i>`
}
}
return rating
})()}
</p>
</div>
</div>
</div>

let rating = ''
const avgRating = shirt.avgRating
for (let i = 1; i <= avgRating; i += 0.5) {
if (i % 1 === 0) {
rating += `<i class="fa-solid fa-star"></i>`;
} else if (i % 1 !== 0 && i === avgRating) {
rating += `<i class="fa-solid fa-star-half-alt"></i>`;
}
}
return rating;

Related

How to filter data using checkbox? Angular

import { Component, OnInit } from '#angular/core';
import { Options } from '#angular-slider/ngx-slider';
#Component({
selector: 'app-trips',
templateUrl: './trips.component.html',
styleUrls: ['./trips.component.css']
})
export class TripsComponent implements OnInit {
tripsBooked: number = 0
trips: Trip[] = []
minValue: number = 600
maxValue: number = 30000
minPer: number = 0
maxPer: number = 100
ngOnInit(): void {
fetch('./assets/trips.json').then(res => res.json()).then(json => {
for (let p in json["Trips"]) {
this.trips.push({
name: json["Trips"][p]["Name"],
destination: json["Trips"][p]["Destination"],
exactdestination: json["Trips"][p]["Exact-Destination"],
date: json["Trips"][p]["Date"],
price: json["Trips"][p]["Price"],
places: json["Trips"][p]["Places"],
maxplaces: json["Trips"][p]["Max-Places"],
description: json["Trips"][p]["Descripion"],
image: json["Trips"][p]["Image"],
likes: json["Trips"][p]["Likes"],
dislikes: json["Trips"][p]["Dislikes"],
voted: json["Trips"][p]["Voted"]
} as Trip)
}
for(let x of this.trips){
if(this.maxValue < x.price)
this.maxValue = x.price
if(this.minValue > x.price)
this.minValue =x.price
}
});
}
//---slider
options: Options = {
floor: this.minValue,
ceil: this.maxValue,
// floor:600,
// ceil:100000,
};
//---slider
options2: Options ={
floor: 0,
ceil: 100,
}
a: number = 5
rating(x: Trip, rate: number) {
switch (x.voted) {
case (0):
if (rate == 1) {
x.likes += 1
x.voted = 1
}
else {
x.dislikes += 1
x.voted = -1
}
break;
case (1):
if (rate == 1) {
x.likes -= 1;
x.voted = 0;
}
else {
x.likes -= 1
x.dislikes += 1
x.voted = -1
}
break;
case (-1):
if (rate == 1) {
x.likes += 1
x.dislikes -= 1
x.voted = 1
}
else {
x.dislikes -= 1
x.voted = 0
}
break;
}
}
getMaxPrice(trips: Trip[]): Trip {
let max = -1
let maxPriceTrip = <Trip>{}
for (let x of trips) {
if (x.price > max) {
max = x.price
maxPriceTrip = x
}
}
return maxPriceTrip
}
getMinPrice(trips: Trip[]): Trip {
let min = 99999999
let minPriceTrip = <Trip>{}
for (let x of trips) {
if (x.price < min) {
min = x.price
minPriceTrip = x
}
}
return minPriceTrip
}
addTrip(trip: Trip): void {
if (trip.places == 0)
return
this.tripsBooked += 1
trip.places -= 1
}
removeTrip(trip: Trip): void {
if (trip.maxplaces == trip.places)
return
this.tripsBooked -= 1
trip.places += 1
}
getBooked(trips: Trip[]): number {
// let cnt = 0
// for(let x of trips)
// cnt += x.places
// return cnt
return this.tripsBooked
}
deleteTrip(trip: Trip): void {
let c = 0
while (this.trips[c] != trip)
c += 1
this.trips.splice(c, 1)
}
formSubmitEventHandler(trip: Trip) {
this.trips.push(trip)
console.log(this.trips)
}
}
export interface Trip {
name: string;
destination: string
exactdestination: string
date: string
price: number
places: number
maxplaces: number
description: string
image: string
likes: number
dislikes: number
voted: number
}
<app-trip-add (formSubmitEvent)="formSubmitEventHandler($event)"></app-trip-add>
<div class="order-details">
<h2 [ngStyle]="{'background-color': getBooked(trips) > 10 ? 'green' : 'red'}">
Akualna ilość zabookowanych miejsc na wycieczki: {{getBooked(trips)}}
</h2>
</div>
<form>
<div *ngFor="let x of trips">
<input type="checkbox"> {{x.destination}}
</div>
</form>
<ngx-slider [(value)]="minValue" [(highValue)]="maxValue" [options]="options" style="width: 80%; margin-left: 100px">
</ngx-slider>
<ngx-slider [(value)]="minPer" [(highValue)]="maxPer" [options]="options2" style="width: 80%; margin-left: 100px">
</ngx-slider>
<div class="trip-list" *ngIf="trips!=[]">
<ng-container *ngFor=" let x of trips">
<div class="single-trip" *ngIf="(x.price>=minValue && x.price<=maxValue && x.likes/(x.dislikes+x.likes)*100 >= minPer && x.likes/(x.dislikes+x.likes)*100 <= maxPer) || x.likes+x.dislikes==0"
[ngClass]="{
'most-expensive': x.price == getMaxPrice(trips).price,
'least-expensive': x.price == getMinPrice(trips).price}">
<h1>{{x.name | uppercase}}</h1>
<hr>
<img src="{{ x.image }}">
<hr>
<h3>{{x.destination | uppercase}}</h3>
<p>{{x.exactdestination}}</p>
<hr>
<p>{{x.date}}</p>
<hr>
<p>{{x.description}}</p>
<hr>
<p>Dostępne miejsca: {{x.places}}</p>
<hr>
<div class="bottom">
<span>${{x.price}}</span>
</div>
<hr>
<div class="reviews">
<app-trip-rating (rated)="rating(x, $event)" [likes]="x.likes" [dislikes]="x.dislikes"
[ngClass]="{'liked': x.voted == 1, disliked : x.voted == -1}"></app-trip-rating>
</div>
<p *ngIf="x.likes+x.dislikes>0"><br>Ta wycieczka podobała się {{x.likes/(x.dislikes+x.likes)*100 |
number:'1.0-0'}}% użytkowników</p>
<hr>
<div class="btn-container">
<div *ngIf="x.places > 0" class="btn" (click)="addTrip(x)"><i class="fa-solid fa-plus"></i></div>
<div *ngIf="x.places != x.maxplaces" class="btn" (click)="removeTrip(x)"><i
class="fa-solid fa-minus"></i></div>
</div>
<p *ngIf="x.places <= 3 && x.places >1" class="bottom-info-text orange">
Pozostały tylko {{ x.places }} wolne miejsca!
</p>
<p *ngIf="x.places == 1" class="bottom-info-text red-orange">
Pozostało tylko {{ x.places }} wolne miejsce!
</p>
<p *ngIf="x.places == 0" class="bottom-info-text red">
Na tę wycieczkę nie ma już wolnych miejsc!
</p>
<div class="deleteBtn" (click)="deleteTrip(x)">usuń wycieczkę</div>
</div>
</ng-container>
</div>
Here I have small angular project with different trips to choose from. I'd like to add ability of filtering using checkbox (filtering by countries). My checkbox looks like this:
<form>
<div *ngFor="let x of trips">
<input type="checkbox"> {{x.destination}}
</div>
</form>
How can I use data that is checked in checkbox to show only trips which destination is checked?
Here is the rest of the code (html and typescript from that component)

How to change color of a class with Javascript

I get all movie datas from Firebase and also i get score of the movies. If the score of the movie is higher than 70, then i will change color of the class as "deepskyblue", if it is 50 or higher it will be "orange" and lastly if it is lower than 50 it will be "crimson"(red). When i do this, it only changes my first movie's class's color. But i wanna change all of them. How can i do this?
var movieNo = 0;
let html = '';
var body = document.getElementById('editor');
var body2 = document.getElementById('week');
function AddItemsToTable(name, score, img, id) {
var movies = `<div class="content"><img src="${img}" ><p>${name}</p> <p> <i class="fa fa-star" id="star"></i> <a class="scoretxt">${score}</a> </p> </div>`;
html = movies;
body.innerHTML += html;
body2.innerHTML += html;
}
function AddAllItemsToTable(TheMovies) {
movieNo = 0;
var counter = 0;
TheMovies.forEach(element => {
if (counter === 6) {
return;
}
AddItemsToTable(element.movieName, element.movieScore, element.movieImage, element.movieId);
var i = document.getElementsByClassName("fa fa-star")[element.movieId];
console.log(i);
if (element.movieScore >= 70) {
i.style.color = "deepskyblue"; //good movie
} else if (element.movieScore >= 50) {
i.style.color = "orange"; //not bad
} else {
i.style.color = "crimson"; //bad movie
}
counter++;
});
}
function getAllDataOnce() {
const dbRef = ref(db);
get(child(dbRef, "Movies"))
.then((snapshot) => {
var movies = [];
snapshot.forEach(childSnapshot => {
movies.push(childSnapshot.val())
});
AddAllItemsToTable(movies);
});
}
window.onload = getAllDataOnce;
<div class="body" id="body">
<div class="baslik">Opening This Week</div>
<div class="baslik2">See all</div>
<div id="week">
</div>
<div class="baslik">Editor's Picks</div>
<div class="baslik2">See all</div>
<div id="editor">
</div>
</div>
My Website
Console.log(i)
Instead of selecting the elements with class name you can give it a unique id. For th i tags you can give the id as for example id="star${id}"
function AddItemsToTable(name, score, img, id) {
var movies = `<div class="content"><img src="${img}" ><p>${name}</p> <p> <i class="fa fa-star" id="star${id}"></i> <a class="scoretxt">${score}</a> </p> </div>`;
html = movies;
body.innerHTML += html;
body2.innerHTML += html;
}
AddItemsToTable(element.movieName, element.movieScore, element.movieImage,
element.movieId);
var i = document.getElementById("#star"+element.movieId);
you can just use a style="color:"desired color name/hexcode" easiest way to change color

Changing color of an id with Javascript

I get all movie datas from Firebase and also i get score of the movies. If the score of the movie is higher than 70, then i will change color of the id as "deepskyblue", if it is 50 or higher it will be "orange" and lastly if it is lower than 50 it will be "crimson"(red). When i do this, it only changes my first movie's id's color. But i wanna change all of them. How can i do this?
My Website
Console.log(i)
var movieNo = 0;
let html = '';
var body = document.getElementById('editor');
var body2 = document.getElementById('week');
function AddItemsToTable(name, score, img, id) {
var movies = `<div class="content"><img src="${img}" ><p>${name}</p> <p> <i class="fa fa-star" id="star"></i> <a class="scoretxt">${score}</a> </p> </div>`;
html = movies;
body.innerHTML += html;
body2.innerHTML += html;
}
function AddAllItemsToTable(TheMovies) {
movieNo = 0;
var counter = 0;
TheMovies.forEach(element => {
if (counter === 6) {
return;
}
AddItemsToTable(element.movieName, element.movieScore, element.movieImage, element.movieId);
var i = document.getElementsByClassName("fa fa-star")[element.movieId];
console.log(i);
if (element.movieScore >= 70) {
i.style.color = "deepskyblue"; //good movie
} else if (element.movieScore >= 50) {
i.style.color = "orange"; //not bad
} else {
i.style.color = "crimson"; //bad movie
}
counter++;
});
}
function getAllDataOnce() {
const dbRef = ref(db);
get(child(dbRef, "Movies"))
.then((snapshot) => {
var movies = [];
snapshot.forEach(childSnapshot => {
movies.push(childSnapshot.val())
});
AddAllItemsToTable(movies);
});
}
window.onload = getAllDataOnce;
<div class="body" id="body">
<div class="baslik">Opening This Week</div>
<div class="baslik2">See all</div>
<div id="week">
</div>
<div class="baslik">Editor's Picks</div>
<div class="baslik2">See all</div>
<div id="editor">
</div>
</div>
I suggest to change the logic.
Your mistake is that you use the same id several times, and it should be unique (1 element = 1 unique id).
Try to make it like this:
// AddAllItemsToTable function
if (element.movieScore >= 50 && element.movieScore < 70 ) {
i.classList.add("deepskyblue"); // good movie
} else if (element.movieScore >= 70) {
i.classList.add("orange"); // not bad
} else {
i.classList.add("crimson"); // bad movie
}
After that, add the following rules to your styles file:
.deepskyblue {
color: deepskyblue;
}
.orange {
color: orange;
}
.crimson {
color: crimson;
}
Everything will work as it should and as a bonus it will be easier to manage styles and and you won't have to fix JS code for this.
Make a function
NOTE IDs need to be unique
const scoreColor = score => {
const color = "crimson"
if (score >= 70) return "deepskyblue"; //good movie
if (score >= 50) return "orange"; //not bad
return score;
};
function AddItemsToTable(name, score, img, id) {
const movies = `<div class="content">
<img src="${img}" >
<p>${name}</p>
<p><i class="fa fa-star"></i> <a class="${scoreColor(score)}">${score}</a></p>
</div>`;
body.innerHTML += movies;
body2.innerHTML += movies;
}

Add or remove a value from a localstorage object

I want add or remove 1 by click for one of the obj.onlist in this array from localstorage
{loklakchicken: {name: "Lok Lak Chicken", tag: "loklakchicken", price: 9.9, onList: 2},…}
Lottchabeef: {name: "Lot Tcha Beef", tag: "Lottchabeef", price: 9.9, onList: 1}
loklakchicken: {name: "Lok Lak Chicken", tag: "loklakchicken", price: 9.9, onList: 2}
loklakvegan: {name: "Lok Lak Vegan", tag: "loklakvegan", price: 9.9, onList: 17}
lottchavegan: {name: "Lot Tcha Vegan", tag: "lottchavegan", price: 9.9, onList: 2}
I try something like this
let obj = localStorage.getItem('prodOnList');
obj = JSON.parse(orderListItems);
for (let i = 0; i < obj.length; i++) {
$('.plus').click(function () {
obj[i].onList += 1;
}
$('.minus').click(function () {
obj[i].onList -= 1;
}
}
localStorage.setItem("prodOnList", JSON.stringify(obj));
I am sure i am missing something pretty obvious, thx
UPDATE
I am doing a cart list create with JS and for each product on the list I have a button to add or remove one...
I try to bind my function setItems on btn plus click event no result...
My problem is i dont now how to target the object from the array on localstorage where i am calling the event click!
thx for your help
class OrderBtn{
constructor(){
this.prodList = [
just remove the array with the products
];
}
addToList(){
let menus = document.querySelectorAll('.add-list');
for (let i = 0; i < menus.length; i++) {
$(menus[i]).click(()=>{
this.listCount(this.prodList[i]);
this.totalPrice(this.prodList[i]);
this.displayOrderList();
});
}
}
listCount(prod){
let productNum = localStorage.getItem('listNum');
productNum = parseInt(productNum);
if (productNum) {
localStorage.setItem('listNum', productNum + 1);
} else {
localStorage.setItem('listNum', 1);
}
this.setItems(prod);
}
setItems(prod){
let orderListItems = localStorage.getItem('prodOnList');
orderListItems = JSON.parse(orderListItems);
if (orderListItems !== null){
if(orderListItems[prod.tag] === undefined){
orderListItems = {
...orderListItems,
[prod.tag]: prod
}
}
orderListItems[prod.tag].onList += 1;
} else{
prod.onList = 1;
orderListItems = {
[prod.tag]: prod
}
}
localStorage.setItem("prodOnList", JSON.stringify(orderListItems));
}
totalPrice(prod){
let orderTotal = localStorage.getItem('totalCost');
if(orderTotal !== null){
orderTotal = parseFloat(orderTotal);
let resultPrice = orderTotal + prod.price;
resultPrice = resultPrice.toFixed(2);
localStorage.setItem('totalCost', resultPrice);
} else {
localStorage.setItem('totalCost', prod.price.toFixed(2));
}
}
displayOrderList(){
let orderItems = localStorage.getItem('prodOnList');
let orderTotal = localStorage.getItem('totalCost');
orderItems = JSON.parse(orderItems);
let orderContainer = document.querySelector('.orderList');
if (orderItems && orderContainer) {
orderContainer.innerHTML = "";
Object.values(orderItems).map(item =>{
let totalItem = item.onList * item.price;
totalItem = totalItem.toFixed(2);
orderContainer.innerHTML += `
<div class="quantity d-flex justify-content-between align-items-center mb-2">
<i class="fas fa-times text-danger"></i>
<div class="itemNum">
<i class="btnMinus fas fa-minus"></i>
<span class="mx-2">${item.onList}</span>
<i class="btnPlus fas fa-plus"></i>
</div>
<span class="total">${totalItem} €</span>
</div>
<div class="product d-flex justify-content-between align-items-center">
<span>${item.name}</span>
</div>
`;
});
$('.totalOrder').text(`Total : ${orderTotal} €`)
}else{
orderContainer.innerHTML = `
<p class="product">Votre panier est vide</p>`;
$('.totalOrder').text(`Total : 0.00 €`)
}
}
}
If I didn't misunderstood your problem, this will work for you
$('.plus').click(function () {
addOrRemoveByOne('add');
}
$('.minus').click(function () {
addOrRemoveByOne('remove');
}
addOrRemoveByOne(option) {
let obj = JSON.parse(localStorage.getItem('prodOnList'));
for (let key in obj) {
if (option === 'add') {
obj[key].onList += 1;
}
if (option === 'remove') {
obj[key].onList -= 1;
}
}
localStorage.setItem("prodOnList", JSON.stringify(obj));}
}

clear input box with vanilla JavaScript?

He Guys, I tried couple of times to reset my input field with Vanilla javaScript with no success...I tried the reset() method but, perhaps I didn't add the code right...Here is my code.
<div class="container">
<h1>Enter a Number<br />
from 1 to 100.
</h1>
<input type="input" id="inputBox">
<input type="button" id="button" value="submit" onclick="myFunction()">
<span id="box1"></span>
</div>
and js
function myFunction() {
var i = document.getElementById("inputBox").value;
//for (var i = 1; i < 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
document.getElementById("box1").innerHTML = "fizzbuzz";
} else if (i % 3 === 0) {
document.getElementById("box1").innerHTML = "fizz";
} else if (i % 5 === 0) {
document.getElementById("box1").innerHTML = "buzz";
} else {
document.getElementById("box1").innerHTML = i;
}
}
I also have a pen here:
http://codepen.io/lucky500/pen/GJjVEO
Thanks!
just set the value of the input document.getElementById("inputBox").value = ""
function myFunction() {
var input = document.getElementById("inputBox");
var i = input.value;
//for (var i = 1; i < 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
document.getElementById("box1").innerHTML = "fizzbuzz";
} else if (i % 3 === 0) {
document.getElementById("box1").innerHTML = "fizz";
} else if (i % 5 === 0) {
document.getElementById("box1").innerHTML = "buzz";
} else {
document.getElementById("box1").innerHTML = i;
}
// clear input
input.value = "";
}
<div class="container">
<h1>Enter a Number<br />
from 1 to 100.
</h1>
<input type="input" id="inputBox">
<input type="button" id="button" value="submit" onclick="myFunction()">
<span id="box1"></span>
</div>

Categories

Resources