Uncaught TypeError: Cannot read properties of null (reading ‘classList’) at HTMLDivElement.

I am working on a drag n drop files thing in HTML and javascript. It makes a new div for every file that is dropped and I want to happen, when it is clicked, a popup shows up. Done with this code.

document.querySelectorAll(".select").forEach(inputElement =>{
    const dropElement = inputElement.closest(".dropfiles");
    
    dropElement.addEventListener("dragover", (e) => {
        e.preventDefault();
        dropElement.classList.add("dropfiles--over");
        
    });
    dropElement.addEventListener("click", e => {
        inputElement.click();
    });
    ["dragleave", "dragend"].forEach(type => {
            dropElement.addEventListener(type, (e) =>{
                e.preventDefault();
                dropElement.classList.remove("dropfiles--over");
        });
        });
    dropElement.addEventListener("drop", (e) =>{
        e.preventDefault();
        if(e.dataTransfer.files.length){
            inputElement.files= e.dataTransfer.files;
            updateThumbnail(dropElement, e.dataTransfer.files[0]);
        }
        dropElement.classList.remove("dropfiles--over");
    });
    })
    
function updateThumbnail(dropElement, file){
    console.log(dropElement);
    console.log(file);
    let ThumbElement = dropElement.querySelector(".thumb");
    
    
    if (dropElement.querySelector(".prompt")){
        dropElement.querySelector(".prompt").remove();
    }
    ThumbElement = document.createElement("div");
    ThumbElement.classList.add("thumb")
    dropElement.appendChild(ThumbElement);
    ThumbElement.addEventListener("click", () => {
        if(file.type.startsWith("image/")){
            const content=document.getElementById("content");
            content.classList.add("show");
            reader.readAsDataURL(file)
            reader.onload = () => {
            content.style.backgroundImage = `url('${reader.result}')`;
            }
        }
    })

    if(file.type.startsWith("image/")){
        const reader = new FileReader();
        reader.readAsDataURL(file)
        reader.onload = () => {
            ThumbElement.style.backgroundImage = `url('${reader.result}')`
            ThumbElement.dataset.label = file.name +" | Last Modified: "+file.lastModifiedDate;
        }
    }
    if(file.type.startsWith("text/html")){
        const reader = new FileReader();
        reader.readAsDataURL(file)
        reader.onload = () => {
            ThumbElement.style.backgroundImage = `url('html.png')`
            ThumbElement.dataset.label = file.name;
            ThumbElement.style.width = '50%';
        }
    }
    if(file.type.startsWith("application/x-javascript")){
        ThumbElement.style.backgroundImage = `url('ohno.png')`
        ThumbElement.dataset.label = "We do not accept Javascript files as they could be harmful.";
    }
}
<!DOCTYPE html>
<html>
    <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" />
        <link href="https://fonts.googleapis.com/css2?family=Material+Icons"
rel="stylesheet">
        <title>Document</title>
        <link rel="stylesheet" href="./file.css" />
        <script src="https://kit.fontawesome.com/2b5f6cfacf.js" crossorigin="anonymous"></script>
      </head>
      <body>
      <div class="dropfiles">
      <div class="prompt">
        <span class="prompt">Drop files in here, Or click to upload</span>
        <input type="file" name="select" class="select"></input>
        <div class="content" id="content"></div>
        </div>
      </div>
      <script src="file.js"></script>

I have tried to do it this way with my code but then I get this error:
Uncaught TypeError: Cannot read properties of null (reading ‘classList’)
at HTMLDivElement.

I have checked to see if, maybe I didnt give it an ID, but I did, I checked if it hadn’t saved, and it did. I am not sure what to do, I have searched the seven seas (Stack Overflow) and none of those answers have helped me. SO pleeeeeez help meeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee

map a string to an object using regex

for some translations need, I need to replace a string having three brackets like

hello {{{'something'}}} world {{{'something else'}}} ... 

with a string containing two brackets and the values

{ 
  value: "hello {{1}} world {{2}}...",
  params: {1: 'something', 2: 'something else', ...}
}

I started with this codepen :

let brutto = "hello {{{'something'}}}} world {{{'something else'}}} ... ";
let regex = /[{]{3}(.+?)[}]{3}/;

let netto = brutto.replace(regex, "{{1}}");
let paramArray = brutto.match(regex).map((e, i) => {return {i: e}});

let result = { value: netto, params: paramArray }
console.log(result);

I get

{
    "value": "hello {{1}}} world {{{'something else'}}} ... ",
    "params": [
        {
            "i": "{{{'something'}}}"
        },
        {
            "i": "'something'"
        }
    ]
}

that is not really close to the desired result…

GSAP scrolling breaks when switching browser tabs

I’ve noticed some strange behavior of GSAP scrolling in GatsbyJS. I have a container with full-page sections that are scrolled with GSAP.

I open a tab in a browser and go to my website. The scrolling works fine. Then I open a new tab and go to (let’s say) google.com and spend some time on that website. The tab with my website is still open in a background. Then I switch from google tab back to my website tab. After doing that GSAP ‘breaks’ and scrolls two full-page sections one after another. Even if I scroll a mouse wheel a bit. And sometimes GSAP can’t scroll the section at all. It looks like a full-page starts moving but suddenly the scrolling stops and GSAP places the current section to it’s place.

I never go to any other website within that browser tab. Also I never go to any another route of my website. I just open an index page -> switch to another browser tab -> and switch back to my website tab. I have no idea how and why but exactly these actions cause the problem.

Code:

export default function IndexPage() {
  useEffect(() => {
    gsap.registerPlugin(ScrollTrigger)
    gsap.registerPlugin(ScrollToPlugin)

    const sections = document.querySelectorAll("section")

    const scrolling = {
      enabled: true,
      events: "scroll,wheel,touchmove,pointermove".split(","),
      prevent: e => e.preventDefault(),
      disable() {
        if (scrolling.enabled) {
          scrolling.enabled = false
          window.addEventListener("scroll", gsap.ticker.tick, { passive: true })
          scrolling.events.forEach((e, i) =>
            (i ? document : window).addEventListener(e, scrolling.prevent, {
              passive: false,
            })
          )
        }
      },
      enable() {
        if (!scrolling.enabled) {
          scrolling.enabled = true
          window.removeEventListener("scroll", gsap.ticker.tick)
          scrolling.events.forEach((e, i) =>
            (i ? document : window).removeEventListener(e, scrolling.prevent)
          )
        }
      },
    }

    function goToSection(section, anim, i) {
      console.log(scrolling.enabled)

      if (scrolling.enabled) {
        // skip if a scroll tween is in progress
        scrolling.disable()

        gsap.to(window, {
          scrollTo: { y: section, autoKill: false },
          onComplete: scrolling.enable,
          duration: 1,
        })

        anim && anim.restart()
      }

      console.log(section)
    }

    sections.forEach((section, i) => {
      const intoAnim = gsap.from(section.querySelector(".right-col"), {
        yPercent: 50,
        duration: 1,
        paused: true,
      })

      ScrollTrigger.create({
        trigger: section,
        start: "top bottom-=1",
        end: "bottom top+=1",
        onEnter: () => goToSection(section, intoAnim),
        onEnterBack: () => goToSection(section),
      })
    })

    return () => {
      ScrollTrigger.kill()
    }
  }, [])

  return (
    <div className={styles.container}>
      <Header />
      <Products />
      <Contact />
      <Footer />
    </div>
  )
}

Why does Gsap copied form codepen doesn’t work on my website?

I’m trying to use a gsap animation copied from Codepen, but it doesn’t work on my page.
I tried many alternatives but seems it wouldn’t work.

This is the codepen project https://codepen.io/manumqln/pen/vYyOmQw


        function BTweens() {
            var W = window.innerWidth, H = window.innerHeight, C = 40;
            TwL.killDelayedCallsTo(BTweens); 
            TwL.delayedCall(C * 4, BTweens);
            for (var i = G.length; i--;) {
                var c = C, BA = [], GWidth = G[i].offsetWidth, GHeight = G[i].offsetHeight;
                while (c--) { 
                    var SO = MR(1); 
                    BA.push({ x: MR(W - GWidth), y: MR(H - GHeight)}); 
                };
                if (G[i].T) { 
                    G[i].T.kill() 
                }
                G[i].T = TweenMax.to(G[i], C * 4, { bezier: { timeResolution: 0, type: "soft", values: BA }, delay: i * 0.35, ease: Linear.easeNone });
            }
        };
        BTweens();
        window.onresize = function () {
            TwL.killDelayedCallsTo(BTweens); 
            TwL.delayedCall(0.4, BTweens);
        }; 

This is my page https://www.attiliosantomo.com/test.html

Can someone help me please? Thank you so much

Select interaction with swipe in Openlayers

I’m using swipe control https://viglino.github.io/ol-ext/examples/control/map.control.swipe.html
to show two layers on the map: right and left side.

I have a select ol.interaction.Select interaction to change the style accordingly
the mouse on the map.
However, I noticed that by hovering over the layer on side 1, it is working with the data
side 2 (image 2 smaller), i.e. changed the style of a polygon that does not exist on the side
1 and only on side 2.
enter image description here
How do I set a select for each side of the swipe?

Daylight Saving Time Handling At Frontend (Angular) Using momentjs and moment timezone

Recently I’ve come across an issue of managing Daylight savings time for the users of different time zones on my platform. For date time operations like parsing and conversion i am using packages like moment js and moment timezone. Upon searching on the internet for Australian timezone DST in changing on first Sunday of April 2022 and first Sunday of October 2022. this change is on +/- 1 hour. Moment js and moment timezone is handling this automatically. but for my use case i want to get the real value of time without DST correction. I am sure that there might be different DST transition dates for different countries also the offset amount ( 1 hour for Australia) will be different. Is there any way to make moment js ignore the DST offset? if there is no options like that then what will be the best way to handle this DST offset correction for various countries?

Need help fixing this error, TypeError. Angular/Typescript

I have been trying to fix this TypeError for quite some time now.
This is the actuall error thats happeing

ERROR TypeError: Cannot read properties of undefined (reading 'stop')
    at processBlob (app.component.ts:149:17)
    at timer (zone.js:2561:1)
    at ZoneDelegate.invokeTask (zone.js:406:1)
    at Object.onInvokeTask (core.js:28679:1)
    at ZoneDelegate.invokeTask (zone.js:405:1)
    at Zone.runTask (zone.js:178:1)
    at invokeTask (zone.js:487:1)
    at ZoneTask.invoke (zone.js:476:1)
    at data.args.<computed> (zone.js:2541:1)

This is the part of the code that causes it. The error message points to the ‘stop’ but this stop is a function. I don’t understand what is happening.

processBlob(){
    this.record.stop(this.addInArray.bind(this));
}

I am working on an Angular app. I did some online googling to fix this and there seems to be a solution to check if it this undefined. I don’t understand this part.
Can you please explain why this error is happening and what can I do to fix it. Thanks

What is the debounce function doing exactly? [duplicate]

So I’ve read some tutorials and watched videos about it and pretty much understood its uses and how to implement. But I still can’t wrap my head around how it does what it does.
This is a basic debounce function:

function debounce(func, timeout = 1000) {
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => func(), timeout);
  };
}
const debouncedFunction = debounce(() => console.log("hello world"));

If we add an event listener to a button which fires debouncedFunction on click, it works perfectly fine. But I can’t figure out the part at which the timer “resets”, I am guessing a new function replaces the older one each time the button is clicked resulting in the timer resetting, but I am not so sure about it. And I couldn’t find anyone explaining how it works.

Can you bypass state management for simple objects? (global shared state)

Can you globally instantiate a class and that will be reliable on react-native? i.e.

// logs.ts
const instance = new Instance()
export { instance }

// something.tsx
const Component = () => {
   instance.method()
   ...
}

If method were to increment a property by 1 would that property always have been incremented the number of times method was called throughout the project?

The primary benefit here is simplicity. For example, it’s easier to define

class SomeClass {
  constructor(properties){}
  addProperty(key,value){ this.properties[key] = value }
}

than it is to do the equivalent in redux. Why don’t people do the above more often?

Why is the last value undefined in this for loop?

const numbers = [1, 2, 3, 4, 5];

const printItems = (arr) => {
  for (let item in arr)
  {
    console.log(item); // 0, 1, 2, 3, 4, undefined
  }
};

console.log(printItems(numbers));

i tried to add more values into the array but i still get undefined for the last value. Also noticed that it’s not inserting the last index into the console.log.

What Im I doing wrong: Uncaught TypeError: Cannot read properties of null [closed]

Im getting the error

index.js:126 Uncaught TypeError: Cannot read properties of null (reading 'child')
    at getWordList (index.js:126:45) 

Line 126 is

const liElements = getNextWordsContainer().child; 

Im not sure what my error is here or what Im doing wrong.

const getWordList = () => {
  let words = [];
  const liElements = getNextWordsContainer().child;

  for (const liElement of liElements) {
    words.push(liElement.firstChild.innerText);
  }

  return liElements;
};

__clone method called on non-object /line 59 Laravel 8

I am trying to notify the user that enrolled in an event a day before the start date but it shows me a different error in the last line when it comes to notify(). dose anyone can help.

i have user model which contains (first_name,last_name,sex,users_phone,email, users_photo andpassword)

<?php

namespace AppConsoleCommands;
use IlluminateConsoleCommand;
use AppModelsUser;
use AppModelsevent;
use AppModelsEnrollment;
use AppMailSendMail;
use IlluminateSupportFacadesMail;
use IlluminateSupportFacadesDB;
use CarbonCarbon;
use IlluminateSupportFacadesNotification;
use IlluminateNotificationsNotifiable;

class SendNotification extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send:notification';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'send automatic notification to users that enrolled in events a day before the event date';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
    
       $events = DB::select('SELECT events.start_date , enrollments.user_id , users.id, users.first_name, users.last_name, users.sex, users.users_phone, users.password, users.email  FROM events , enrollments , users where events.id= event_id and enrollments.user_id=users.id');
        

                foreach($events as $event) {

                $created = new Carbon($event->start_date);
                 $now = Carbon::now();
                 if((($created->diffInHours($now))>=24 )&& (($created->diffInHours($now))<=48) && ($event->user_id == $event->id)){
                
                app(User::class)->fill(['id' =>$event->id,  'first_name' => $event->first_name, 'last_name' => $event->last_name, 'sex' => $event->sex, 'users_phone' => $event->users_phone, 'email' => $event->email,'password' => $event->password])->notify("Your deadline is in  day!"); 
                 }
            }        
        
    }
}
    

class SendNotification extends Command.

event model (id, eventname, eventstartdate)

enrollments user_id , event_id

How to capture image from both front and rear camera using JavaScript?

I am trying to build an application that can capture an image from the front and rear camera simultaneously (on a mobile device). I have experience with the library p5.js, which will allow me to take a picture from either the front or rear camera. Does anyone have an idea, example or suggestion for how to achieve the functionality of capturing an image from both cameras?

It seems as though the Media Capture and Streams API only allows a binary selection of either ‘user’ or ‘environment’ for the facingMode. This also seems to be the case for the p5.js library. Does anyone have an idea or example of what to do when the goal is to capture an image from the front and rear camera simultaneously?

TypeError: Cannot read properties of undefined (reading ‘transaction’) –> when I try to write to indexedDB when offline

I’m trying to get my app to use indexedDB when there is no internet connection. I have an idb.js file that sets up the object store and then defines a saveRecord function that I use in another js file:

let db;

const request = indexedDB.open('pizza_hunt', 1);

request.onupgradeneeded = function(event) {
    const db = event.target.result;
    db.createObjectStore('new_pizza', { autoIncrement: true });
}

request.onsuccess = function(event) {
    // when db is successfully created with its object store (from onupgradeneeded event above) or simply established a connection, save reference to db in global variable
    if (navigator.onLine) {
        // uploadPizza();
    }
};

request.onerror = function(event) {
    console.log(event.target.errorCode);
};

// This function will be executed if we attempt to submit a new pizza and there's no internet connection
function saveRecord(record) {
    const transaction = db.transaction(['new_pizza'],'readwrite');

    const pizzaObjectStore = transaction.objectStore('new_pizza');

    pizzaObjectStore.add(record);
};  

But when the function is called in the other file, I keep getting the error from above, that .transaction is undefined and it doesn’t write anything to the new_pizza object store.

Here’s the context in which it is called (another js file). It all works unless the catch is triggered:

const formData = { pizzaName, createdBy, size, toppings };

  fetch('/api/pizzas', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(formData)
  })
    .then(response => response.json())
    .then(postResponse => {
      alert('Pizza created succesfully!');
      console.log(postResponse);
    })
    .catch(err => {
      console.log(err);
      saveRecord(formData);
    });