How can i optimise this JS code to avoid the repetition of assigning different API values to different element?

So I am kinda new to JS and I have been trying to fetch data from the API server but as you can see each currency element is assigned to a different coin value.


const container=document.querySelector(".scoll_display");
const currency=container.querySelectorAll(".Exchange_rate");

async function getExchangePrice() {
    const options = {
      method: "GET",
      headers: { "x-cg-demo-api-key": "CG-NhdhrCZRnCSqdjMyf3XUu9k4" },
    };
  
    try {
        const response1= await fetch("https://api.coingecko.com/api/v3/exchange_rates", options);
        const data1 = await response1.json();
        
        currency[1].innerHTML=`(ETH) ${data1.rates.eth.value}`;
        currency[2].innerHTML=`(LTC) ${data1.rates.ltc.value}`;
        currency[3].innerHTML=`(BCH) ${data1.rates.bch.value}`;
        currency[4].innerHTML=`(BNB) ${data1.rates.bnb.value}`;
        currency[5].innerHTML=`(XLM) ${data1.rates.xlm.value}`;
        currency[6].innerHTML=`(DOT) ${data1.rates.dot.value}`;
        currency[7].innerHTML=`(₹) ${data1.rates.inr.value}`;
        currency[8].innerHTML=`(¥) ${data1.rates.jpy.value}`;
        currency[9].innerHTML=`(μBTC) ${data1.rates.bits.value}`;
        currency[10].innerHTML=`(£) ${data1.rates.gbp.value}`; 
      
    } catch (error) {
      console.error(error);
    }
  }
  
  getExchangePrice();

calendar keeps showing the wrong time

I am trying to fix the timezones for the calendar. It sends to the django server the times as an ISO format with the offsets as the timezone that the user selects at the dropdown menu and saves it. It is saved in the server correctly. But upon loading it into the calendar, it seems to interpret it as actually 5 hours ahead (America/Chicago CST time) instead of the time format as 00:00:00 that was input originally. And yes the offset is -5.

I’ve already tried removing the timeZone option in the fullcalendar variable and that didn’t do anything.

#calendar.html

var calendar = $("#calendar").fullCalendar({
          // timeZone: $("#id_timezone").val(),
          timeZone: "UTC", #UTC is just for testing purposes
          header: {
            left: "prev,next today",
            center: "title",
            right: "month,agendaWeek,agendaDay",
          },
          events: "/all_events",
          selectable: true,
          selectHelper: true,
          editable: true,
          eventLimit: true,
          eventDurationEditable: true,

          select: function (start, end, allDay) {
            var title = prompt("Enter Event Title");
            if (title) {
              var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
              var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
              $.ajax({
                type: "GET",
                url: "/add_event",
                data: {
                  title: title,
                  start: start,
                  end: end,
                  timezone: $("#id_timezone").val(),
                },
                dataType: "json",
                success: function (data) {
                  calendar.fullCalendar("refetchEvents");
                  alert("Added Successfully " + start);
                },
                error: function (data) {
                  alert(
                    "There is a problem!!! " + start + $("#timezone").val()
                  );
                },
              });
            }
          },
          eventResize: function (event) {
            var start = $.fullCalendar.formatDate(
              event.start,
              "Y-MM-DD HH:mm:ss"
            );
            var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
            var title = event.title;
            var id = event.id;
            $.ajax({
              type: "GET",
              url: "/update",
              data: {
                title: title,
                start: start,
                end: end,
                id: id,
                timezone: $("#id_timezone").val(),
              },
              dataType: "json",
              success: function (data) {
                calendar.fullCalendar("refetchEvents");
                alert("Event Update");
              },
              error: function (data) {
                alert("There is a problem!!!");
              },
            });
          },

          eventDrop: function (event) {
            var start = $.fullCalendar.formatDate(
              event.start,
              "Y-MM-DD HH:mm:ss"
            );
            var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
            var title = event.title;
            var id = event.id;
            $.ajax({
              type: "GET",
              url: "/update",
              data: {
                title: title,
                start: start,
                end: end,
                id: id,
                timezone: $("#id_timezone").val(),
              },
              dataType: "json",
              success: function (data) {
                calendar.fullCalendar("refetchEvents");
                alert("Event Update");
              },
              error: function (data) {
                alert("There is a problem!!!");
              },
            });
          },

          eventClick: function (event) {
            $("#eventModal").modal("show");
            $("#modalTitle").val(event.title);
            const dayStart = $.fullCalendar.formatDate(event.start, "Y-MM-DD");
            const dayEnd = $.fullCalendar.formatDate(event.end, "Y-MM-DD");
            var timeStart = $.fullCalendar.formatDate(event.start, "HH:mm:ss");
            var timeEnd = $.fullCalendar.formatDate(event.start, "HH:mm:ss");
            $("#dayStart").val(dayStart);
            $("#dayEnd").val(dayEnd);
            $("timeStart").val(timeStart);
            $("timeEnd").val(timeEnd);
            $("#desc").val(event.desc);
            $("#saveEvent").on("click", function () {
              var id = event.id;
              $.ajax({
                type: "GET",
                url: "/updateEvent",
                data: {
                  id: id,
                  title: $("#modalTitle").val(),
                  dayStart: $("#dayStart").val(),
                  dayEnd: $("#dayEnd").val(),
                  timeStart: $("#timeStart").val(),
                  timeEnd: $("#timeEnd").val(),
                  desc: $("#desc").val(),
                  timezone: $("#id_timezone").val(),
                },
                dataType: "json",
                success: function (id) {
                  calendar.fullCalendar("refetchEvents");
                  alert("Event Updated");
                },
                error: function (data) {
                  alert("There is a problem!!! " + id);
                },
              });
            });

            $("#removeBtn").on("click", function () {
              var id = event.id;
              $.ajax({
                type: "GET",
                url: "/remove",
                data: { id: id },
                dataType: "json",
                success: function (data) {
                  calendar.fullCalendar("refetchEvents");
                  alert("Event Removed");
                },
                error: function (data) {
                  alert("There is a problem!!!");
                },
              });
            });
          },
        });
#views.py

def all_events(request):
    user = request.user.id                                                                                                 
    user_events = Events.objects.filter(user=user)   
    program_events = Events.objects.filter(user__isnull=True)                                                                                 
    out = []                 
    tz = afbUsers.objects.get(pk=user)
    timezone = pytz.timezone(tz.timezone)                                                                                            
    for event in user_events:    
        # start = event.start.strftime('%Y-%m-%d %H:%M:%S')
        # print(start)
        # start = parser.parse(start)
        # start =  start.astimezone(timezone) 
        # print(start)
        # end = event.end.strftime('%Y-%m-%d %H:%M:%S')
        # end = parser.parse(end)
        # end =  end.astimezone(timezone)                                                                                 
        out.append({                                                                                                     
            'title': event.name,                                                                                         
            'id': event.id,                                                                                              
            'start': event.start.strftime("%m/%d/%Y, %H:%M:%S"),                                                         
            'end': event.end.strftime("%m/%d/%Y, %H:%M:%S"),                                                             
        })          
    # for event in program_events:  
    #     start = event.start 
    #     start =  start.astimezone(utc_timezone)  
    #     end = event.end
    #     end =  end.astimezone(utc_timezone)                                                                                           
    #     out.append({                                                                                                     
    #         'title': event.name,                                                                                         
    #         'id': event.id,                                                                                              
    #         'start': start.strftime("%m/%d/%Y, %H:%M:%S"),                                                         
    #         'end': end.strftime("%m/%d/%Y, %H:%M:%S"),                                                             
    #     })                                                                                                         

                                                                       
    return JsonResponse(out, safe=False) 

Can someone help me understand what the problem here is and possible solutions?

I”m still new to JS and localStorage and I’m trying to understand it better. I am trying to be able to take 2 inputs from the user and when a button is clicked it displays those values (sort of like a todo list). I’m trying to implement localStorage and I’m able to save the key/value pair but I can’t seem to display them properly. I’m able to click the button and display the values the first time I do it but the second click gives me a “Unexpected non-whitespace character after JSON at position 24 (line 1 column 25)” console message after.

Can someone help me understand what the problem is?
My goal is figure out how to display multiple items stored in a object.

Here is my code

HTML

<body>
    
    <div class="container">
        <input type="text" class="inputField">
        <input type="text" class="inputFieldTwo">
        <button id="btn">Click</button>

        <div class="sample">
            
        </div>

        
    </div>
    
    <script src="main.js"></script>
</body>

JS

const userInput = document.querySelector(".inputField");
const userInputTwo = document.querySelector(".inputFieldTwo");
const button = document.querySelector("#btn");
const contain = document.querySelector('.sample');

let arr = [];


button.addEventListener("click", () => {
    let thisObj = {
        user: `${userInput.value}`,
        num: `${userInputTwo.value}`
    }

    let strObj = JSON.stringify(thisObj);
 
    arr.push(strObj)

    localStorage.setItem("data", arr)

    let parseObj = JSON.parse(arr);

    for (let i = 0; i < arr.length; i++) {
        let input = document.createElement("input");
        let inputTwo = document.createElement("input");
        input.type = "text";
        inputTwo.type = "number";

        input.value = parseObj.user
        inputTwo.value = parseObj.num
 
        localStorage.setItem("data", JSON.stringify(arr));

        contain.appendChild(input);
        contain.appendChild(inputTwo);
        return
    }
})

ag-grid export removes leading zeros

following is the function i have used for exporting file:
excelStyles: [
{
id: ‘header’,
interior: {
color: ‘#aaaaaa’,
pattern: ‘Solid’,
},
},
{
id: ‘body’,
dataType : ‘string’,
interior: {
color: ‘#dddddd’,
pattern: ‘Solid’,
},
},
]

function exportToExcel (){
var sheetNameVal = “Btest”;

    var params = {
            skipPinnedTop : false,
            sheetName :      sheetNameVal
    }
    params.processCellCallback = function(params) {
        var val = params.value ;
        if(/^d+$/.test(val))
            val = " "+val;
        else if(params.column.colDef.dataType=="Date/Time"){
            if(val)
                val = val.length>10 ? val.substring(0,10) : val;
        }else if(!_.isEmpty(params.column.colDef.refData)){
            val = params.column.colDef.refData[val];
        }
        if((params.column.colDef.field).includes("_TRX_AMT")){
            var trxCurr = params.node.data.TRX_CURRENCY ;
            val = FormatCurrency2(val,trxCurr);
        }
        return val;
    };
    gridOptions.api.exportDataAsExcel(params);
}

now if suppose one of my cell has value = ‘000000180’ when i export it to excel the value is changed to 180. i have tried converting it to string using val = ” “+val but somehow it didn’t work.

Mongoose post hook limbo when saving with await

I’m creating a post hook to create a slug after the a Post has been save. When I try and use Postman the check my result, the process go into limbo (no data was returned).I am using [email protected].

Code for the post hook:

PostsSchema.post("save", async function (doc, next) {
  try {
    doc.postSlug = slugify(doc.postTitle, { lower: true });
    await doc.save();
    return next();
  } catch (err) {
    console.log("inside catch method");
    return next(createError(500, err.message));
  }
});

Code for the route I use:

module.exports.createPost = async (req, res, next) => {
  const { postTitle, postContent, postAuthor } = req.body;
  try {
    // check if author exist
    const authorExist = await AccountsModel.findById(postAuthor);
    if (!authorExist) {
      return next(createError(404, `Author ID: ${postAuthor} Not Found`));
    }
    // create post
    console.log("route 1")
    const postNew = new PostsModel({
      postTitle: postTitle,
      postContent: postContent,
      postAuthor: postAuthor,
    });
    await postNew.save();
    // populate data for return
    let postCreated = await postNew.populate("postAuthor");
    return res.status(200).json({
      code: 1,
      success: true,
      message: "New Post Created",
      data: postCreated,
    });
  } catch (error) {
    return next(createError(500, error.message));
  }
};

I did fix this by removing the await in front of the doc.save():

PostsSchema.post("save", async function (doc, next) {
  try {
    doc.postSlug = slugify(doc.postTitle, { lower: true });
    doc.save();
    return next();
  } catch (err) {
    console.log("inside catch method");
    return next(createError(500, err.message));
  }
});

But found some other post what have await and the answers indicate that it is not the problem:

So, I am wondering is it the await that break the process or something else?

Change Badge Color In JS By Value

I’m new in javascript. I try to make the badge color change according to the value. I’ve tried but the output is error badge

<th>
                            <select class="select2-placeholder form-control" id="sIsLocked">
                                <option value="">Pilih</option>
                                <option value="false">Un Locked</option>
                                <option value="true">Locked</option>
                                    
                            </select>
                        </th>`your text`
                            render: function (data, type, row, meta) {
                                switch (data) {
                                    case false:
                                        return '<span class="badge bg-success">Un Locked</span>';
                                    case true:
                                        return '<span class="badge rounded-pill bg-secondary">Locked</span>';
                                    default:
                                        return '<span class="badge badge-danger badge-pill">Error!</span>';
                                        
                                }
                            }

Is the meatamask API incompatible with tron chains?

Why am I able to transfer USDT using the Metamask interface standard, but not on the tron chain? They are all managed in the same wallet, do I need to do different API docking? What is the difference between TRC20 and ERC20? Is it true?

I have read the official Meatamask API and implemented USDT transfer. I hope to make USDT transfers through the tron chain as well.

Array iteration management [closed]

I am trying to do an iteration to an array to validate data, The problem is that when I do the if(){}else{} For validation, the if is executed as else, both.

what I’m trying to do is, validate data to prevent repeated data from being inserted

  const myData = [
     {id: "001", nombre: "pedro",   apellido: "mejia",   codigo: "0012325", estado: "Activo"},
     {id: "002", nombre: "gristan", apellido: "smill",   codigo: "0022325", estado: "Activo"},
     {id: "003", nombre: "marco",   apellido: "rosario", codigo: "0032325", estado: "Desativado"},
     {id: "004", nombre: "juan",    apellido: "vergobe", codigo: "0042325", estado: "Activo"},
     {id: "005", nombre: "salomon", apellido: "mende",   codigo: "0052325", estado: "Desativado"},
  ]
var myclick = false;
  for (let index = 0; index < myData.length; index++) {
    const element = myData[index];
    var resultadoArray = element.id;
   if(myclick == false){
     if(resultadoArray != "003"){
          console.log('true');
          myclick = true;
        }else{
          console.log('fase');
          myclick = true;
      }
    }
  }

Swiperjs breakpoints doesn’t apply when reach the breakpoints

I’m using swiperjs and I want to make the swiper responsive by using breakpoints property. However, the default value of slidesPerView the isn’t applied when the screen reaches a smaller value than breakpoint. When I test in a separate html file, the breakpoints work fine but not in my laravel project. I’m using cdn as the source for swiper, here’s my code:

My js to initialize the swiper

var swiper = new Swiper('.history-swiper', {
    // Optional parameters
    slidesPerView: 2,
    spaceBetween: 10,

    breakpoints: {
        975: {
            slidesPerView: 2
        }
    },
  
    // If we need pagination
    pagination: {
      el: '.swiper-pagination',
      clickable: true,
    },
  
    // Navigation arrows
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
  
    // And if we need scrollbar
});

var swiper_index = new Swiper('.index-swiper', {
    // Optional parameters
    slidesPerView: 2,
    spaceBetween: 10,

    breakpoints: {
        975: {
            slidesPerView: 3,
            spaceBetween: 20,
        }
    },

    // If we need pagination
    pagination: {
        el: '.swiper-pagination',
    },

    // Navigation arrows
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    },

    // And if we need scrollbar
});

my HTML for the swiper which have some cards as the swiper items

<div class="swiper index-swiper">
            <!-- Additional required wrapper -->
            <div class="swiper-wrapper">
              <!-- Slides -->
                <div class="swiper-slide">
                    <div class="card">
                        <div class="img-wrapper">
                            <img src="{{ asset('photos/anh1.jpeg') }}" class="card-img-top" alt="...">
                        </div>
                        <div class="card-body">
                              <h5 class="card-title">Dịch vụ chăm sóc sức khỏe A</h5>
                              <p class="card-text">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quae consectetur culpa quam nisi. Blanditiis sed officiis, corporis ullam maiores, magnam aperiam qui quasi amet eveniet quia quas cumque error dolore!
                            </p>
                              <a href="#" class="fw-bold">Xem chi tiết</a>
                        </div>
                    </div>
                </div>

                <div class="swiper-slide">
                    <div class="card">
                        <div class="img-wrapper">
                            <img src="{{ asset('photos/anh1.jpeg') }}" class="card-img-top" alt="...">
                        </div>
                        <div class="card-body">
                            <h5 class="card-title">Dịch vụ chăm sóc sức khỏe A</h5>
                            <p class="card-text">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Explicabo mollitia sapiente et dicta fuga quaerat accusantium, omnis eligendi dolorem fugit facere dolores recusandae ea quisquam vero voluptatem reprehenderit? Libero, natus.
                            </p>
                            <a href="#" class="fw-bold">Xem chi tiết</a>
                        </div>
                    </div>
                </div>

                <div class="swiper-slide">
                    <div class="card">
                        <div class="img-wrapper">
                            <img src="{{ asset('photos/anh1.jpeg') }}" class="card-img-top" alt="...">
                        </div>
                        <div class="card-body">
                            <h5 class="card-title">Dịch vụ chăm sóc sức khỏe A</h5>
                            <p class="card-text">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Explicabo mollitia sapiente et dicta fuga quaerat accusantium, omnis eligendi dolorem fugit facere dolores recusandae ea quisquam vero voluptatem reprehenderit? Libero, natus.
                            </p>
                            <a href="#" class="fw-bold">Xem chi tiết</a>
                        </div>
                    </div>
                </div>

                <div class="swiper-slide">
                    <div class="card">
                        <div class="img-wrapper">
                            <img src="{{ asset('photos/anh1.jpeg') }}" class="card-img-top" alt="...">
                        </div>
                        <div class="card-body">
                              <h5 class="card-title">Dịch vụ chăm sóc sức khỏe A</h5>
                              <p class="card-text">Dịch vụ này mang đến rất nhiều những tư vấn hữu ích cho sức khỏe của khách hàng....Hơn nữa Khách hàng còn được trải nghiệmrất nhiều những tiện ích khác nữa...
                            </p>
                              <a href="#" class="fw-bold">Xem chi tiết</a>
                        </div>
                    </div>
                </div>
            </div>

            <div class="swiper-button-prev"></div>
            <div class="swiper-button-next"></div>

        </div> 

Here’s my css for cards and swiper

.card{
    margin: 0 .5em;
    box-shadow: 2px 6px 8px 0 rgba(22, 22, 26, 0.18);
    border: none;
}

.card .img-wrapper {
    max-width: 100%;
    height: 13em;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}

img{
    max-height: 100%;
}

.carousel-custom{
    max-width: 945px;;
}

.card-img-top{
    object-fit: none;
}

.card-text {
    display: -webkit-box;
    -webkit-line-clamp: 3; /* Number of lines to display before cutting off text */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

.swiper {
    width: 100%;
    height: fit-content;
    padding: 0 10px 10px 0px;
}

.swiper-slide{
    width: fit-content;
}

.history-swiper > .swiper-wrapper{
    padding: 24px 0 24px 0;
}   

Unable to properly change one variable and access it in another JS File

I’m creating a variable called current to store what button was just clicked. Then I want to use that info in another JS File when loading up a new HTML page. However, current still remains as “my_null”. I’m assuming it’s still my_null because when file2 creates the new page, the problem_type_title displays “my_null”

I expected current to change to the value that I passed in based on which button was clicked. I ordered the JS Files correctly in my HTML files when using . I know the variable is being passed through files as problem_type is “my_null” and not undefined. However, it shouldn’t be “my_null” and should be “Geometry” for example.

Here is file 1

const geo = document.getElementById('geo');
const algebra = document.getElementById('alegbra');
const centroid = document.getElementById('centroid');
const angle_bisector = document.getElementById('angle_bisector');
const two_pole = document.getElementById('two_pole');
const herons = document.getElementById('herons');
const x_intercept = document.getElementById('x_intercept');
const inverse_functions = document.getElementById('inverse_functions');
const challenge = document.getElementById('challenge');
var current = 'my_null';

geo.addEventListener('click', () => {update_curr('Geometry')});
alegbra.addEventListener('click', () => {update_curr('Alegbra')});
centroid.addEventListener('click', () => {update_curr('Centroid')});
angle_bisector.addEventListener('click', () => {update_curr('Angle Bisector')});
two_pole.addEventListener('click', () => {update_curr('Two Pole')});
herons.addEventListener('click', () => {update_curr("Heron's Formula")});
x_intercept.addEventListener('click', () => {update_curr('X-intercept')});
inverse_functions.addEventListener('click', () => {update_curr('Inverse Functions')});
challenge.addEventListener('click', () => {update_curr('Challenge Problems')});


function update_curr(clicked) {
    current = clicked;
}

Here is file 2

// Deleted code before this function for readability
async function update(url){
  // Setting value of current as a variable in this function
  let problem_type = current;
  let id = await set_problem(url);
  url = url + "challenges/" + id;
  console.log(url);
  console.log("id = " + id)
  fetch(url).then(res => res.json())
  .then(function(problem) {
      console.log(problem);
      img = problem.img;
      answer = problem.answer;
      div_main = document.createElement('div');
      div_main.innerHTML = `
        <div class='trainer_area' id='trainer_area'>
            <div class='problem_type_title'>
                // Accessing the variable
                ${problem_type}
            </div>
       // More code that doesn't matter

Activating TOAST messages via _POST / _GET (mdl)

After successful or unsuccessful execution of a PHP script, i want to display the execution result on the site in the form of a pop-up notification. How can I do this better?
Let’s say I pass the result via _GET or _POST
Is it possible to use a toast for this, something like:

if (isset $_POST['message']) {
$message = $_POST['message'];
showmessage("$message");
}

I know that in PHP there is no such thing as ShowMessage, but I’m not very strong in JS.

How to make html hover over image

Ive been trying to fix my code for ages no matter how much i hover over the hamburger menu image the cursor just woudnt change:

    <div class="header">
        <nav>
            <h1 class="nav1">CEA</h1>
            <h1 class="line"></h1>
            
        </nav>
        <nav class="nav">
            <div class="nav-left "> <!--active-->
                
                <ul>
                    <li class="nav-link"> <a class="large" href="#">About</a></li>
                    <li class="nav-link"> <a class="large" href="#">Our Work</a></li>
                    <li class="nav-link"> <a class="large" href="#">Contact</a></li>
                    <li class="nav-link"> <a class="small" href="#">Web Design</a></li>
                    <li class="nav-link"> <a class="small" href="#">eCommerce</a></li>
                    <li class="nav-link"> <a class="small" href="#">Blog</a></li>
                </ul>
                    <div class="contact">
                        <p class="large">Get in touch</p>
                        <p class="small">0302101290391</p>
                        <p class="small">[email protected]</p>
                    </div>  
            </div>
            <div class="nav-right "> <!--active-->
                
            </div>
            <img src="Imagesmenu.png" alt="menu" class="menu" style="z-index: 10;">
        </nav>

        
    </div>

my css:

.header{
    height: 110px;
}

.menu{
    display: inline;
    height: 80px;
    position: fixed;
    top: 8px;
    right: 48px;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    transition: 0.5;
}

idk if my js is affectign this code but heres my js:

const menuTog = document.querySelector(".menu");
const nav = document.querySelector(".nav");
const navLeft = document.querySelector(".nav-left");
const navRight = document.querySelector(".nav-right");
const navLinks = Array.from(document.querySelectorAll(".nav-links"));
const contact = document.querySelector('.contact');
const logo = document.querySelector('.logo');

menuTog.addEventListener('click', () => {
    menuTog.classList.toggle('active');
    nav.classList.toggle('active');
    navLeft.classList.toggle('active');
    navRight.classList.toggle('active');
    logo.classList.toggle('active');

    contact.classList.remove('active');
    navRight.classList.remove('active');

    if (menuTog.classList.contains('active')) {
        setTimeout(() => {
            navRight.classList.add('active');
        }, 100)
    }
});

I already addded pointer cursor in the div but it still woudnt work. I already added the .menu:hover but it still woudnt work idk whats wrong with my code if theres someone out there that could help me than please do thank you.

Function that returns object with same keys as the input object

I attempt to write a function fn() with the following properties:

  1. Takes a single argument x which is an object with optional keys “a” and “b” (for simplicity, each field may be numeric)
  2. It outputs a new object with the same keys as provided in the input object but each field is a specific class (a->A, b->B), i.e. the desired behavior is:
  • if I call fn({a: 1, b: 1}) I receive {a: A, b: B}
  • if I call fn({b:1}) I receive {b: B} and
  • if I call fn({}) I receive {}.

You can take the numeric values in the input object as initialization values for the classes in the output object. Also, new fields “c”, “d”, “e”, … may be added later to this function.

I struggle to set this up on the type level but also in the JS code. I have written the following code which raises Typescript errors:

  • Type ‘string’ is not assignable to type ‘keyof OutputObject’.ts(2344)
  • Type ‘Partial’ is not assignable to type ‘Pick<OutputObject, K>’.ts(2322)
class A {}
class B {} 

interface InputObject {
a: number,
b: number
}

interface OutputObject {
a: A,
b: B
}

// My failed attempt at writing fn()

const fn = <
    TObj extends Partial<InputObject>,
    K extends keyof TObj
>(x: TObj): Pick<OutputObject, K> => {

    let returnValue: Partial<OutputObject> = {}

    if (x.a) {
        returnValue.a = new A()
    }

    if (x.b) {
        returnValue.b = new B()
    }

    return returnValue
}

How do I stop website from caching? Is it at all possible?

I am making a website that needs to be able to be updated about once a day or so. Whenever I update the htdocs, it doesn’t update because the website is cached into the device (which means it can take days sometimes for it to update), is there a way to stop this without server side code? If so then how? If I go into icognito mode it works fine though.

I saw a couple other questions saying to use <meta http-equiv="cache-control" content="no-cache" />, but this doesn’t seem to quite work.

Sorry if this is a dumb question… I don’t do web dev.

I have a website, and I updated it. Now it doesn’t update for a while…