how to change navigation focus view of v-date-picker with manual trigger

i made vue date range picker manually using v-list and v-date-picker :

<v-card width="600" elevation="1" rounded>
    <v-container class="pa-0" fluid>
      <v-row dense no-gutters>
        <v-col cols="3" style="height: 100%">
          <v-list>
            <v-list-item-group v-model="select">
              <v-list-item v-for="(item, i) in items" :key="i">
                <v-list-item-content>
                  <v-list-item-title v-text="item.time" @click="tes(item.duration)"></v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list-item-group>
          </v-list>
        </v-col>
        <v-divider></v-divider>
        <v-col cols="9">
          <v-date-picker ref="tes" v-model="dates" range full-width>
            <template>
              <v-container class="pa-0">
                <v-row>
                  <v-col cols="6"><YBtn block secondary>Cancel</YBtn></v-col>
                  <v-col cols="6"><YBtn block>Apply</YBtn></v-col>
                </v-row>
              </v-container>
            </template>
          </v-date-picker>
        </v-col>
      </v-row>
    </v-container>
</v-card>

and my script :

export default {
data() {
    return {
    select: { time: 'Today', duration: 'today' },
    items: [
        { time: 'Today', duration: 'today' },
        { time: 'Yesterday', duration: 'yesterday' },
        { time: 'This Month', duration: 'thismonth' },
        { time: 'This Year', duration: 'year' },
        { time: 'Previous Month', duration: 'previousmonth' }
    ],
    dates: [this.$moment().format('YYYY-MM-DD')]
    }
},

methods: {
    tes(e) {
    switch (e) {
        case 'yesterday':
        this.dates = this.$moment().subtract(1, 'days').format('YYYY-MM-DD')
        break
        case 'thismonth':
        this.dates = [
            this.$moment().startOf('month').format('YYYY-MM-DD'),
            this.$moment().endOf('month').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        case 'year':
        this.dates = [
            this.$moment().startOf('year').format('YYYY-MM-DD'),
            this.$moment().endOf('year').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        case 'previousmonth':
        this.dates = []
        this.dates = [
            this.$moment().startOf('month').subtract(1, 'months').format('YYYY-MM-DD'),
            this.$moment().endOf('month').subtract(1, 'months').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        default:
        this.dates = this.$moment().format('YYYY-MM-DD')
        break
    }
    }
}
}

when i click on previous month, it succesfully change v-date-picker value to the selected previous month. but, the navigation still in current month. how do i change v-date-picker navigation focus to selected previous month?

as you can see there, the focus navigation at december. what i want when i click prevous month. it showing november, which is the previous selected month

How do I create a custom Form with FormData and upload to a server as PHP

If you wanted to upload randomText - 5994 text to a PHP server without the client using a <form> and data was sent in the background, how would you do it?
I guess this should be my code…

let xhr = new XMLHttpRequest();
xhr.open("log.php","POST");
//correct after this line.
xhr.send('{"name":"Sample Form Data","age":".."}');
xhr.close();

The code should send a request + data and the PHP code will do the rest.
This is the PHP code.

$name = $_POST["name"];
$age = $_POST["age"];
echo "client: ".$name."age".$age."yrs";

Native Javascript click event not working on icon in button

I have a button in my HTML + Tailwindcss page like so:

<div class="fixed bottom-4 right-4 z-10">

    <button
        id="button-fab-anchor"
        class="z-50 whitespace-nowrap flex items-center px-3.5 py-2 rounded-full shadow-xl
           outline-none focus:outline-none border-t border-b border-transparent
           combo-primary hover:bg-primary-contrast active:bg-primary-contrast"
    >
        <span class="z-40 icon-inverse-primary text-lg text-center">
            <i id="up-icon" class="fal fa-chevron-up"></i>
            <i id="down-icon" class="fal fa-chevron-down hidden"></i>
        </span>

    </button>

    <ul id="button-fab-list" class="absolute bottom-full right-0 flex flex-col justify-end hidden">
        <li> Buttons here... </li>
    </ul>

</div>

On the page I have the following JS:

document.addEventListener("DOMContentLoaded", function(event) {

    const btnAnchor = document.getElementById('button-fab-anchor');

    if (btnAnchor) {

        const btnList = document.getElementById("button-fab-list");
        const upIcon = document.getElementById("up-icon");
        const downIcon = document.getElementById("down-icon");

        btnAnchor.addEventListener("click",  function(event) {
            if (event.target == btnAnchor) {
                btnList.classList.toggle('hidden');
                upIcon.classList.toggle('hidden');
                downIcon.classList.toggle('hidden');
            }
        });

    }

});

This works fine if I click on the button but not on the icon in the button. I have tried using z-index to place the button parent at z-50 and the icon as z-10 so the parent is stacked above the child.

What sis I miss / How do I set up the event to work on the button parent and all its children (i.e.: the icon)?

How do I access a constructor “this” variable? [duplicate]

In my updateCamera(event) function, I am trying to access this.camera as can be shown in my constructor. Unfortunately, it’s undefined in that function, I assume it’s a scope issue, but I’m not sure how to solve it. Any ideas? Thank you.

export default class Experience {
    constructor(options = {}) {
        this.camera = new Camera();
        // removed unnecessary stuff
        this.onMouseDrag();
    }

    updateCamera(event) {
        console.log(this.camera); //Prints "undefined" in the console
        this.camera.position.x = (event.clientX / window.innerWidth) * 2 - 1;
    }

    onMouseDrag() {
        window.addEventListener("mousedown", () => {
            window.addEventListener("mousemove", this.updateCamera);
        });
        window.addEventListener("mouseup", () => {
            window.removeEventListener("mousemove", this.updateCamera);
        });
    }

Javascript single quote inside string for exported text file [duplicate]

I am creating a node.js file that creates and readme file where the install directions need to be displayed as shell or javascript type font. However, I have not been able to use the single quotes required to make that work since they close out the string.

function generateExport(data) {
  const { username, ...title} = data;

  return `
    ```shell <--- how would you do this ?
    ${data.title} 
    ```  <----- and this?
`;
}

“Error : Cannot use ‘in’ operator to search for ‘length’ in [{“ID”:”2″,”Name”:”EAA2″}]” when performing $.each

What ever I do, I keep getting the same error. The only thing I have found that might of helped is the JSON.parse, but I still get the same problem. console log gives data as [{"ID":"2","Name":"EAA2"}]

I split it into two functions as I didn’t want to keep going back to the api everytime a user selects/de-selects an option.

I have also tried the following:

  1. Changing vars to lets
  2. Passing data.d from the update to the populate
function populateAvailableAuthorities() {
            var list = $('#availableAA');
            var data = JSON.parse($('#AAJSON').val());
            var auths = $('#tbSelectedAA').val();

            list.empty();
            
            $.each(data, function (key, entry) {
                if (!~auths.indexOf(entry.ID + ';')) {
                    list.append($('<option></option>').attr('value', entry.ID).text(entry.Name));
                }
            });
            
        }

        function updateListboxes() {
            var teams = '';
            let aa = $('#AAJSON');

            aa.empty();

            $('#cblTeams input:checked').each(function () {
                teams += $(this).attr('value') + ',';
            });

            if (teams.length > 1) {
                teams = teams.substr(0, teams.length - 1);

                $.ajax({
                    type: "POST",
                    url: '<%# ResolveUrl("~/api/Authorities.asmx/FetchByTeam") %>',
                    data: '{teams: "' + teams + '"}',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        aa.val(JSON.stringify(data.d));
                        populateAvailableAuthorities();
                    }
                });
            }
        }

Vue : How to use async await accordingly in a function array of which can have two functions for Promise.all?

I want to use await where I marked [here] in 1.vue. However, if I use await there then it emits error Unexpected reserved word 'await'. If I want to use async useFunctionToAllServers() sequentially after [Promise.all] then, where to put async or how to change async useFunctionToAllServers()? Or need to change submitToTheOthers()?

1.vue

<template>
  <div>
    <label for="imgUpload">
      <button class="point">upload</button>
    </label>
    <input
      type="file"
      class="input-file"
      ref="logo1"
      id="imgUpload"
      @change="sendFile('logo')"
    />
    <div v-if="imageData" class="imgBox">
      <img :src="imageData" />
    </div>

    <label for="imgUpload">
      <button class="point">upload1</button>
    </label>
    <input
      type="file"
      class="input-file"
      ref="logo1"
      id="imgUpload"
      @change="sendFile('logo1')"
    />
    <div v-if="imageData1" class="imgBox">
      <img :src="imageData1" />
    </div>
    <button @click="useFunctionToAllServers">BUTTON</button>
  </div>
</template>
<script>
import {
  updateGeneralInfo,
  createUploadToOther,
  updateGeneralInfoToOther,
} from '@/2'

export default {
  data() {
    return {
      filename: '',
      filename1: '',
      originalFilename: '',
      originalFilename1: '',
      imageData: '',
      imageData1: '',
      serverNames: ['a server', 'b server'],
      idxs: [0, 1],
      serverFullAddress:['http://a.url', 'http://b.url'],
      serverResCheck:[],
      isLogoChanged:false,
      isLogo1Changed:false,
    }
  },
  methods: {  
    sendFile(type) {
      let file = ''
      if (type == 'logo') {
        file = this.$refs.logo.files[0]
      } else {
        file = this.$refs.logo1.files[0]
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        if (type == 'logo') {
        this.imageData = e.target.result
        } else {
        this.imageData1 = e.target.result
        }
      }
    },
    sendFileToOther(type, serverFullURL) {
      let file = ''
      if (type == 'logo') {
        file = this.$refs.logo.files[0]
        this.originalFilename = this.$refs.logo.files[0].name
      } else {
        file = this.$refs.logo1.files[0]
        this.originalFilename1 = this.$refs.logo1.files[0].name
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      const formdata = new FormData()
      formdata.append('logo', file)
      
      formdata.append('serverURL', serverFullURL)

      return createUploadToOther(formdata)
    },
    
    async useFunctionToAllServers() {
      
        let data = {
          foo: this.foo,
          bar: this.bar,
        }
        
        await updateGeneralInfo(data).then().catch()
      
        await Promise.all(this.submitToTheOthers()).catch((err) =>{ // [Promise.all]
          console.log('Promise.all err>>', err)
        });  
        
        let notWorkingServers = []
        for(let i=0; i< this.idxs.length ; i++){
          if(!this.serverResCheck[i]){
          notWorkingServers.push(this.serverNames[i])
          }
        }
        if(Array.isArray(notWorkingServers) && notWorkingServers.length == 0){
          alert('not working : ', notWorkingServers)
        }else{
          alert('all server works')
        }      
    },
    submitToTheOthers(){
      let data = {
        foo: this.foo,
        bar: this.bar,
      }
      let logoData ={}
      if(this.originalFilename){
        data.logo = this.originalFilename
        logoData.logo = true
      }else if(this.isLogoChanged){
        data.logo = this.logo
      }
      if(this.originalFilename1){
        data.logo1 = this.originalFilename1
        logoData.logo1 = true
      }else if(this.isLogo1Changed){
        data.logo1 = this.logo1
      }
      
      return this.idxs.map( (_entry, i) => {
        return updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then((res) => { // [here2]
          if (res.status == 200) {
            this.serverResCheck[i] = true
            if(logoData.logo){
              this.sendFileToOther('logo', this.serverFullAddress[i]).then((res) => { // [here]
              }).catch((err) => {
                this.serverResCheck[i] = false
              })
            }
            if(logoData.logo1){
              this.sendFileToOther('logo1', this.serverFullAddress[i]).then((res) =>{ // [here]
              }).catch((err) => {
                this.serverResCheck[i] = false
              })
            }
          }else{
            this.serverResCheck[i] = false            
          }
        }).catch((err) => {
          this.serverResCheck[i] = false
        })
      })
    },
  },
}
</script>

2.js

import axios from 'axios'
export const headers = {
  'Content-Type': 'application/json',
  'header1' : 'header1',
  'header2' : 'header2',
}

export function updateGeneralInfoToOther(id, data, serverAddress) {
  data.serverAddress = serverAddress
  return axios.put(`/u/r/l/${id}`, data, { headers })
}

export function updateGeneralInfo(id, data) {
  return axios.put(`/extra/u/r/l/${id}`, data, { headers })
}

export function createUploadToOther(data) {
  return axios.post('/u/r/l', data, { headers })
}

How to validate a Cloned form fields by javascript?

// Cloning Form
  var id_count = 1;
  $('.add').on('click', function() {
    var source = $('.form-holder:first'), clone = source.clone();
    clone.find(':input').val("").attr('name', function(i, val) {
      return val + '-'+id_count;
    });

    clone.appendTo('.form-holder-append');
      id_count++;

  });

  // Removing Form Field
  $('body').on('click', '.remove', function() {
    var closest = $(this).closest('.form-holder').remove();
  });
.remove
{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-folder">

 <input type="file" name="variant_images" id="upload_file" required multiple>
  
 
  
  <button class="remove">remove -</button>
</div>



  <div class="form-holder-append"></div><br>
  <button class="add">Add +</butoon>
  
// Cloning Form
  var id_count = 1;
  $('.add').on('click', function() {
    var source = $('.form-holder:first'), clone = source.clone();
    clone.find(':input').val("").attr('name', function(i, val) {
      return val + '-'+id_count;
    });

    clone.appendTo('.form-holder-append');
      id_count++;

  });

  // Removing Form Field
  $('body').on('click', '.remove', function() {
    var closest = $(this).closest('.form-holder').remove();
  });





//Image upload restriction
$(document).ready(function(){
  $('#upload_file').change(function(){
   //get the input and the file list
    var images = document.getElementById('upload_file');
      if(images.files.length<4){
          alert ("Please Upload minimum 4 images.");
          $("#upload_file").val('');

      }
   });
});
.remove
{
display:none;
}
.form-holder-append .remove {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-holder">

  <input type="file" name="variant_images" id="upload_file" required multiple>
 <button class="remove">remove - </button>

</div>
<div class="form-holder-append"></div><br>
<button class="add">add + </button>

I want to validate a each cloned forms input file, the validation is –>minimum 4 images should be uploaded otherwise the field returns empty value. But I have got this for fist form. After cloned, the id would be same and this is not working. How to write this for unlimited clone forms?

(Beginner Coder. Entry Entry Level) Save/Load function on HTML clicker game not working

Beginner learning from forums websites and youtube, bear with me pls.
(plus im dumb)

I’m making a stupid clicker game just to see if i can do it (clearly not).
I’ve got some buttons with onclick functions and multipliers setup whatever everything works fine.

Until Saving/Loading.

I followed a tutorial i found for the save function, to save/load your progress via localStorage/cookies, and it’s saving the total “money” (score) upon refresh, but my “scorepersecond” and every upgrade via button doesn’t save, even though i’ve included their cost and name values to tell which variables i want to save. I’m using VS Code with Live Server extension to test (firefox).

    function loadGame() {
            var savedGame = JSON.parse(localStorage.getItem("gameSave", "score", "scorepersecond", "cursors", "cursorcost", "lighters", "lightercost", "grinders", "grindercost", "devils", "devilcost", "trays", "traycost", "dealers", "dealercost"));
            if (typeof savedGame.score !== "undefined") score = savedGame.score;
        }
         function saveGame() {
             
            var gameSave = {
                 score: score,
                 scorepersecond: scorepersecond,
                 clickingPower: clickingPower,
                 cursors: cursors,
                 cursorcost: cursorcost,
                 lighters: lighters,
                 lightercost: lightercost,
                 grinders: grinders,                
                 grindercost: grindercost,
                 devils: devils,
                 devilcost: devilcost,
                 trays: trays,
                 traycost: traycost,
                 dealers: dealers,
                 dealercost: dealercost,
                        
             };
             localStorage.setItem("gameSave", JSON.stringify(gameSave));
            document.getElementById("score").innerHTML = score;
        document.getElementById("scorepersecond").innerHTML = scorepersecond;
            document.getElementById("cursorcost").innerHTML = cursorcost;
            document.getElementById("cursors").innerHTML = cursors;
            document.getElementById("lightercost").innerHTML = lightercost;
            document.getElementById("lighters").innerHTML = lighters;
            document.getElementById("grindercost").innerHTML = grindercost;
            document.getElementById("grinders").innerHTML = grinders;
            document.getElementById("devilcost").innerHTML = devilcost;
            document.getElementById("devils").innerHTML = devils;
            document.getElementById("traycost").innerHTML = traycost;
            document.getElementById("trays").innerHTML = trays;
            document.getElementById("dealercost").innerHTML = dealercost;
            document.getElementById("dealers").innerHTML = dealers;
         }
         window.onload = function() {
            loadGame();
            updatescorepersecond();
            document.getElementById("score").innerHTML = score;
            document.getElementById("cursorcost").innerHTML = cursorcost;
            document.getElementById("cursors").innerHTML = cursors;
            document.getElementById("lightercost").innerHTML = lightercost;
            document.getElementById("lighters").innerHTML = lighters;
            document.getElementById("grindercost").innerHTML = grindercost;
            document.getElementById("grinders").innerHTML = grinders;
            document.getElementById("devilcost").innerHTML = devilcost;
            document.getElementById("devils").innerHTML = devils;
            document.getElementById("traycost").innerHTML = traycost;
            document.getElementById("trays").innerHTML = trays;
            document.getElementById("dealercost").innerHTML = dealercost;
            document.getElementById("dealers").innerHTML = dealers;
            
         };

Thing’s I’ve Tried.

        var savedGame = JSON.parse(localStorage.getItem("gameSave"));
        if (typeof savedGame.score !== "undefined") score = savedGame.score;
    }```

```function loadGame() {
        var savedGame = JSON.parse(localStorage.getItem("gameSave"));
        if (typeof savedGame.score !== "undefined") score = savedGame.score;
        if (typeof savedGame.scorepersecond!== "undefined") scorepersecond = savedGame.scorepersecond;
    }

along with other variables i want to save, in the form of “(typeof ” which have also failed.

Not sure if this bit literally means anything, but if i inspect element on the page and access local storage it updates accordingly every 30 seconds with proper values, but upon page refresh it poof’s (except for total “money” (score) on top of the page).

Not sure what people need to see or if i shared enough, but if anyone could help without being a d-bag that’d be cool 🙂 even if not to solve it but a general idea of where i f’d up besides the whole thing. thanks in advance and lmk if you need to see more of my poopy clicker game.

Finding the creation date of the guild in the correct format, using discord.js

I’m trying to make a serverinfo command, and I wanted to add Server CreationDate.

This should give the Date, Time and How long ago.

But the issue is when I use message.guild.createdAt the output looks like this:

Sat Sep 04 2021 09:44:44 GMT+0000 (Coordinated Universal Time)

It’s too long AND it looks bad, I’m wondering if I can have the output look something like this?

09/04/2021 11:44 (3 months and 10 days ago)

Here is my code:

const { MessageEmbed } = require('discord.js');

module.exports = {
    name: 'serverinfo',
    category: 'Info',
    description: 'Shows info about the server.',
    aliases: [],
    usage: 'Serverinfo',
    userperms: [],
    botperms: [],
    run: async (client, message, args) => {
  if(message.author.bot) return;

  let staffcount = message.guild.roles.cache.get(process.env.ROLE_STAFF).members.size;
  let botcount = message.guild.roles.cache.get(process.env.ROLE_BOT).members.size;
  let membercount = message.guild.memberCount - botcount
  let verifiedcount = message.guild.roles.cache.get(process.env.ROLE_MEMBER).members.size - staffcount

    const embed = new MessageEmbed()
      .setThumbnail(client.user.displayAvatarURL({ dynamic: true, size: 512 }))
      .setColor("BLUE")
      .setTitle(':desktop: SERVER INFORMATION :desktop:')
      .addField('Server Name', '```' + message.guild.name + '```',true)
      .addField('Server Owner', '```SirDevinci#1998```',true)
      .addField('Server Members ['+ membercount +']', '```' + verifiedcount + ' Verified Members | ' + staffcount + ' Staff Members```',false)
      .addField('Server Tier','```' + message.guild.premiumTier + '```',true)
      .addField('Server Boosts','```' + message.guild.premiumSubscriptionCount + '```',true)
      .addField('Server CreationDate','```' + message.guild.createdAt + '```',false)
      message.channel.send(embed);
  }
}

thanks.

Hide module until everything is loaded

I’m using an interactive module within an article that takes a while to download completely.

I am hoping to have a “Loading…” div in place of the module that sticks until the whole module/article page is fully rendered.

Here’s my CSS:

.loading {
  font-family: "National Book",system-ui;
  color: #26a0a5;
  font-size: 16px;
max-width: 300px;
margin:auto;
}

.loading-wrapper {
background: #fff;
position: absolute;
top: 0;
left:0;
width: 100%;
height:100%;
z-index: 22;
}

.loading-bar {
  height: 2rem;
  background: #26a0a5;
  width: 100%;
  display: block;
  animation-name: loading;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

@keyframes loading {
  from {
    width: 0%;
  }
  to {
    width: 100%;
  }
}

.relative {
position: relative;
}

Here’s my Javascript:

  let canvasInterval = setInterval(()=>{
    if(window.MentalCanvas){
      clearInterval(canvasInterval)
      GScene = window.MentalCanvas.default.run(
        document.getElementById('render-container'),
        { path: 'https://files.sfchronicle.com/static-assets/mental-canvas/MAQUILADORA',
          fullscreen: false,
          controlsMode: 'scrolly' },
        function(error) {
          console.log(error)
         }
      );
      GScene.addEventListener('startRender', function() {
        document.querySelector('.loading-wrapper').classList.add('hidden');
      })
    }

    //declare box, element, pos
    function writeLayout(percent){
      if(GScene){
        GScene.setAnimationScrubT(percent);
        let captions = document.getElementById('captions');
        // Convert from "% of animation" (dummy.t) to "bookmark index"
        //   e.g., 0.45
        // the integer part (0) means "bookmark #1", the fractional part (0.45)
        // means "45% of the way to bookmark #2".
        //
        // This is important when the bookmark animation has different durations for
        // each bookmark, or linger times, etc.
        const bookmarkIndexFrac = GScene.cameraAnimator.GetSplinePos();
        captions.scrollTop = bookmarkIndexFrac*captions.clientHeight;
      }
    }


    window.addEventListener('scroll', ()=> {
      let scrollY = document.documentElement.scrollTop;
      let scrollRef = document.getElementById('scroll-ref');
      let offsetTop = scrollRef.offsetTop;
      let offsetHeight = scrollRef.offsetHeight-window.innerHeight; //*0.8
      let percent = (scrollY-offsetTop)/offsetHeight;

      if(scrollY>offsetTop && scrollY<offsetTop+offsetHeight){
        requestAnimationFrame(() => {
          writeLayout(percent)
        });
      }
    });

  }, 500)

And here’s the syntax I’m using right before the code for the module:

<div class="relative">
<div class="loading-wrapper">
<div class="loading">
        Loading... <span class="loading-bar"></span>
      </div>
</div>

<div id="canvas-scroller-30" class="mcscroller-module--render-container--32l70 mcscroller-module--visually-hidden--3v228"></div>

Right now, the “Loading…” shows up as intended, but it does not stay for the duration of the entire module load time.

Any help on adjusting this part of the code so it functions how it should?

GScene.addEventListener('startRender', function() {
        document.querySelector('.loading-wrapper').classList.add('hidden');
      })
    }

Using a JavaScript Prompt as a Password for a Small Website

This is probably not the safest way to do this, but I only have access to html and javascript so this is the best I can think of. I wrote a demo code of how it should work, but for some reason it’s just not!

<h1 id="hiddenContent" style="visiblity: hidden">Hidden Stuff That Requires Password To See!</h1>

window.onload = function() {
  chgDailyImg();
  document.getElementById('answer').innerHTML = imagearray[i]
}
var passwordInput = prompt("Please enter the password to continue...");
const imagearray = new Array();
imagearray[0] = "9G7DcwnWafg*EtMH";
imagearray[1] = "MDe^5qHTG#P9dHBm";
imagearray[2] = "h%$u@2Nfu8FL9H+R";
imagearray[3] = "X&NB5tYdUs5u@G#z";
imagearray[4] = "k#Rc3LGsCdu4q%qZ";
imagearray[5] = "!$p!Ss5BA%#4zeAa";
imagearray[6] = "qz63!tue3WCUxJ@R";
let i = 0;

function chgDailyImg() {
  let d = new Date();
  i = d.getDay();
}

if ((passwordInput, imagearray[i]) === true) {
  document.getElementById('hiddenContent').style.visibility = "visible"
  console.log("RIGHT")
} else {
  document.getElementById('hiddenContent').style.visibility = "hidden"
  console.log("WRONG")

}

I have messed around with this code for days and nothing…

Global memoizing fetch() to prevent multiple of the same request

I have an SPA and for technical reasons I have different elements potentially firing the same fetch() call pretty much at the same time.[1]

Rather than going insane trying to prevent multiple unrelated elements to orchestrate loading of elements, I am thinking about creating a gloabalFetch() call where:

  • the init argument is serialised (along with the resource parameter) and used as hash
  • when a request is made, it’s queued and its hash is stored
  • when another request comes, and the hash matches (which means it’s in-flight), another request will NOT be made, and it will piggy back from the previous one

async function globalFetch(resource, init) {
  const sigObject = { ...init, resource }
  const sig = JSON.stringify(sigObject)

  // If it's already happening, return that one
  if (globalFetch.inFlight[sig]) {

  // NOTE: I know I don't yet have sig.timeStamp, this is just to show
  // the logic
  if (Date.now - sig.timeStamp < 1000 * 5) {  
    return globalFetch.inFlight[sig]
  } else {
    delete globalFetch.inFlight[sig]
  }

  const ret = globalFetch.inFlight[sig] = fetch(resource, init)
  return ret
}
globalFetch.inFlight = {}

It’s obviously missing a way to have the requests’ timestamps. Plus, it’s missing a way to delete old requests in batch. Other than that… is this a good way to go about it?

Or, is there something already out there, and I am reinventing the wheel…?

[1] If you are curious, I have several location-aware elements which will reload data independently based on the URL. It’s all nice and decoupled, except that it’s a little… too decoupled. Nested elements (with partially matching URLs) needing the same data potentially end up making the same request at the same time.

How can I implement this so that the video only plays when the video is positioned in the center of the screen in react?

This is the code I applied first

main page!!
<MainProduct>
      {products.map((ele, idx) => {
        return (
          <div key={idx}>
            {products.length - 1 === idx ? (
              <ModelImages
                onClick={() => moveDetailPage(ele.product_seq)}
                id={ele.product_seq}
                alt={ele.product_name}
                src={ele.image_url}
                poster={ele.image_url}
                ref={ref}
                autoPlay
                muted
                loop
              />
            ) : (
              <ModelImages
                onClick={() => moveDetailPage(ele.product_seq)}
                id={ele.product_seq}
                alt={ele.product_name}
                src={ele.image_url}
                poster={ele.image_url}
                autoPlay
                muted
                loop
              />
            )}
          </div>
        );
      })}
    </MainProduct>

---------------------------------------------

index.html!!
<script type="text/javascript">
      window.addEventListener('load', videoScroll);
      window.addEventListener('scroll', videoScroll);

      function videoScroll() {
        if (document.querySelectorAll('video[autoplay]').length > 0) {
          var windowHeight = window.innerHeight,
            videoEl = document.querySelectorAll('video[autoplay]');

          for (var i = 0; i < videoEl.length; i++) {
            var thisVideoEl = videoEl[i],
              videoHeight = thisVideoEl.clientHeight,
              videoClientRect = thisVideoEl.getBoundingClientRect().top;

            if (
              videoClientRect <= windowHeight - videoHeight * 0.5 &&
              videoClientRect >= 0 - videoHeight * 0.5
            ) {
              thisVideoEl.play();
            } else {
              thisVideoEl.pause();
            }
          }
        }
      }
    </script>

It works, but I get these errors and it slows down a bit

enter image description here

If there is a way to fix the error or an appropriate method, please share it.

No matter how much I google, I can’t find anything.
No matter how much I google, I can’t find anything.