In which it is better to make an e-commerce shopping cart function in django or js

Hi I’m wondering if my way of making a shopping cart is good, all the tutorials I see on the web rather insist on doing it using js rather than recording it in a model table.

class Cart(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    def total(self):
        user_cart = Cart.objects.get(user=self.user)
        items_in_cart = CartItem.objects.filter(cart=user_cart)

        total_price = 0
        for item in items_in_cart:
            total_price += item.product.price
        return total_price

    def quantity_of_items(self):
        user_cart = Cart.objects.get(user=self.user)
        items_in_cart = CartItem.objects.filter(cart=user_cart)
        return len(items_in_cart)


class CartItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)

view to save

class ProductDetailView(View):
    def get(self, request, pk):
        product = Product.objects.get(id=pk)
        context = {'object': product}
        return render(request, "products/detailview.html", context)

    def post(self, request, pk):
        if not request.user.is_authenticated:
            messages.success(request, "You must be logged in")
            return redirect('Login')

        cart, created = Cart.objects.get_or_create(
            user=request.user,
        )
        cart.save()

        added_item = Product.objects.get(id=pk)
        added_item.popularity += 1
        added_item.save()

        item_in_cart = CartItem.objects.filter(cart=cart)
        for item in item_in_cart:
            if item.product.title == added_item.title:
                messages.success(request, "It's already in the basket")
                return redirect('ProductDetail', pk=pk)

        new_item_in_cart = CartItem.objects.create(
            product=added_item,
            cart=cart,
        )
        new_item_in_cart.save()

        added_item.quantity -= 1
        if added_item.quantity == 0:
            added_item.is_available = False
        added_item.save()

        messages.success(request, "Add to cart")
        return redirect('home')

With the help of redis I check every hour the time of the last change of the basket if it is greater than 1 hour I delete the whole basket so that the number of items agrees and it does not depend.

Please advise, I don’t know whether to abandon it and convert it to js? Thank you all!

async/await not pausing execution of script and failing validation checks

I have written some code that successfully pulls the value from MongoDB, to check what has been sent to the API is the same price in MongoDB. In order to get the value from MondoDB, I have to use findbyID (a Mongoose function).

For some reason, despite using async and await, the validation checks are run before the value is returned from Mongoose’s findById function and the value from MongoDB is provided on the last line of the console log output, despite me thinking it should be the second console logged output.

Please could someone tell me how I can ensure the checks only begin after getting the dbPrice.price value from MongoDB and assigning it to the DBPrice variable?

Here’s the code and the console output:

Code

var checkValidPrice = [];
  req.body.products.map((item) => {
    const itemPrice = item.price;
    console.log(`item price: ${itemPrice}`);
    async function checking() {
      let dbPrice = await Product.findById(item.productId, "price");
      console.log(`dbPrice: ${dbPrice.price}`);
      if (itemPrice === dbPrice.price) {
        return checkValidPrice.push("true");
      } else {
        return checkValidPrice.push("false");
      }
    }
    checking();

    console.log(`check price printing: ${checkValidPrice}`);
  });

  console.log(`func? ${checkValidPrice.includes("false")}`);

actual console output

item price: 350
check price printing: 
func? false
dbPrice: 350

expected console output

item price: 350
dbPrice: 350
check price printing: true
func? false

What happens once we run our JS script?

My doubt is in relation to the code executed in relation to the phases of the event loop. I’ve read from beginning to end about the phases. But when we get into some articles and examples, it gets really confusing.

The following code is very simple and I have some doubts as soon as we run it: node my-script.js

{console.log('start'); 

setTimeout(() => console.log('time out'), 0); 

setImmediate(() => console.log('immediate')); 

const sum = 10 + 10; 

console.log(`result sum = ${sum}`);}

1- Is all our js code my-script.js executed in the poll phase??

2- I was reading that as soon as we run our ‘node my-script.js’ file (for example), before the event loop enters its phases, a process of registering the callbacks takes place. This means that when we run node …. it will take the setTimeout callback and put it in the heap, take the setImmediate callback and in the check phase, it will take the console.log and put it in the poll phase, and only after that the event loop will start entering your phases??

2.1- If that was true, as soon as we set the setTimeout to 0 and the event loop enters the timers phase, the timer will already have expired and be executed, right!? But that doesn’t actually happen. Eh as if it was only scheduled when we enter the poll phase

This for me is very confusing when I read several articles.

According to the articles read, the time limit must be printed beforehand. But that doesn’t happen.

JSON doesn’t recognize non-english characters

I made a calculator for my webflow website, but when I try to automate it using webflow “Logic” (like zapier), by sending form data to my gmail and to my google sheet, I get an error that action fails (even tho I test run it in the designer module, only on live site it fails). My idea is that since im from non-english speaking country and my website uses non ASCII characters it might be not understanding. Here is my calculator:

<script>
//slider
var productsSlider = document.getElementById("productsSlider");
var productsSlider2 = document.getElementById("productsSlider2");

//input
var productsInput = document.getElementById("Valandos");
var productsInput2 = document.getElementById("Kilometrai");
var totalCost = document.getElementById("Pilna-kaina");
var avansas = document.getElementById("Avansas");

//Text
var nuolaida10 = document.getElementById("Nuolaida-Fotosesijai");
var gif = document.getElementById("Judancios-Nuotraukos");
var nuolaida20 = document.getElementById("Nuolaida-Akimirkoms");
var fotosesijainfo = document.getElementById("fotosesijainfo");
var akimirkosinfo = document.getElementById("akimirkosinfo");
var fotoknygainfo = document.getElementById("fotoknygainfo");
var nuotraukos = document.getElementById("Nuotraukos");

//checkboxes
var fotosesija = document.getElementById("Love-Story-Fotosesija");
var fotosesijoskaina = document.getElementById("fotosesijos-kaina");
var akimirkos = document.getElementById("Pirmosios-Akimirkos");
var akimirkoskaina = document.getElementById("Akimirkos-Kaina");
var fotoknyga = document.getElementById("Fotoknyga");
var fotoknygakaina = document.getElementById("Fotoknyga-kaina");

//set defaults
productsInput.value = 4;
productsInput2.value = 0;
totalCost.value = 400;
avansas.value = 80;
nuolaida10.value = "– 10% nuolaida Love - Story"
nuolaida10.style.color = "#cecece"
gif.value = "– Judančios nuotraukos (GIF)"
gif.style.color = "#cecece"
nuolaida20.value = "– Pirmosios akimirkos 20% pigiau"
nuolaida20.style.color = "#cecece"
fotosesijainfo.value = "– Love - Story Fotosesija"
fotosesijainfo.style.color = "#cecece"
akimirkosinfo.value = "– Pirmosios Akimirkos"
akimirkosinfo.style.color = "#cecece" 
fotoknygainfo.value = "– Fotoknyga"
fotoknygainfo.style.color = "#cecece"

fotosesijoskaina.value = 90;
akimirkoskaina.value = 90;
fotoknygakaina.value = 170;
nuotraukos.value = 120;

//Calculation
function calculateChange() {
productsInput.value = productsSlider.value;
productsInput2.value = productsSlider2.value;
totalCost.value = productsInput.value * 100 + productsInput2.value * 0.3;
nuotraukos.value = productsInput.value * 30;
   //nuolaida10
if (productsInput.value === "7" || productsInput.value === "8" || productsInput.value === "9" || productsInput.value === "10") {
nuolaida10.style.color = "#333"
fotosesijoskaina.value = "81"
else {
nuolaida10.style.color = "#cecece"
fotosesijoskaina.value = "90"
  }
  //nuolaida20
if (productsInput.value === "10") {
nuolaida20.style.color = "#333"
akimirkoskaina.value = "81"
else {
nuolaida20.style.color = "#cecece"
akimirkoskaina.value = "90"
  }

if (fotosesija.checked === true) {
totalCost.value = Number(totalCost.value) + Number(fotosesijoskaina.value);
fotosesijainfo.style.color = "#333"
else {
totalCost.value = Number(totalCost.value);
fotosesijainfo.style.color = "#cecece"
  }
if (akimirkos.checked === true) {
totalCost.value = Number(totalCost.value) + Number(akimirkoskaina.value);
akimirkosinfo.style.color = "#333"
else {
totalCost.value = Number(totalCost.value);
akimirkosinfo.style.color = "#cecece"
  }
if (fotoknyga.checked === true) {
totalCost.value = Number(totalCost.value) + 170;
fotoknygainfo.style.color = "#333"
else {
fotoknygainfo.style.color = "#cecece"
  }
 
avansas.value = (totalCost.value * 20) / 100;



  //gif
if (productsInput.value >= "5") {
gif.style.color = "#333"
else {
gif.style.color = "#cecece"
  }
if (productsInput.value === "10") {
gif.style.color = "#333"
  }
 
}

//Avansas
//function calculateChange() {
//avansas.value

//call functions
fotosesijoskaina.onchange = function () {
  calculateChange();
};
akimirkoskaina.onchange = function () {
  calculateChange();
};
fotosesija.onchange = function () {
calculateChange();
};
fotoknyga.`o

nchange = function () {
calculateChange();
};
akimirkos.onchange = function () {
calculateChange();
};

“`

Thanks for the help.

I’m trying to create a javascript code to calculate the total cost of services which the user selects

I’m trying to create a javascript code to calculate the total cost of services which the user selects. The total cost should be updated live in the cart as the user selects any service. Discount and taxes are also meant to be taken into account. The code that I’ve tried will be provided below.

<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<meta http-equiv="X-UA-Compatible" content="IE=Edge">

<<link rel="stylesheet" href="style.css">

<title>TribalGateway - Airport Escort</title>
<h1>Airport Escort</h1>

<p>

  Thank you for the opportunity to allow us to make your visit to Nigeria as

  stress-free as possible. Our Airport Escort will greet you once you arrive

  and guide you through the Immigration Lines as quickly as possible. You

  can have one loved one meet you right outside of the Security Door. To

  customize your experience, please select your preferences below.

</p>

<form action="#" method="post">

  <fieldset>

    <legend>Personal Information</legend>

    <label for="name">Name:</label>

    <input type="text" id="name" name="name" required /><br />

    <label for="phone">Phone:</label>

    <input type="tel" id="phone" name="phone" required /><br />

    <label for="email">Email Address:</label>

    <input type="email" id="email" name="email" required /><br />

    <label for="arrival-date">Date of Arrival:</label>

    <input type="date" id="arrival-date" name="arrival-date" required /><br />

    <label for="arrival-time">Time of Arrival:</label>

    <input type="time" id="arrival-time" name="arrival-time" required /><br />

    <label for="airline">Airline:</label>

    <input type="text" id="airline" name="airline" required /><br />

    <label for="departure-date">Date of Departure:</label>

    <input type="date" id="departure-date" name="departure-date" required /><br />

    <label for="persons-arriving">How many persons will be arriving?</label>

    <input type="number" id="persons-arriving" name="persons-arriving" required /><br />

  </fieldset>

  <fieldset>

    <legend>Escort Service</legend>

    <p>I NEED ESCORT SERVICE FOR:</p>

    <label>

      <input type="checkbox" name="escort-service" value="Arrival Only" /> Arrival Only

      $150pp

    </label><br />

    <label>

      <input type="checkbox" name="escort-service" value="Departure Only" /> Departure Only

      $150pp

    </label><br />

    <label>

      <input type="checkbox" name="escort-service" value="Both Arrival and Departure" /> Both

      Arrival and Departure $275

    </label><br />

    <p>Will someone be in Nigeria to greet you at the airport?</p>

    <label for="greet-name">Name:</label>

    <input type="text" id="greet-name" name="greet-name" /><br />

    <label for="greet-phone">Phone#:</label>

    <input type="tel" id="greet-phone" name="greet-phone" /><br />

    <label for="emergency-contact">Emergency Contact in Home Country:</label>

    <input type="text" id="emergency-contact" name="emergency-contact" /><br />

  </fieldset>

  <fieldset>

    <legend>TRANSPORTATION</legend>

Please indicate if you will need transportation on the day of your Arrival and Departure.

I will need transportation from the airport to my housing accommodations on the day of my Arrival. ($50)

I will need transportation from my housing accommodation to the airport on the day of my Departure. ($50)

For my arrival, I will need transportation for my Relative to be picked up and brought to the airport to greet me, and then take us both to our accommodation from the airport ($100)

I will also need this for my Departure. The driver will pick us up from our accommodation and take us to the airport. The driver will wait at the airport while my Relative sees me off. Then the driver will take my Relative back to the accommodations. ($100)

<legend>SECURITY</legend>

<p>Would you like to have a security officer to escort you for the day?</p>

<input type="radio" name="security" value="no" id="security-1" checked>

<label for="security-1">No</label>

<br>

<input type="radio" name="security" value="private-officer" id="security-2">

<label for="security-2">Private Officer ($50 daily)</label>

<br>

<input type="radio" name="security" value="police-officer" id="security-3">

<label for="security-3">Police Officer ($70 daily)</label>

<br>

<input type="checkbox" name="security" value="visibly-armed" id="security-4">

<label for="security-4">Visibly Armed ($50 daily surcharge, in addition to above Officer Charge)</label>
<legend>T-SHIRTS</legend>

<p>Queen Tshirt $25</p>

<input type="checkbox" name="tshirt" value="queen-s" id="tshirt-1">

<label for="tshirt-1">S</label>

<input type="checkbox" name="tshirt" value="queen-m" id="tshirt-2">

<label for="tshirt-2">M</label>

<input type="checkbox" name="tshirt" value="queen-l" id="tshirt-3">

<label for="tshirt-3">L</label>

<input type="checkbox" name="tshirt" value="queen-xl" id="tshirt-4">

<label for="tshirt-4">XL</label>

<input type="checkbox" name="tshirt" value="queen-1x" id="tshirt-5">

<label for="tshirt-5">Queen T-Shirt (1X)</label>

0
1
2
3
4
5

Matching King T-Shirt:

King T-Shirt (M)

<option value="0">0</option>

<option value="1">1</option>

<option value="2">2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

King T-Shirt (L)

<option value="0">0</option>

<option value="1">1</option>

<option value="2">2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

King T-Shirt (XL)

<option value="0">0</option>

<option value="1">1</option>

<option value="2">2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

King T-Shirt (1X)

<option value="0">0</option>

<option value="1">1</option>

<option value="2">2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

<legend>CART</legend>

Escort Services $<span id="escort-total">0</span><br>

Transportation $<span id="transportation-total">0</span><br>

Security $<span id="security-total">0</span><br>

T-Shirts $<span id="tshirt-total">0</span><br>

Vat/Taxes $<span id="vat-total">10</span><br>

<hr>

SUBTOTAL $<span id="subtotal">0</span><br>

DISCOUNT CODE: <input type="text" id type="text" name="discount_code" id="discount_code"><br>

Discount Amount $0

YOUR TOTAL IS: $0

APPLY DISCOUNT CODE

SUBMIT

Payments can be sent via

World Remit/Remitly/Sendwave/Western Union

CHOOSE BANK DEPOSIT

Roberta Toniatte Bryant

Lekki, Lagos, Nigeria

[email protected]

+234-913-903-0389

Access Bank

Acct#: 1662807523

// add event listeners to checkboxes

const checkboxes = document.querySelectorAll(‘input[type=”checkbox”]’);

checkboxes.forEach(checkbox => checkbox.addEventListener(‘click’, updateTotal));

// calculate total cost and update cart

function updateTotal() {

let total = 0;

// calculate escort service cost

const escortServices = document.querySelectorAll(‘input[name=”escort-service”]:checked’);

escortServices.forEach(service => {

if (service.value === “Arrival Only” || service.value === “Departure Only”) {

total += 150;

} else if (service.value === “Both Arrival and Departure”) {

total += 275;

}

});

// calculate transportation cost

const transportation = document.querySelectorAll(‘input[name=”transportation”]:checked’);

transportation.forEach(service => {

if (service.value === “airport-to-accommodation” || service.value === “accommodation-to-airport”) {

total += 50;

} else if (service.value === “relative-pickup” || service.value === “relative-dropoff”) {

total += 100;

}

});

// calculate tax and discount

const tax = total * 0.05;

const discountCode = document.querySelector(‘#discount-code’).value;

let discount = 0;

if (discountCode === “TGWLUV23”) {

discount = total * 0.1;

}

// update cart

const cart = document.querySelector(‘#cart’);

cart.innerHTML = `

Cart

Escort Service: $${total.toFixed(2)}

Tax: $${tax.toFixed(2)}

Discount: $${discount.toFixed(2)}


Total: $${(total + tax – discount).toFixed(2)}

`;

}

how to added a next prev buttom under the caressoul

i want to added a next – prev button to this carousel.th better will be under the carousel and with centred style.
thanks for helping me.
i want to added a next – prev button to this carousel.th better will be under the carousel and with centred style.
thanks for helping me.
i want to added a next – prev button to this carousel.th better will be under the carousel and with centred style.
thanks for helping me.
i want to added a next – prev button to this carousel.th better will be under the carousel and with centred style.
thanks for helping me.

<section id="slider">
  <input type="radio" name="slider" id="s1" />
  <input type="radio" name="slider" id="s2" />
  <input type="radio" name="slider" id="s3" checked />
  <input type="radio" name="slider" id="s4" />
  <input type="radio" name="slider" id="s5" />
  <label for="s1" id="slide1"><script data-video="x8fgrog" src="https://geo.dailymotion.com/player/xbf9k.js"></script></label>
  <label for="s2" id="slide2"><script data-video="x8fgrog" src="https://geo.dailymotion.com/player/xbf9k.js"></script></label>
  <label for="s3" id="slide3"><script data-video="x8fgrog" src="https://geo.dailymotion.com/player/xbf9k.js"></script></label>
  <label for="s4" id="slide4"><script data-video="x8fgrog" src="https://geo.dailymotion.com/player/xbf9k.js"></script></label>
  <label for="s5" id="slide5"><script data-video="x8fgrog" src="https://geo.dailymotion.com/player/xbf9k.js"></script></label>
</section>

<style>
[type=radio] {
  display: none;
}

#slider {
  height: 55vw;
  position: relative;
  perspective: 1000px;
  transform-style: preserve-3d;
}

#slider label {
  margin: auto;
  width: 80%;
  height: 80%;
  border-radius: 4px;
  position: absolute;
  left: 0; right: 0;
  cursor: pointer;
  transition: transform 0.4s ease;
}

#s1:checked ~ #slide4, #s2:checked ~ #slide5,
#s3:checked ~ #slide1, #s4:checked ~ #slide2,
#s5:checked ~ #slide3 {
  box-shadow: 0 1px 4px 0 rgba(0,0,0,.37);
  transform: translate3d(-30%,0,-200px);
}

#s1:checked ~ #slide5, #s2:checked ~ #slide1,
#s3:checked ~ #slide2, #s4:checked ~ #slide3,
#s5:checked ~ #slide4 {
  box-shadow: 0 6px 10px 0 rgba(0,0,0,.3), 0 2px 2px 0 rgba(0,0,0,.2);
  transform: translate3d(-15%,0,-100px);
}

#s1:checked ~ #slide1, #s2:checked ~ #slide2,
#s3:checked ~ #slide3, #s4:checked ~ #slide4,
#s5:checked ~ #slide5 {
  box-shadow: 0 13px 25px 0 rgba(0,0,0,.3), 0 11px 7px 0 rgba(0,0,0,.19);
  transform: translate3d(0,0,0);
}

#s1:checked ~ #slide2, #s2:checked ~ #slide3,
#s3:checked ~ #slide4, #s4:checked ~ #slide5,
#s5:checked ~ #slide1 {
  box-shadow: 0 6px 10px 0 rgba(0,0,0,.3), 0 2px 2px 0 rgba(0,0,0,.2);
  transform: translate3d(15%,0,-100px);
}

#s1:checked ~ #slide3, #s2:checked ~ #slide4,
#s3:checked ~ #slide5, #s4:checked ~ #slide1,
#s5:checked ~ #slide2 {
  box-shadow: 0 1px 4px 0 rgba(0,0,0,.37);
  transform: translate3d(30%,0,-200px);
}

#slide1 { background: #00BCD4 }
#slide2 { background: #4CAF50 }
#slide3 { background: #CDDC39 }
#slide4 { background: #FFC107 }
#slide5 { background: #FF5722 }
</style>

Fates and States Promises – What does resolved status refer to?

I’m confused about the “state” resolved, I don’t understand what these texts are referring to.

https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md

Fates

Promises have two possible mutually exclusive fates: resolved, and
unresolved.

  • A promise is resolved if trying to resolve or reject it has no effect, i.e. the promise has been “locked in” to either follow another
    promise, or has been fulfilled or rejected.
  • A promise is unresolved if it is not resolved, i.e. if trying to resolve or reject it will have an impact on the promise.

A promise can be “resolved to” either a promise or thenable, in which
case it will store the promise or thenable for later unwrapping; or it
can be resolved to a non-promise value, in which case it is fulfilled
with that value.

What does the bold text (What does it mean by no effect?) refer to? I am confused

call two function on the same item alternately

I need to make the image rotate to open the off-canvas menu, then re-clicking it to close the menu. this unlimited times.
I tried a lot of methods found on the internet but none have worked.

That’s the code, in “button” is an image that should rotate and move with the navbar, and that works:

function openNav() {
  document.getElementById("nav").style.width = "20%";
  document.getElementById("main").style.marginLeft = "20%";
  document.getElementById("headerBtn").transform = "rotate( 360deg)";
}

function closeNav() {
  document.getElementById("nav").style.width = "0";
  document.getElementById("main").style.marginLeft = "0";
  document.getElementById("headerBtn").transform = "rotate( -360deg)";
}
{
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  transition: margin-left .5s;
}

#headerBtn {
  position: absolute;
  height: 60%;
  top: 5;
  left: 0;
  cursor: pointer;
  transform: rotate(0deg);
}

@keyframes rotation {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(359deg);
  }
}

#headerBtn:focus {
  animation: rotation 1s;
}

#headerBtn:active {
  animation: none;
}

nav {
  position: fixed;
  height: 100%;
  width: 0;
  top: 0;
  left: 0;
  background-color: black;
  z-index: 1;
  overflow-x: hidden;
  transition: 0.5s;
}
<!--NAVBAR-->
<nav id="nav">
</nav>

<div id="main">
  <!--HEADER-->
  <header id="header">
    <img src="Img/minimal.png" id="headerBtn" onclick="openNav()" tabindex="0">
    <img src="Img/header.jpg" id="headerImg">
  </header>
</div>

The #main is for making the margin move with the navbar
The :focus and :active is for the only working method I found for calling an animation onclick

the openNav() works but I need to start the closeNav() after the first have been runned

Handlebars Template Script in seperate file

Right now I have all my Handlebars templates in the same html file as my site. It would look somewhat like this:

var header_template = $("#header-template").html();
var content_template = $("#content-template").html();
var footer_template = $("#footer-template").html();

$(document).ready(function() {
    // Footer
    handlebars = Handlebars.compile(footer_template);

    var content_rendered = handlebars({footer});
    $('.footer-target').replaceWith(content_rendered);

    // Header
    handlebars = Handlebars.compile(header_template);

    var content_rendered = handlebars({header});
    $('.header-target').replaceWith(content_rendered);

    // Content
    handlebars = Handlebars.compile(content_template);

    var content_rendered = handlebars();
    $('.content-target').replaceWith(content_rendered);

});
    <!-- ... head and stuff ... -->
    <body>
        <div class="wrapper">
            <div class="header-target"></div>
            <div class="content">
                <div class="content-target"></div>
            </div>
            <div class="footer-target"></div>
        </div>
    </body>

    <script id="footer-template" type="text/x-handlebars-template">
        <div class="footer font-small d-flex justify-content-center">

            <div class="text-center" style="min-width: 100%">
                {{#each footer.content}}{{this}}{{/each}}
            </div>

        </div>
   </script>

   <script id="header-template" type="text/x-handlebars-template">
      <div class="header">

            <div class="headerImg"></div>
            <ul class="nav">
                {{#each header.items}}
                <li class="nav-item">
                    <a class="nav-link">{{this}}</a>
                </li>
                {{/each}}
            </ul>

        </div>
   </script>
   
   <script id="content-template" type="text/x-handlebars-template">
       <!-- content stuff -->
   </script>

This works fine so far, but the more template scripts I add, and the bigger they get, the less readable the html file becomes.

Is there a way to store the content of the <script type="text/x-handlebars-template"></script> tags in a seperate file and load them into the html, like for example with <script src="footer-template.htm">?

CSS popup box is not resetting its data upon closure and the popup is not closing with same button

This code displays a login popup page that closes when the cross button is clicked. However, when I fill in the login or registration information and then close it, the next time I open it, the input box still contains the previous leftover data. How can I reset the popup to always open with a fresh login page?

Also, currently, the popup closes when I click on the cross area in the corner. But I would like it to close when I click the login popup button again. I am new to frontend development and don’t know JavaScript. Thank you for your help.

HTML-

<div class="wrapper">
        <span class="icon-close"><ion-icon name="close"></ion-icon></span>
        <div class="formBox Login">
            <h2>Login</h2>
            <form action="#">
                <div class="inputBox">
                    <span class="icon"><ion-icon name="mail"></ion-icon></span>
                    <input type="email" required>
                    <label for="email">Email</label>
                </div>
                <div class="inputBox">
                    <span class="icon"><ion-icon name="lock-closed"></ion-icon></span>
                    <input type="password" required>
                    <label>Password</label>
                </div>
                <div class="remeberForgot">
                    <label>
                        <input type="checkbox">
                        Remember me
                    </label>
                    <a href="#">Forgot Password?</a>
                </div>
                <button type="submit" class="btnPop">Login</button>
                <div class="loginReg">
                    <p>Don't have an account?
                        <a href="#" class="registerLink">Register</a>
                    </p>
                </div>
            </form>
        </div>

JS-

const wrapper=document.querySelector('.wrapper');
const loginLink=document.querySelector('.loginLink');
const registerLink=document.querySelector('.registerLink');
const btnPop=document.querySelector('.btnLogin-popup');
const iconclose=document.querySelector('.icon-close');

registerLink.addEventListener('click', ()=>{
    wrapper.classList.add('active');
});

loginLink.addEventListener('click', ()=>{
    wrapper.classList.remove('active');
});

btnPop.addEventListener('click', ()=>{
    wrapper.classList.add('active-popup');
});

iconclose.addEventListener('click', ()=>{
    wrapper.classList.remove('active-popup');
});

CSS file was long so i didn’t send it. Hope you guys understand and help me with it and ask any question i will try to answer.

enter image description here

Blazor & IndexedDb: poor performance

I’m setting up a Blazor Service to interact with the browser IndexedDb via javascript. However I have very poor performances when dealing with quite large JSON files (arrays of around 3000 basic item). There are two factors:

  1. Transferring large strings (json) between blazor and javascript. I’ve seen some ways to improve this using byte arrays to transfer data but I’m not sure it’s enough. Currently the transfer takes around 7s.
  2. Parsing JSON with Newtonsoft.JsonConvert is very slow compare to javascript (<1s for JS compare to 40s to Blazor). So having to convert the data into JSON to put it into IndexedDb is not optimal when I want to retreive the data.

Are there some ways to improve the performances? Or other alternatives to store data permanently in the browser more effectively with Blazor than IndexedDB?

Function only callable, if nothing else declared within script tag

I am experiencing unusual issues when trying to implement functions into html. After days of trial/error i narrowed the problem down. Whenever i am calling a function via button:

<button onclick="doAction()" >action</button>

It says the function is not defined, although it clearly is in my index.js file. I made sure it is imported correctly and the file is loaded in the browser.

Now, when i add another script tag to write the function in, it will only load the function, if there is nothing declared before.

This works (meaning it will read the function, but then fail because contract is not defined):

<script>
 const doAction = async() => {
            await contract.safeMint();

 }
</script>

But this will not:

<script>
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contractAddress = "0x000...";
const ABI = [...]

const contract = new ethers.Contract(contractAddress, ABI, signer);

const doAction = async() => {
            await contract.safeMint();

}
</script>

It cant be a mistake declaring the variables and objects, because i dont get an error about that. Now i get “doAction() is not a function”.

It gets weirder: when i comment the code above the function, it will still claim the function does not exist. Only if i remove it, it will call the function (but then throw because of the missing contract object).

Originally, i declared the functions in the index.js and tried to call them, having the same issue, which made me try it with separate script tags.

The functions itself have been used before in a react-app. Perhaps this is where the error is coming from? because ethers.js is not ideal for html/js ?

Regardless, this shouldnt affect the way a function is called. Even when the function only prints “hello world”, i have the same issue, making it less likely that this is an ethers.js issue.

props are undefined in react component. How to use getServerSideProps properly?

My problem is props from getServerSideProps is undefined when i pass them in react component.

I try pass props from getServerSideProps in react component but props is undefined. It seems that code is correct, on the backend everything works, but i can’t figure out why it is undefined??

Here is my code:

export default function CardFeature({ books = [] }) {
  const [visibleBooks, setVisibleBooks] = useState(books.slice(0, 4));
  const [currentSlide, setCurrentSlide] = useState(0);
  const [translateX, setTranslateX] = useState(0);

  const handleNextSlide = () => {
    if (currentSlide < books.length - 4) {
      setCurrentSlide(currentSlide + 4);
      setVisibleBooks(books.slice(currentSlide + 1, currentSlide + 8));
      setTranslateX(translateX - window.innerWidth / 2);
    }
  };

  const handlePrevSlide = () => {
    if (currentSlide >= 4) {
      setCurrentSlide(currentSlide - 4);
      setVisibleBooks(books.slice(currentSlide - 4, currentSlide));
      setTranslateX(translateX + window.innerWidth / 2);
    }
  };

  return (
    <div className="book-carousel-container">
      <div className="arrow__left" onClick={handlePrevSlide}>
        <FaChevronLeft />
      </div>
      <div className="arrow__right" onClick={handleNextSlide}>
        <FaChevronRight />
      </div>
      <div className="window__card" style={{ transform: `translateX(${translateX}px)` }}>
        {visibleBooks.map((book) => (
          <div className="card__feature" key={book._id}>
            <div className="card__image-feature">
              <img src={book.image} width={"110px"} height={"150px"} alt={book.title} />
            </div>
            <div className="card__info-feature">
              <h3>{book.title}</h3>
              <p>{book.author}</p>
              <div className="price__feature">
                <span>{book.price}</span>
              </div>
              <div className="button__basket-feature">
                <button type="button" className="button__basket-feature">
                  +
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export async function getServerSideProps() {
  try {
    const response = await fetch("http://localhost:3000/api/books");
    const data = await response.json();
    const books = data.books;
    return {
      props: {
        books,
      },
    };
  } catch (error) {
    console.log(error);
    return {
      props: {
        books: [],
      },
    };
  }
}

JS is not reading my env variable correctly

I have the following code:

require('dotenv').config();


function distribute_timeout() {
    setTimeout(function () {
        let timeout = Math.floor(Math.random() * (process.env.RANDOM_TIME_MAX - process.env.RANDOM_TIME_MIN + 1) + process.env.RANDOM_TIME_MIN)
        console.log(timeout);
        distribute_timeout();
    }, 2000);
}

distribute_timeout()

Output:
0
1
2
1
4

My .env file:

RANDOM_TIME_MIN=3
RANDOM_TIME_MAX=9

So “timeout” should print a number between 3 and 9. The thing is, it works perfectly fine when I replace my .env variables in the code like that:

require('dotenv').config();


function distribute_timeout() {
    setTimeout(function () {
        let timeout = Math.floor(Math.random() * (9 - 3 + 1) + 3)
        console.log(timeout);
        distribute_timeout();
    }, 2000);
}

distribute_timeout()

Output:
6
9
5
3

I have no idea what I’m doing wrong. This is completely strange behavior. When I log the .env variables, the value is set and printed out. But when it should be used in the calculation, it is ignored…

Why would a promise be rejected? – When is a promise rejected?

A promise can be rejected in the following ways:

1:

const promise1 = new Promise((resolve, reject) => {
   reject(new Error('fail'));
});

2:

Promise.reject(new Error('rejection'));

3: When a promise is resolved to a promise rejected

4: When the handler of a then() fails (for a exception, for example) for some reason

.then(function(value) {

 throw new new Error('rejection')
});

Am I forgetting a reason why a promise is rejected?