What’s an efficient way of calling a method on every page load?

I am new to PHP OOP. There is a members section, an admin section, and a public section on my website. I want a task to be executed on the website every day. There is no need for the task to be executed when there is no visit. Therefore I am not using a cron job.

I am trying to achieve it by keeping a record of the last time the task was executed. For this, I want to use a method to check if the task timestamp is from today. If not, this method should perform the task and update the timestamp.

Website structure: Both in the members and the admin section, there are separate module files that contain DB connection details. Then there are respective class files that extend the module files and have methods performing CRUD operations on AJAX requests.

My question is, how can I efficiently call the daily task method every time any page from any of the sections (members, admin, or public) is loaded? An ajax call can be made from every page’s JS, but that’s not very elegant.

i need move photo left and right using onclick event

et left = document.querySelector(‘#left’);

let right = document.querySelector(‘#right’);

let counter = 1;

let img_contant = document.querySelector(‘.img_contant’);

let size = img_contant.clientWidth;

let increment = function () {
img_contant.style = margin-left: + counter * size + px;
counter++;
console.log(counter);
}

let decrement = function () {
img_contant.style = margin-left: + counter * size + px;
counter–;
console.log(counter);
}

left.addEventListener(‘click’, decrement);

right.addEventListener(‘click’, increment);

Compare two arrays and if match pass to object

The function has test each element of the first array using the callback to see if the output matches the corresponding element (by index) of the second array. If there is a match, the element from the first array becomes a key in an object, and the element from the second array becomes the corresponding value.

    function objOfMatches(arr1, arr2, callback){
let obj ={};
let newArr1 = arr1.toString();
newArr1 = callback(newArr1);
newArr1 = newArr1.split(",");

arr1.forEach(el=>{
  if((callback(newArr1) === arr2[el])) obj[arr1[el]] = arr2[el];
});

return obj;
}

The problem I got is that when I call function like this:

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); };
console.log(objOfMatches(arr1, arr2, uppercaser));

It gives an error (Type Error on line 18: str.toUpperCase is not a function).

However, it is working perfectly fine if used with a FOR loop instead of .forEach like this:

for(let i=0; i<arr1.length; i++){
  if(callback(arr1[i]) === arr2[i]){       
    obj[arr1[i]] = arr2[i];
  }
}

Can someone please explain to me in a JS beginner level language why it does not work?

How to debug “Cannot access X before initialization” errors?

This is part of my real code:

import { Tree, Text } from '@List'
import Upsert from './Upsert'
import { EntitySeo } from '../../Seo/Exports'

const filters = <>
    <Text
        column="Title"
        placeholder="Title"
    />
</>
...

And my Vite React application loads perfectly fine.

But when I change in some files, the HMR complains that:

react_devtools_backend.js:4026    
ReferenceError: Cannot access 'Text' before initialization
    at Tree.jsx:6:6   

overrideMethod @ react_devtools_backend.js:4026
warnFailedFetch @ client.ts:28    
(anonymous) @ client.ts:333    
await in (anonymous) (async)       
fetchUpdate @ client.ts:320    
(anonymous) @ client.ts:74    
handleMessage @ client.ts:72    
(anonymous) @ client.ts:45    
react_devtools_backend.js:4026    
[hmr] Failed to reload /src/Panel/Menu.jsx.    
This could be due to syntax errors or importing non-existent modules. (see errors above)

I don’t know how to debug this. What systematic steps can I take to find out the root of the problem. Because import { Text } from '@List' is lexically in previous lines to its usage.

VUE-JSON-EXCEL Change format date

I just want to ask on how to change format date for the VUE-JSON-EXCEL library?

After i click the generate excel button, it will display in the excel a date format like this “2022-06-10T18:18:34.000Z” instead of “10/6/2022 18:18:34”

Already use moment.js but it’s not working

Dealing with time in different timezones react/javascript (PST/PDT)

So I have this use case where a user should be able to enter data into a react site having an order_fulfilment_datetime_str which is supposed to be a RFC 3339 datetime string according to the specs of the api this would be posted to.

So essentially a user(in any timezone) selects a (future) date and time (using a plugin such as react-datepicker) assuming that the date time is going to be in PST/PDT.
But the plugin and javascript date object returns the selected date time in the browser’s timezone. So I have two things to solve:

  1. How do I make sure that selected date/time is in PST/PDT
  2. How to deal with DST?

Currently what I am trying to do is to simply get individual date, hours, minutes using getHours(), getMinutes(), getDate() to form the string. But again then how will I find out if this selected datetime has offset of -8 or -7(i.e. PST/PDT)?

I checked date-fns and date-fns-tz library but was not sure how to solve this issue using these.

Dropdown Date Picker is created. What can I write on servlet?

Dropdown Date Picker that only displays exitsting dates from year 1980 to 2020 is created.(For example 2/30 does not exist so this does not show.)

This is how the screen looks like now on this jsp

  1. Now, instead of not showing the non-existing dates in the option, I want to use servlet to display on the textbox (“The date does not exist”)if non existing date is picked.

  2. Also if the date does exist, I want to show the date on the textbox in the format that is picked on the radio box.

Even a tiny little hint to do this will be a great help.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
enter code here

<!DOCTYPE HTML>
<html lang="ja">
<head>
<title>Sample</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
    const monthCheck = function() {
        var year_value = document.getElementById("year").value;
        var month_value = document.getElementById("month").value;
        year_value = parseInt(year_value);
        month_value = parseInt(month_value);

        var x = document.form_signin.day;
        if (x.hasChildNodes()) {
            while (x.childNodes.length > 0) {
                x.removeChild(x.firstChild)
            }
        }

        if (year_value % 4 == 0 && month_value == 2) {
            for (var i = 1; i < 30; i++) {
                document.form_signin.day.options[i] = new Option(i , i);
            }
        } else if ([1, 3, 5, 7, 8, 10, 12].find(month_value)) { 
            for (var i = 1; i < 32; i++) {
                document.form_signin.day.options[i] = new Option(i , i);
            }
        } else if (month_value == 2) { 
            for (var i = 1; i < 29; i++) {
                document.form_signin.day.options[i] = new Option(i , i);
            }
        } else { 
            for (var i = 1; i < 31; i++) {
                document.form_signin.day.options[i] = new Option(i , i);
            }
        }
    }


</script>
<head>
<body>

<form name="form_signin" action="/something/Something" method="POST">

    <select name="birthday" id="year" onchange="monthCheck()">
        <option value="1">--year--</option>
        <option value="1980">1980</option>
        <option value="1981">1981</option>
        <option value="1982">1982</option>
        <option value="1983">1983</option>
        <option value="1984">1984</option>
        <option value="1985">1985</option>
        <option value="1986">1986</option>
        <option value="1987">1987</option>
        <option value="1988">1988</option>
        <option value="1989">1989</option>
        <option value="1990">1990</option>
        <option value="1991">1991</option>
        <option value="1992">1992</option>
        <option value="1993">1993</option>
        <option value="1994">1994</option>
        <option value="1995">1995</option>
        <option value="1996">1996</option>
        <option value="1997">1997</option>
        <option value="1998">1998</option>
        <option value="1999">1999</option>
        <option value="2000">2000</option>
        <option value="2001">2001</option>
        <option value="2002">2002</option>
        <option value="2003">2003</option>
        <option value="2004">2004</option>
        <option value="2005">2005</option>
        <option value="2006">2006</option>
        <option value="2007">2007</option>
        <option value="2008">2008</option>
        <option value="2009">2009</option>
        <option value="2010">2010</option>
        <option value="2011">2011</option>
        <option value="2012">2012</option>
        <option value="2013">2013</option>
        <option value="2014">2014</option>
        <option value="2015">2015</option>
        <option value="2016">2016</option>
        <option value="2017">2017</option>
        <option value="2018">2018</option>
        <option value="2019">2019</option>
        <option value="2020">2020</option>
    </select> <select name="birthday" id="month"
        onchange='monthCheck(this.selectedIndex)'>
        <option value="0">-Month-</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
        <option value="12">12</option>
    </select> <select name="birthday" id="day">
        <option value="0">-date-</option>
    </select>
</form>

<form name="form_005">
    <input type="button" value="➡" onclick="clickButton_003()"> <br>
    <input type="radio" name="select" value="A" id="date1">yyyy/MM/dd
    </br> <br> <input type="radio" name="select" value="B" id="date2">yy-MM-dd
    </br> <br> <input type="radio" name="select" value="C" id="date3">yyyy-MM-dd</br>
    <br> <input type="text" name="textBox_007"></br>

</form>

</head>
</body>
</html>

Replace method not working with function arguments [closed]

I have written a function that replace some strings. Below is the code of the function.

const replaceTemplate = (template, product) => {
    let output = template.replace(/${PRODUCT_NAME}/g, product.productName)
    output = template.replace(/${IMAGE}/g, product.image)
    output = template.replace(/${PRODUCT_LOCATION}/g, product.from)
    output = template.replace(/${NUTRIENTS}/g, product.nutrients)
    output = template.replace(/${QUANTITY}/g, product.quantity)
    output = template.replace(/${PRICE}/g, product.price)
    output = template.replace(/${DESCRIPTION}/g, product.description)
    output = template.replace(/${ID}/g, product.id)
    if (!product.organic) {
        output = template.replace(/${NOT_ORGANIC}/g, 'not-organic')
    }
    return output
}

The above function should replace a HTML template but it’s not. Even VS Code is not considering replace() as a method when using it with arguments. But replace() is working fine with normal strings.

Javascript window.confirm only works if the chrome dev tools is open?

My code is extremely simple:

const response = confirm(requestDetails.message);
console.log('done');

If I have the dev tools closed, the confirm modal simply does not appear and it skips straight to printing done.
I have the dev tools open, the confirm modal appears.

I am kinda lost on this one, am I missing something here? If I just write setTimeout(() => { confirm() }, 3000) in the dev tools of a random tab and then close the dev tools, then the confirm still appears there. But with the actual code running on my page…nothing.

Uncaught TypeError: Cannot read properties of undefined (reading ‘0’)

I have no clue why I am getting this error, I believe the logic is fine.

matchData[0] contains this information:

{    players: ["Disguised Lizard", "DrSpiteful"],
    winner: "DrSpiteful",
    scoreDifference: 1
}

Here’s the logic containing Match(props) info:

import React from 'react';
import Match from './Match';
import matchData from '../data/matchData';

function MatchList(props) {
  const oneMatch = matchData[0];
  console.log(oneMatch);
  return (
    <section className="PlayerList MatchList">
      <h1>Match list</h1>
      <Match
        players={oneMatch.players}
        winner={oneMatch.winner}
        scoreDifference={oneMatch.scoreDifference}
        />
    </section>
  );
}

export default MatchList;

I am getting an issue with this line of {props.players[0]} <span>vs</span> {props.players[1]} extracted from the code below:

import React from 'react';

function Match(props) {
  return (
    <article className="Match">
      <h1>
        {props.players[0]} <span>vs</span> {props.players[1]}
      </h1>
      {/* To be shown when there is a winner */}
      <h2>
        {props.winner} is the winner by {props.scoreDifference}!
      </h2>
      {/* To be shown when there is no winner */}
      <h2>No winners yet!</h2>
    </article>
  );
}

export default Match;

Can anyone point out to me what I am doing wrong, I honestly don’t see the issue.

Toggle Two Divs Onclick JavaScript

I am writing a function that toggles two divs onclick. I have 2 functions that displays an api json data as a table and graph (formatGraph and formatTable).
i have created two different divs and appended the formatGraph and formatTable functions to those divs. Then created a mainDiv to wrap the two divs.

I have an if statement that checks for when to show or hide the divs. I am calling the formatData function somewhere in my fetch call while rendering my result. I have a css file with the following code:

.displayTable {
    display: block;
}

.displayGraph{
    display: none;
}

But I am currently getting undefined and

Uncaught TypeError: Cannot read properties of null (reading 'style')
at HTMLButtonElement.

Any idea what I am missing, or how I can go about this? Here’s my function:

const formatData = (response) => {
    const mainDiv = document.createElement("div");
    const div1= document.createElement("div");
    div1.classList.add("displayTable");
    div1.appendChild(formatTable(response));
    mainDiv.appendChild(div1)

    const div2 = document.createElement("div");
    div2.classList.add("displayGraph");
    div2.appendChild(formatGraph(response));
    mainDiv.appendChild(div2)
    

    viewTable.addEventListener("click", function() {

    if(document.querySelector('.displayTable').style.display === "none") {
        document.querySelector('.displayGraph').style.display = 'none';
        document.querySelector('.displayTable').style.display = 'block';
    }

    else{
        document.querySelector('.displayTable').style.display === "none"
       document.querySelector('.displayGraph').style.display = 'block';
    }
    
    
})
};

Stop the Image Scrolling when it reached Nav bar CSS and Javascript

I am trying to figure out how to stop the image from moving/scrolling up before it reached the nav bar using javascript and css. but it still can scroll down.

I will really appreciate any help in advance thank you.
I attached the image of the desire output

output desire

My code is below

https://codesandbox.io/s/html-css-navbar-forked-06mjm0?file=/src/styles.css

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Navigation Bar</title>
    <link rel="stylesheet" href="../src/styles.css" />
  </head>
  <body>
    <nav>
      <div class="logo">
        <a href="#">Brand name</a>
      </div>
      <div class="menuIcon">
        <div class="line"></div>
        <div class="line"></div>
        <div class="line"></div>
      </div>
      <ul class="nav-links">
        <li class="nav-item active"><a href="#">Home</a></li>
        <li class="nav-item"><a href="#">Services</a></li>
        <li class="nav-item"><a href="#">About</a></li>
        <li class="nav-item"><a href="#">Contact</a></li>
      </ul>
    </nav>
    <div class="mainSec">
      <div id="animatedDiv"></div>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>

index.js

    var aDiv = document.getElementById("animatedDiv");

function changeWidth() {
  var scrollVal = window.pageYOffset;

  //Changing CSS Width

  /* This lags if you scroll fast.. aDiv.style.width = (100 - (scrollVal*100/800)) + "%"; 
  I just tried it out, so instead use the code down above, 800 to 1500 doesn't matter, I just increased time of animation
*/
  //NOTE this line checks if PERCENT <= 10 then sets width to 10%
  50 - (scrollVal * 100) / 1500 <= 10
    ? (aDiv.style.width = "10%")
    : (aDiv.style.width = 50 - (scrollVal * 100) / 1500 + "%");
}

window.addEventListener(
  "scroll",
  function () {
    requestAnimationFrame(changeWidth);
  },
  false
);

const menuIcon = document.querySelector(".menuIcon");
const menuIcons = document.querySelectorAll(".menuIcon .line");
const navLinks = document.querySelector(".nav-links");
const items = document.querySelectorAll(".nav-links li");
const logo = document.querySelector(".logo");
menuIcon.addEventListener("click", () => {
  navLinks.classList.toggle("open");
  logo.classList.toggle("close");
  items.forEach((item) => {
    item.classList.toggle("fade");
  });
  menuIcons.forEach((Icon) => {
    Icon.classList.toggle("open");
  });
});

const menu = document.querySelector(".nav-links");
const menuItems = document.querySelectorAll(".nav-links li");

menuItems.forEach((item) => {
  item.addEventListener("click", function () {
    menu.querySelector(".active").classList.remove("active");
    item.classList.add("active");
  });
});

style.css

   .mainSec {
  width: 100%;
  display: flex;
  justify-content: center;
}
#animatedDiv {
  background: url("https://media.tenor.com/images/34b16b199449136a845ea0300ff2cef3/raw")
    no-repeat;

  min-height: 200vh;
  width: 50%;
  position: absolute;
  margin-top: 20%;
}
#secondPage {
  background: url("https://www.downloadclipart.net/large/doraemon-png-free-download.png")
    no-repeat;
  display: block;
  width: 50%;
}

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
}

nav {
  position: fixed;
  height: 10vh;
  background-color: rgb(12, 77, 151);
  display: flex;
  align-items: center;
  width: 100%;
}

nav .logo a {
  color: white;
  font-size: 1.5rem;
  text-decoration: none;
  display: flex;
  text-align: center;
  margin: 0px 10px;
}
nav .nav-links {
  list-style: none;
  margin-left: auto;
}
.nav-links li {
  display: inline-block;
}

.nav-links .active {
  background-color: black;
  border: 2px solid black;
  border-radius: 10px;
}
nav .nav-links li a {
  color: white;
  text-decoration: none;
  font-size: 1rem;
  font-weight: 500;
  padding: 0px 10px;
}

@media screen and (max-width: 768px) {
  nav {
    position: relative;
    display: block;
  }
  .logo {
    height: 10vh;
    display: flex;
    align-items: center;
  }
  .logo a {
    text-align: center;
  }
  nav .menuIcon {
    position: absolute;
    cursor: pointer;
    top: 30%;
    right: 5%;
  }
  nav .menuIcon .line {
    width: 30px;
    margin: 5px 0px;
    height: 3px;
    background-color: white;
    position: relative;
  }
  nav .menuIcon .line:nth-child(1).open {
    transform: rotate(45deg);
    width: 40px;
    height: 5px;
    left: 0px;
    top: 16px;
    transition: all 1s ease;
  }
  nav .menuIcon .line:nth-child(2).open {
    opacity: 0;
  }
  nav .menuIcon .line:nth-child(3).open {
    transform: rotate(-45deg);
    width: 40px;
    height: 5px;
    transition: all 1s ease;
  }
  nav .nav-links {
    margin-top: -10px;
    padding: 0px;
    height: 90vh;
    width: 100%;
    background-color: rgb(12, 77, 151);
    display: flex;
    align-items: center;
    flex-direction: column;
    clip-path: circle(50px at 90% -10%);
    -webkit-clip-path: circle(50px at 90% -10%);
    transition: all 1s ease-out;
  }
  .nav-links li {
    margin: 40px 0px;
  }
  nav .nav-links.open {
    clip-path: circle(1000px at 90% -10%);
    -webkit-clip-path: circle(1000px at 90% -10%);
  }
  .nav-links li {
    opacity: 0;
  }
  .nav-links li a {
    font-size: 25px;
  }
  .nav-links li:nth-child(1) {
    transition: all 0.5s ease 0.2s;
  }
  .nav-links li:nth-child(2) {
    transition: all 0.5s ease 0.4s;
  }
  .nav-links li:nth-child(3) {
    transition: all 0.5s ease 0.6s;
  }
  .nav-links li:nth-child(4) {
    transition: all 0.5s ease 0.8s;
  }
  li.fade {
    opacity: 1;
  }
  .logo.close {
    visibility: hidden;
  }
}

why data is not syncing in shopify?

I am using shopify app/store and storefront API . storefront API working fine “ADD cart” “remove cart” . but it is not sync with shopify app/store . why ?

I am using react , graphgql example. In all example are working . but it is not syn with shopify theme/store.

https://github.com/Shopify/storefront-api-examples

In other words when I am adding a item in “CART” API return 200 but it is not adding shopify theme application.It should be sync with shopify store or when I open my application home page it should should one item added in cart

Why does my useEffect run if I’m not expecting it?

I am making a search engine using an input and a button that I hope will execute the search but when I just enter a letter in the input that sets the search value of useState my useEffect is executed even though search is not found in the useEffect dependency array.

Input:

                                        <div className="flex gap-1">
                                            <input className="border-1 border-2 border-solid rounded border-slate-300"
                                                value={search}
                                                onChange={(e) => setSearch(e.target.value)} 
                                            />
                                            <button onClick={ ()=> handleSearch() }><FiSearch/></button>
                                        </div>

handleSearch()

  const handleSearch = async () => { 
       setLimitPage(10)
       setPage(1)
       await getProducts(limitPage, page, search)
   }

my useEffect that is executed without being expected that way as soon as search changes

useEffect (() => {
    // eslint-disable-next-line
    getProducts(limitPage, page, search) 
    setTotalDocs(products.products?.totalDocs)
    setTotalPages(products.products?.totalPages)
    setCurrentPage(products.products?.page)
    setNextPage(products.products?.hasNextPage)
    setPreviousPage(products.products?.hasPrevPage)

    const totalPages = Math.ceil(totalDocs/limitPage)
    const links = []
    for (let i = 1; i <= totalPages; i++) {
        links[i] = i
    }
    setNumbers(links)
}, [products, limitPage, page ])

I don’t understand how I can avoid this so that I can use my search function before useEffect is executed