Javascript syntax to add a loop variable inside another variable

I am looking to incorporate the following id variables: e1, e2, etc. into a loop.

What is the right syntax to handle the ‘#e’+i and ‘#e’+i elements, to avoid writing multiple functions eg. : $(document).on('change', '#e1', function() { and var exp = 'e1';

PS: Currently, the below on change function is not triggered.

for (var i = 0; i < 10; i++) {      
        
$(document).ready(function() {          
              $(document).on('change', '#e'+i, function() {
                if ($("#e"+i).is(":checked")) {     var chk = $('#e'+i).val(); var exp = 'e'+i; }
                else {  chk = 0 ;   var exp = 'e'+i;    }
                $.ajax({
                        url: "modify.php",
                        method: "POST",
                        data: {check: chk, experience: exp },
                  });
              });       
            })
            ;
        }       

How do I get text appear on the right side of the map when I click on a country using Javascript events?

This is the task:

Create a web page showing the map of Scandinavia on the left and a blank element on the right. Here it is a good idea to use the map as a background image in an element.
Add round – elements (Hint: border-radius) with each of the four flags and place them over the country to which they belong (Hint: position).
Add an effect when you hover the mouse pointer over a flag.
For example, you can change the arrow to a hand, and you can do something with the elements that make it clear that you are holding them over.
Add a click event to each of the flags. When a flag is clicked, a text about the country should appear in the element on the right. The text must contain information about the country, and must at least contain area, population, currency and capital.

All I have left is to get the text about the the clicked country to appear on the right side of the map.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *,*::before,*::after{
            box-sizing: border-box;
        }
        .container{
            display: flex;
        }
        
        .container>div:first-child{
            position: relative;
            height: 500px;
            width:500px;
            padding:1rem;
            background-color: #eee;
            background-image:url(./Oppgave2/Skandinavia.png);
            background-position: center;
            background-size:contain;
            background-repeat:no-repeat;
        }
        .container>div:first-child .flag{
            width: 32px;
            height: 32px;
            position:absolute;
            border-radius: 50%;
            background-color: #fff;
            padding:0.1rem;
        }
        .container>div:first-child img{
            width: 28px;
            height: 28px;
            border-radius: 50%;
            
        }

        .container>div:first-child img:hover{
            cursor:pointer;
            transform:scale(1.2);
        }
        .norway{
            top: 300px;
            left: 126px;
        } 

        .finland{
            top:234px;
            left: 350px;
        }

        .sweden{
            top:282px;
            left: 203px;
        }

        .denmark{
            top:447px;
            left: 120px;
        }
    </style>
</head>

<body>
    <div class="container">
        <div>
            <div class="flag norway" >
                <img src="./Oppgave2/Norge.png" alt="Norway">
            </div>
            <div class="flag denmark">
                 <img src="./Oppgave2/Danmark.png" alt="Denmark">
            </div>
           
            <div class="flag sweden"> 
                <img src="./Oppgave2/Sverige.png"  alt="Sweden">
            </div>

           <div class="flag finland">
               <img src="./Oppgave2/Finland.png" alt="Finland">
           </div>
            
        </div>
        <div>

        </div>
    </div>
    <script>
    </script>
</body>

</html>

All I have left is to get the text about the country I want to click to appear on the right side of the map when I click the country. So if I want to click on Norway, it should appear a text containing information about Norway on the right side of the map. The same goes for Sweden, Denmark and Finland’s flags.

Time issue with different Time zones with Node , Mongodb and React

I’m facing issues with different time zone while uploading data in MongoDB with backend as a Nodejs. So the issue is, for example when I’m uploading some data from America with Date with local UTC format (Ex: 20-Dec-2021). so from other locations like from India when I’m filtering the data on the Date: 20-Dec-2021, I’m not getting any date. how do I manage the data globally to access the uploaded date?.

And I want to understand how MongoDB stores the date in which formate.

Dropdown Select resetting to first value when navigating to URL route

Just started building my own React site after many circles of tutorials. I have a simple dropdown select that navigates to a specific route/URL when selected. However I’d like the select to stay at the URL that the user navigated to ( so when the “Ants” page is selected, the dropdown goes to “Ants” or “Bees” etc). Here’s my code. I tried a bunch of different things as well as. using “useNavigate” from Router & a few other methods to no avail. Anyone have any ideas? Thank you and sorry if this is a dumb question.

Here’s my Dropdown component code

export default function DropDown() {
  function onChange(e) {
    const url = window.location.href = `/${e.target.value}`;
  };

  return (
    <div className="select-container">
      <p> <label htmlFor="pests">Choose a pest: </label></p>
      <div class="select-dropdown">
        <select onChange={onChange}>
          <option value="ants">Ants</option>
          <option value="wasps">Wasps</option>
          <option value="mice">Mice</option>
        </select>
      </div>
    </div>
  );
}

Here’s the code from my app.js (Router)

function App() {
  return (
    <div className="main">
      <Header />
      <NavbarBasic />
      {/* These are the main routes and subpages */}
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/about' element={<About />} />
        <Route path='/pests-we-treat' element={<Pests />} />
        <Route path='/services' element={<Services />} />
        <Route path='/contact' element={<Contact />} />
        <Route path='/ants' element={<Ants />} />
        <Route path='/wasps' element={<Wasps />} />
        <Route path='/roaches' element={<Roaches />} />
        <Route path='/bedbugs' element={<Bedbugs />} />
        <Route path='/bees' element={<Bees />} />
        <Route path='/mice' element={<Mice />} />
        <Route path='/flies' element={<Flies />} />
      </Routes>
    </div>
  );
}


  return (
    <div className="select-container">
      <p> <label htmlFor="pests">Choose a pest: </label></p>
      <div class="select-dropdown">
        <select onChange={onChange}>
          <option value="ants">Ants</option>
          <option value="wasps">Wasps</option>
          <option value="mice">Mice</option>
        </select>
      </div>
    </div>
  );
}

and for posterity here’s my code with the actual Navbar

export default function NavbarBasic() {

  const Hamburger = () => {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
      x.className += " responsive";
    } else {
      x.className = "topnav";
    }
  }


  return (
    <div className="topnav" id="myTopnav">
      <NavLink to="/">Home</NavLink>
      <NavLink to="/about">About</NavLink>
      <NavLink to="/contact">Contact</NavLink>
      <NavLink to="/pests-we-treat">Pests We Treat</NavLink>

      <div className="dropdown">
        <button className="dropbtn">Pests We Treat
        <CaretDownIcon className="caret" />
        </button>

        <div className="dropdown-content">
          <a href="/ants" to="/">Ants</a>
          <a href="/bedbugs" to="/">Bedbugs</a>
          <a href="/flies" to="/">Flies</a>
          <a href="/roaches" to="/">Roaches</a>
          <a href="/wasps" to="/">Wasps</a>
        </div>
      </div>
      <a href="#" className="icon" onClick={Hamburger}>&#9776;</a>
    </div >
  )
}

How to use importScripts with quasar

I’m trying to use web worker in my project. It works fine in the dev mode but failed after build.

Uncaught DOMException: 
Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:4000/js/js/vendor.4a4f636a.js' failed to load.

The file structure is shown as follow

image

It seem that an extra “js/” is added in the link. The correct link for the script file should be http://localhost:4000/js/vendor.4a4f636a.js

To reproduce, I create a small repo.
It is strange that it works after removing the for loop in src/worker/load_data.js.

Have I done something wrong? Are there any configurations needed to make this work?

how to add Realtime audio chat between players in web based multiplayer game?

I had idea to build web based game in which players also can talk to each other.
i fond one solution for text based real time chat using deepstream server , but its currently not maintained by team so i decided to drop using deepstream server idea.

if you have any solution to share Realtime audio and chat between users (same as multiplayer games freefire etc.) in web based app or game help me out.

please make sure you are suggesting scalable solution.

Vue Carousel 3D slider not working properly

I am adding vue carousel 3d into my project. However it takes space for slider to display but cannot see slider there. I wanted to inspect and right click on it , the slider suddenly stars showing. When I refresh the page, again it disappears. I don’t know what to do and whats the problem with that. Can anyone please explain how to solve this issue? Thanks.

App.vue

<template>
  <div id="app" class="wrapper">
    <div class="box">
      <!-- <h3>Controls visible</h3> -->

      <carousel-3d :controls-visible="true">
        <slide v-for="(slide, i) in slides" :index="i" :key="i">
          <img :src="slide.src">

        </slide>
        <!-- <slide :index="0" :key="0"><p>a</p></slide>
        <slide :index="1" :key="1"><p>b</p></slide>
        <slide :index="2" :key="2"><p>c</p></slide> -->
        <!-- <slide :index="3"><p>a</p></slide> -->
      </carousel-3d>
    </div>
  </div>
</template>
<script>
import Carousel3d from "./Carousel3d.vue";
import Slide from "./Slide.vue";

const slides = [
  {
    title: 'Slide 1',
    desc: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim, maxime.',
    src: 'https://placehold.it/360x270'
  },
  {
    title: 'Slide 2',
    desc: 'Lorem ipsum dolor sit amet ',
    src: 'https://placehold.it/360x270'
  },
  {
    title: 'Slide 3',
    desc: 'abcd ',
    src: 'https://placehold.it/360x270'
  },
]

export default {
  name: 'App',
  components: {
    Carousel3d,
    Slide
  },
  data () {
    return {
      slides: slides,
      slideCount: 3
    }
  },
 }
}
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

How to customize MUI React Component?

I’m building an application in React, using React MUI Components.

In my RecipeReviewCard.js, I’ve copied the source code from MUI website.
It look’s like this:

import * as React from "react";
import { styled } from "@mui/material/styles";
import Card from "@mui/material/Card";
import CardHeader from "@mui/material/CardHeader";
import CardMedia from "@mui/material/CardMedia";
import CardContent from "@mui/material/CardContent";
import CardActions from "@mui/material/CardActions";
import Collapse from "@mui/material/Collapse";
import Avatar from "@mui/material/Avatar";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import { red } from "@mui/material/colors";
import FavoriteIcon from "@mui/icons-material/Favorite";
import ShareIcon from "@mui/icons-material/Share";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import MoreVertIcon from "@mui/icons-material/MoreVert";

const ExpandMore = styled((props) => {
  const { expand, ...other } = props;
  return <IconButton {...other} />;
})(({ theme, expand }) => ({
  transform: !expand ? "rotate(0deg)" : "rotate(180deg)",
  marginLeft: "auto",
  transition: theme.transitions.create("transform", {
    duration: theme.transitions.duration.shortest,
  }),
}));

export default function RecipeReviewCard() {
  const [expanded, setExpanded] = React.useState(false);

  const handleExpandClick = () => {
    setExpanded(!expanded);
  };

  return (
    <Card sx={{ maxWidth: 345 }}>
      <CardHeader
        avatar={
          <Avatar sx={{ bgcolor: red[500] }} aria-label="recipe">
            R
          </Avatar>
        }
        action={
          <IconButton aria-label="settings">
            <MoreVertIcon />
          </IconButton>
        }
        title="Shrimp and Chorizo Paella"
        subheader="September 14, 2016"
      />
      <CardMedia
        component="img"
        height="194"
        image="/static/images/cards/paella.jpg"
        alt="Paella dish"
      />
      <CardContent>
        <Typography variant="body2" color="text.secondary">
          This impressive paella is a perfect party dish and a fun meal to cook
          together with your guests. Add 1 cup of frozen peas along with the
          mussels, if you like.
        </Typography>
      </CardContent>
      <CardActions disableSpacing>
        <IconButton aria-label="add to favorites">
          <FavoriteIcon />
        </IconButton>
        <IconButton aria-label="share">
          <ShareIcon />
        </IconButton>
        <ExpandMore
          expand={expanded}
          onClick={handleExpandClick}
          aria-expanded={expanded}
          aria-label="show more"
        >
          <ExpandMoreIcon />
        </ExpandMore>
      </CardActions>
      <Collapse in={expanded} timeout="auto" unmountOnExit>
        <CardContent>
          <Typography paragraph>Method:</Typography>
          <Typography paragraph>
            Heat 1/2 cup of the broth in a pot until simmering, add saffron and
            set aside for 10 minutes.
          </Typography>
          <Typography paragraph>
            Heat oil in a (14- to 16-inch) paella pan or a large, deep skillet
            over medium-high heat. Add chicken, shrimp and chorizo, and cook,
            stirring occasionally until lightly browned, 6 to 8 minutes.
            Transfer shrimp to a large plate and set aside, leaving chicken and
            chorizo in the pan. Add pimentón, bay leaves, garlic, tomatoes,
            onion, salt and pepper, and cook, stirring often until thickened and
            fragrant, about 10 minutes. Add saffron broth and remaining 4 1/2
            cups chicken broth; bring to a boil.
          </Typography>
          <Typography paragraph>
            Add rice and stir very gently to distribute. Top with artichokes and
            peppers, and cook without stirring, until most of the liquid is
            absorbed, 15 to 18 minutes. Reduce heat to medium-low, add reserved
            shrimp and mussels, tucking them down into the rice, and cook again
            without stirring, until mussels have opened and rice is just tender,
            5 to 7 minutes more. (Discard any mussels that don’t open.)
          </Typography>
          <Typography>
            Set aside off of the heat to let rest for 10 minutes, and then
            serve.
          </Typography>
        </CardContent>
      </Collapse>
    </Card>
  );
}

Then, In my UserPanel.js component, I’m importing this component.

const UserPanel = () => {
  let history = useHistory();

  useEffect(() => {
    let authToken = sessionStorage.getItem("AuthToken");

    if (authToken) {
      history.push("/userpanel");
    }

    if (!authToken) {
      history.push("/login");
    }
  }, []);

  const handleLogout = () => {
    sessionStorage.removeItem("AuthToken");
    history.push("/login");
  };

  return (
    <>
      {/* <Sidebar /> */}
      <RecipeReviewCard></RecipeReviewCard>
    </>
  );
};

export default UserPanel;

Is there any way to customize for example the text placed in in my UserPanel.js component via props?
Or any diffrent element from MUI Component?
Without creating and duplicating the MUI component?

How to prevent an eventListner for the first time on pageLoad In JS

i have used preventDefault() but thats not working
here is My Code

btnBookNameSearch.addEventListener("click", (e) => {
    e.preventDefault();
    const searchValue = btnBookNameSearch.value.toLowerCase().trim();
 
    allPgBooks.forEach((product) => {
        if (product.name == searchValue) {
            allPgBooksE2.innerHTML = '';
            if (allPgBooksE2) { 

there is a mistake i am doing in the first two line of code above but idk how to fixenter image description here

Puppeteer screenshot ignoring parameters

I am creating a function on AWS Lambda to take screenshots of websites and save the resulting image to S3. The function is successfully creating a screenshot and saving to S3, however it is ignoring the parameters given to the page.screenshot() function and just using defaults.

const chromium = require('chrome-aws-lambda');
const aws = require('aws-sdk');

var s3 = new aws.S3();

exports.handler = async (event, context, callback) => {
  let result = null;
  let resultKey = null;
  let browser = null;

  try {
    resultKey = event.url.replace(/[W_]+/g,"_") + '.png';
    
    browser = await chromium.puppeteer.launch({
      args: chromium.args,
      defaultViewport: chromium.defaultViewport,
      executablePath: await chromium.executablePath,
      headless: chromium.headless,
      ignoreHTTPSErrors: true,
    });

    let page = await browser.newPage();

    await page.goto(event.url || 'https://example.com');

    result = await page.screenshot({
      type: 'jpeg',
      fullpage: true
    });
    
     // Image ready. Send to S3
     var params = {
       Bucket: 'mybucket',
       Key: resultKey,
       Body: result
      };
      s3.putObject(params, function(err, data) {
        if (err) {
          console.error(err, err.stack);
        } else {
          console.log(data);
        }
      });
  } catch (error) {
    return callback(error);
  } finally {
    if (browser !== null) {
      await browser.close();
    }
  }

  return callback(null, result);
};

So the image created ignores the type and fullpage parameters, and creates a .png image that is not fullpage.

What am I doing wrong?

Reload a wordpress page with javascript

I need to build a charts with chartjs library.

I’ve got a strange behavior with firefox : the charts behaves randomly :

  • sometimes it’s OK and sometimes I need to click several time on my button

is anyone know a method in javascript to force the reload via a simple button like this? :

<a href="javascript:window.location.reload(true)" class="refresh">Refresh the page</a>

Call a classes function from within window scope

I have a simple class,

class TestClass {
   init() {
       this.loadGoogle();
   }
   
   initializeSearch() {
       alert("here");
   }
   
   loadGoogle() {
       const script = document.createElement('script');
        script.src = 'https://maps.googleapis.com/maps/api/js?key={MY_KEY}&libraries=places&callback=initMap';
        script.async = true;

        window.initMap = () => {
        //JS API IS LOADED
            this.initializeSearch();
        };

        document.head.append(script);
   }
}

I am having trouoble calling the intializeSearch method when the callback is fired. I am assuming it’s because this is out of scope? Can I bring this into the scope of the window global?

Passing props via spread operator in React

Using React I have a component that I need to pass an ‘id’ prop to render an id on the html anchor. Starting at the lowest return level for this anchor point and working up we have:

// links.jsx
export const myLink = ({children, location, ...props}) => {
  const href = "mydomain.com" + location;
  return (
    <a href={href} {...props}>{children}</a>
  )
}

//components.jsx
export const Block = ({linkLocation, htmlId, children, externalLink: isExternalLink}) => {
  const EditLink = isExternalLink ? Link1 : Link2;
  return <div className="outer-div">
    <div className="inner-div">
      {children}
    </div>
 
    <EditLink location={editLocation} id={htmlId}>{translate('edit')}</EditLink>
  </div>
}

export const Summary = ({info1, info2, info3}) => {
  return <SummaryBlock htmlId={'i-am-id-' + info2}>
    <div>{info1}</div>
    <div>{info2}</div>
    <div>{info3}</div>
  </SummaryBlock>
}

That htmlId is what I’m seeking to pass up to myLink to assign the anchor’s id attribute yet on page render it doesn’t appear. Is it because id’s are protected/special? Do I need to assign the spread operator on props to the EditLink component? Am I missing a passing point somewhere? I’m especially confused because similar questions show the spread operator as being just the right thing to do what I’m seeking.

Guidance would be much appreciated!

Webpack 5 & Vue 3 – CSS Tree Shake

I’m developing a UI component library using Vue 3, SCSS and Webpack 5. The library consists of serval components (button, input, form etc) having a scoped SCSS each.

After installing the library in my main project (also built with Vue 3 & Webpack 5), I’m importing only a single component (button) into it. However, after the build finished (CSS build) I see other components’s CSS are included in the build as well. I should mention The JS tree shaking do working.

I want to reduce my bundle size to include only the CSS of the imported components.

An example for button component in my build file:

var script$4 = defineComponent({
    name: "SButton",
    props: {
        stype: {
            type: String,
            default: "primary"
        },
        type: {
            type: String,
            default: "button"
        }
    }
});

const _withId$4 = /*#__PURE__*/withScopeId("data-v-7a74475b");

const render$4 = /*#__PURE__*/_withId$4((_ctx, _cache, $props, $setup, $data, $options) => {
  return (openBlock(), createBlock("button", {
    class: ["s-button", _ctx.stype],
    type: _ctx.type
  }, [
    renderSlot(_ctx.$slots, "default")
  ], 10 /* CLASS, PROPS */, ["type"]))
});

var css_248z$6 = "html {n  --sbutton-general-icon-padding: 9px;n  --sbutton-general-icon-width: 36px;n  --sbutton-general-icon-height: 36px;n  --sbutton-width: 100%;n  --sbutton-min-height: 56px;n  --sbutton-line-height: 32px;n}n@media (min-width: 992px) {n  html {n    --sbutton-general-icon-padding: 7px;n    --sbutton-general-icon-width: 32px;n    --sbutton-general-icon-height: 32px;n    --sbutton-width: auto;n    --sbutton-min-height: 46px;n    --sbutton-line-height: 22px;n  }n}";
styleInject(css_248z$6);