Javascript React Day Picker

so I want to pick today’s date, and then display the next 7 days. do not display weekends but count weekends into the 7.

For example: today is 3/8, which is a Tuesday,
so will display 3/9, 3/10, 3/11, (here skipping 3/12 and 3/13 as weekends), 3/14

so including 3/8 altogether 7 days but do not display weekends.

fix hotspot image on screen

i changed the display of hotspots but I want to fix the hotspots location on the screen rather than on the photo. I want hotspots to follow the screen when I navigate through the panoramic view can i do this ?
I want to give perspective to hotspots my goal is to get hotspots more flat on the ground

transform-style: preserve-3d; transform: translateZ(-100px);

I tried something like this but it didn’t work,
I want to do something like this;

Is it possible to do this with css?

Convert string of character and number into integer?

I want to convert this string “F1” into an integer 1.

For example

"F1" ===> 1
"F2" ===> 2
"F3" ===> 3

So far, this is what I’ve done

parseLevel: function(level) {
    var levels = {
        "F1": 1,
        "F2": 2
    };
    return levels[level];
}

Here’s the function

parseLevel: function (level) {
  return parseInt(level, 10);
}

I’m getting an error says it’s NaN

getStaticProps returning undefined in Nextjs

I’m working on a blog in Nextjs, and I want it to to fetch all of the blog posts from a directory on build. But no matter what I return with getStaticProps, it always returns undefined in the main component. I have tried it in both next dev and next build

//import Markdown from "react-markdown";
import styles from "./post.module.css";
import { promises as fs } from "fs";
import parse from "gray-matter";

const Post = ({ post, title, date, summary, image, test }) => {
    console.log(post) //returns undefined
    return (
        <div id={ styles.postcontainer }>
            <div id={ styles.post }>
            </div>
        </div>
    );
};

export default Post;

export const getStaticPaths = async() => {
    return {
        paths: [...(await fs.readdir("assets/markdown")).map(file => { return { params: { id: file.replace(".md", "") } } }) ],
        fallback: false
      }
};
  

export const getStaticProps = async(context) => {
    const post = await fs.readFile(`assets/markdown/${ context.params.id }.md`, "utf8");
    console.log(post) //success
    return {
        props: {
            post : parse(post).content,
            title : parse(post).data.title,
            date : parse(post).data.date,
            summary : parse(post).data.summery,
            image : `../assets/${ parse(post).data.image }`,
        }
    }
};

Im pretty sure that the issue isn’t with the data == undefined, because when I log it in terminal (inside getStaticProps) it responds with the correct values.

console.log(post)

---
title : test
slug : test
date : 3-9-22
summery : lorem ipsum
image : test.png

---

# Header 1

I’ve tried

props: {
            test : "testvalue123"
        }

but it still returns undefined in the main component. Thanks in advance!

Why the image open instead of download in javascript? [duplicate]

This is my code:

var url = 'https://c4.wallpaperflare.com/wallpaper/203/636/834/minimalism-landscape-digital-windows-11-hd-wallpaper-preview.jpg';

function download(source) {
  const fileName = source.split('/').pop();
  var el = document.createElement("a");
  el.setAttribute("href", source);
  el.setAttribute("download", fileName);
  document.body.appendChild(el);
  el.click();
  el.remove();
}

download(url);

When I call this function it’s open the image instead of download it can anyone please tell me why it’s happening what’s wrong with my code…

P5js I want code to run for a susstained ammount of time after keyIsPressed

I am a complete beginner and I am working inside a custom p5js framework for a school project. We are working on a clock.

Basically, I want a piece of code to stay active for ~5 seconds after using the keyIsPressed feature. I’ve tried just about every solution I can possibly think of, for loops, while loops. Even my teacher hasn’t been able to help me solve this.

The kicker is we are not allowed to use the native p5js seconds. Since we are working inside the clock framework for school they have made custom hour, minute, second objects. I feel like these will be the key but I just can figure it out.

  if((keyIsPressed === true) &&  (keyCode === ENTER)) {
  fill(255, 0, 0);
  ellipse(700, 250, 300, 300);
  }

Is there a way where I can sustain the code inside this if statement instead of it just running while the key is held?

This is probably a silly question but I just couldn’t find an answer anywhere, Thank you in advance.

Break/return in a for loop of async calls?

Currently my function looks like this:

const checkDynamoID = (dynamoClient, tableName) => {
  function runCheck(client, params, id) {
    return new Promise(resolve => {
      client.getItem(params, function(err, data) {
        if (err) {
          console.log("Error",  err);
        } else {
          if (data.Item === undefined) {
            console.log("Key available: " + id)
            resolve(id)
          } else {
            console.log("Key taken: " + id)
          }
        }
      });
    });
  }

  for (let i = 0; i < 10; i++) {
    const randomID = this.generateRandomBase64URL()
    const dynamoParams = {
      TableName: tableName, //TABLE_NAME
      Key: {
        'videoID': { S: randomID },
      }
    }

    const res = runCheck(dynamoClient, dynamoParams, randomID).then((result) => {
      console.log("Result: " + result)
      if (typeof result !== 'undefined') {
        console.log("Result: " + result)
        return result
      }
    })
  }

  return ""
}

My goal is to run runCheck, which makes async calls to a DynamoDB to check for an ID, in a for loop until it returns a valid ID. After that, I’d like to return or break out of the external for loop that encloses the call and return from checkDynamoID. However, I’m not sure how to do this; I tried running this and it does not return, even after generating a valid value (ie. typeof result !== 'undefined').

Is there a way of doing this?

changing a Javascript image on event listener click

i have a Div holding an image with the id sunset that i want to add an onclick to to change its width from the CSS 25% to 100%

cannot see why my code is not working

var content = document.getElementById("sunset");
var first_click = true;

content.addEventListener("click", function () {
    if (first_click) {
        content.style.width = "100%";
    }

    else {
        content.style.width = "25%";
    }

});

CSS

#sunset{
    width:25%
}

How to add to a set without mutating it?

I want to add an item to a Set without mutating the original set. I tried using add() but this mutates the original:

var s = new Set();
var s1 = s.add('foo');
console.log('s has foo:', s.has('foo'));
console.log('s1 has foo:', s1.has('foo'));

How can I create a new set by adding an item to it, without mutating the original set?

useEffect hook isn’t triggered inside ReactDOMServer.renderToString()

I’m using leaflet and react-leaflet libraries to create a map inside a React Js app as well as Material UI library for the core UI components.

I’m creating a custom cluster and marker components (using React component, not using image/icon file) for the cluster and marker inside the map. I’m using react-leaflet-markercluster for the custom cluster feature and the pie chart from Apache Echarts library for the custom cluster component.

Problem

The problem I’m facing is the useEffect hook inside my CustomCluster component is never triggered.

Steps to produce

  1. Run the playground here: https://codesandbox.io/s/stackoverflow-custom-cluster-react-leaflet-s2wwsh
  2. This is the initial state
    enter image description here
  3. Press the zoom out button (top left corner)
    enter image description here
    We can see that the 3 markers become a single cluster. The console prints the cluster value from the CustomCluster component but there is no “update chart” message. It means that the useEffect hook is not triggered.
  4. Press again the zoom out button
    enter image description here
    We can see that all 4 markers become a single cluster. The console prints the updated cluster value from the CustomCluster component but again there is no “update chart” message. It means that the useEffect hook is not triggered again.

Code

App.jsx

const customClusterIcon = (cluster, dummyLocationList) => {
  return L.divIcon({
    // className: 'marker-cluster-custom',
    // html: `<span>${cluster.getChildCount()}</span>`,
    // iconSize: L.point(40, 40, true),
    className: "custom-icon",
    html: ReactDOMServer.renderToString(
      <ThemeProvider theme={customTheme}>
        <StyledEngineProvider injectFirst>
          <CustomCluster cluster={cluster} locationList={dummyLocationList} />
        </StyledEngineProvider>
      </ThemeProvider>
    )
  });
};

<MarkerClusterGroup
  showCoverageOnHover={false}
  spiderfyDistanceMultiplier={2}
  iconCreateFunction={(cluster) =>
    customClusterIcon(cluster, dummyLocationList)
  }
>
  {dummyLocationList.map((item, index) => (
    <Marker
      key={index}
      position={[item.latitude, item.longitude]}
      icon={L.divIcon({
        className: "custom-icon",
        html: ReactDOMServer.renderToString(
          <ThemeProvider theme={customTheme}>
            <StyledEngineProvider injectFirst>
              <CustomMarker
                movingStatus={item.status}
                label={item.deviceName}
              />
            </StyledEngineProvider>
          </ThemeProvider>
        )
      })}
    />
  ))}
</MarkerClusterGroup>

CustomCluster.jsx

const CustomCluster = (props) => {
  const { cluster, locationList } = props;

  const classes = useStyles();

  const chartRef = useRef();

  let clusterLocationList = [];
  cluster.getAllChildMarkers().forEach((itemCluster) => {
    locationList.forEach((itemLocation) => {
      if (
        itemCluster._latlng.lat === itemLocation.latitude &&
        itemCluster._latlng.lng === itemLocation.longitude
      )
        clusterLocationList.push(itemLocation);
    });
  });

  const chartOption = {
    series: [
      {
        name: "Access From",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: "inner"
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 1048, name: "Search Engine" },
          { value: 735, name: "Direct" },
          { value: 580, name: "Email" },
          { value: 484, name: "Union Ads" },
          { value: 300, name: "Video Ads" }
        ]
      }
    ]
  };

  useEffect(() => {
    console.log("update chart");

    let chart;
    if (chartRef.current !== null) chart = init(chartRef.current);

    const resizeChart = () => {
      chart?.resize();
    };
    window.addEventListener("resize", resizeChart);

    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      chart.setOption(chartOption);
    }

    return () => {
      chart?.dispose();
      window.removeEventListener("resize", resizeChart);
    };
  }, [cluster]);

  console.log(cluster);

  return (
    <>
      {/* AVATAR */}
      <Avatar>{cluster.getChildCount()}</Avatar>

      {/* PIE CHART */}
      <Box className={classes.chartContainer}>
        <Box ref={chartRef} className={classes.chart} />
      </Box>
    </>
  );
};

export default CustomCluster;

Question

Based on some articles on the internet, the useEffect hook is not triggered on React server-side render (SSR) for example here https://codewithhugo.com/react-useeffect-ssr/.

So what’s the solution for this case?

The goal is to create a custom cluster feature using a pie chart.

Javascript functions not working on github pages (but working locally)

I am able to load my javascript functions on the local machine (local host). But on github pages, it is not working (but marked as successfully pushed and “deployed”.)

I have included the file in tags.html as

<script>
    $(document).ready(function() {

        let currentTag = "";
        const queryTag = getQuery().tag;
     
        if (queryTag) {
            currentTag = queryTag;
            filterByTagName(currentTag)
        }
        //binding event
        $(".tag").click((e) => {
            currentTag = e.target.dataset.tag;
            filterByTagName(currentTag);
            updateQueryString(currentTag);
        })
    });
   
    function getQuery() {     
        var params = {};  
    
        window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, 
            function(str, key, value) { 
                params[key] = value; 
            }
        );     
        
        return params; 
    }

    function updateQueryString(tagName) {

        const path = `${location.protocol}//${location.host}${location.pathname}?tag=${tagName}`;
        window.history.replaceState({ path }, '', path);
    }

    function filterByTagName(tagName) {
        $('.hidden').removeClass('hidden');

        $('.post-list').each((index, elem) => {
            //elem -> element (ex. div) has data-tag1
            if (!elem.hasAttribute(`data-${tagName}`)) {
            $(elem).addClass('hidden');
            }
        });
        $(`.tag`).removeClass('selected');
        $(`.tag[data-tag=${tagName}]`).addClass('selected');
    }
</script>

The page I need to fix is https://popla0428.github.io/tags/

The code is at https://github.com/popla0428/popla0428.github.io
–> At this tag page, I want to filter the posts by tag icon, and that’s why I add the above.

Any help would be appreciated. Thanks in advance.

How can I read from a local txt file and check when it changes in javascript?

I want to make my js program read from a txt file whose location is hardcoded. Every time the txt file is update, I want to store the new data as a new variable.
For example, when the txt file changes from blank to the following:

Lorem ipsum dolor sit amet

it will store newInfo = “Lorem ipsum dolor sit amet”
Then if the txt file is updated to the following:

Lorem ipsum dolor sit amet
consectetur adipiscing elit

It will store newInfo = “consectetur adipiscing elit”

Coin Flip Animation. Doesn’t do the flip animation if it lands on the same face twice in a row

When the coin is on HEADS and the logic runs and determines that its HEADS again on the next flip the animation will not trigger because its dependent on a className changing and then having CSS take care of the animation. We are using state to change the className. I figured that setting the state to be null or something would work because technically the className is changing but maybe it runs to fast for the browser to notice?
Order of code should be: Flip Logic, JSX ClassName that changes, CSS for animation

    const flipCoin = () => {
    setCoin("");
    const random = Math.random();
    if (random < 0.5) {
      console.log(random);
      setCoin("heads");
      setHeadsCount(headsCount + 1);
    } else {
      console.log(random);
      setCoin("tails");
      setTailsCount(tailsCount + 1);
    }
  };
       <div className="coinContainer">
          <div id="coin" className={`animate-${coin}`}>
            <div id="heads" className="heads"></div>
            <div id="tails" className="tails"></div>
          </div>
        </div>
 .animate-heads {
  animation: flipHeads 3s;
  animation-fill-mode: forwards;
}

@keyframes flipHeads {
  from {
    transform: rotateY(0deg);
  }
  to {
    transform: rotateY(1800deg);
  }
}

.tails {
    background-image: url(./assets/tails.jpg);
    transform: rotateY(-180deg);
}

.animate-tails {
  animation: flipTails 3s;
  animation-fill-mode: forwards;
} 

SO if anyone has an answer that would be amazing. Thank you for your time.