How to get image metadata into useChat within Svelte?

I am writing a ChatBot using Svelte and am using the useChat function to interface with my backend to talk to an LLM.

<script lang="ts">
    import ChatList from '$lib/components/ChatList.svelte';
    import PromptForm from '$lib/components/PromptForm.svelte';
    import { useChat, type Message } from 'ai/svelte';
    import { API_BASE_URL } from '$lib/config';

    export let id: string | undefined;
    export let initialMessages: Message[] | undefined;

    const { messages, append, isLoading, input } = useChat({
        initialMessages,
        id,
        api: `${API_BASE_URL}/api/chat`,
    });

    let tempUserInput = '';

    async function handleFinished() {
        await append({ id, content: tempUserInput, role: 'user' });
        tempUserInput = '';
    }
</script>

<div class="flex flex-col min-h-screen bg-background">
    <div class="flex-1 overflow-y-auto pt-6">
        <ChatList {messages} />
    </div>

    <div class="fixed inset-x-0 bottom-0 bg-metallic-gradient">
        <div class="mx-auto sm:max-w-2xl sm:px-4 flex gap-2">
            <div
                class="space-y-4 border-t bg-background px-4 py-2 shadow-subtle sm:rounded-t-xl sm:border md:py-4 flex gap-2 items-center grow"
            >
                <PromptForm on:submit={handleFinished} {input} {isLoading} />
            </div>
        </div>
    </div>
</div>

This is working fine for just chats, but sometimes I want to be able to get back images also from the LLM. According to the documentation, I think I can use experimental_attachments for this.

But I am not sure what to return from my backend to get the information about additional attachments into this experimental_attachments field.

Right now, I am returning a string, and that automatically seem to go inside the message.content field.

I tried returning a json instead that looks like this –

{
    'content': self.settings['dev_test_string'],
    'role': 'assistant',
    'experimental_attachments': {
        'content_type': 'img',
        'url': 'some_string'
    }
}

But this parses the whole of the return json into the message.content field. What should I return from the backend so that I have more control over what goes into the message object?

ReactJS strange state behaviour

I have two components: legacy parent class component, let’s call it RowComponent, and child ModalComponent. State of those modal is located in parent component:

this.state = {
  modalIsOpen: false,
};

When I click on button it executes function which changes modalIsOpen state to true and modal is popped up. So far so good.

showRequestModal() {
  this.setState({ modalIsOpen: true });
}

Inside my child component I have isOpen state which is property that relies on modalIsOpen

<Modal
  width={600}
  destroyOnClose
  open={isOpen}
  onCancel={hideModalHandler}
/>

hideModalHandler is function that passed as property like this:

hideModalHandler={this.hideRequestModal}

That’s how my hideRequestModal looks like (it bind properly):

hideRequestModal() {
  console.log('Executing hideRequestModal');
  this.setState({ modalIsOpen: false }, () => {
    console.log('callback - modalIsOpen:', this.state.modalIsOpen);
  });
}

The real magic (or what I would say my lack of knowledge) starts here. When I try to close my modal from child component I can see text Executing hidRequestModal without changing the state (which I see from the callback). But the most bizarre thing is when I click ESC button on modal it closes (and state is updating). So my question is what the hell is going on and how to close modal on click also, not by clicking Escape key. So I suppose there is some conflicts in events or something like that. I consider rewriting parent component to be function component and maybe it will solve the issue but I don’t know. Appreciate any help

Uncaught TypeError: Cannot set properties of undefined (setting ‘_DT_CellIndex’) for binding values

I have below html for which I am getting error as

Uncaught TypeError: Cannot set properties of undefined (setting ‘_DT_CellIndex’)

function dispalySignOffSheetFTTX(ReportType, Month, DataList) {
var _reportType = (ReportType == 'ALL') ? "PAN INDIA" : ReportType;
var _month = Month;
var table = $('#grdCicleDatatable');
$(table).empty();
var thead = "";
var datalist = JSON.parse(DataList);
if (ReportType == 'ALL') {        
    thead = "<thead>< tr ><th rowspan='2' class='text-left'>Maintenance Zone</th><th colspan='3'>FTTX</th><th colspan='3'>Grand Total</th></tr><tr><th>UG</th><th>Aerial</th><th>MDU</th><th>UG</th><th>Aerial</th><th>MDU</th></tr></thead >";
}

var tbody = "<tbody>";
table.append(thead);
table.append(tbody);
if (datalist != null && datalist.length > 0) {
    var grandTotalUG = 0;
    var grandTotalAR = 0;
    var grandTotalMDU = 0;
    $.each(datalist, function (key, val) {

        val.NE_LENGTH = val.NE_LENGTH == null ? 0 : parseFloat(val.NE_LENGTH);
        val.UG_LENGTH = val.UG_LENGTH == null ? 0 : parseFloat(val.UG_LENGTH);
        val.AR_LENGTH = val.AR_LENGTH == null ? 0 : parseFloat(val.AR_LENGTH);
        val.MDU_LENGTH = val.MDU_LENGTH == null ? 0 : parseFloat(val.MDU_LENGTH);

        grandTotalUG = val.UG_LENGTH;
        grandTotalUG = grandTotalUG.toFixed(3);
        grandTotalAR = val.AR_LENGTH;
        grandTotalAR = grandTotalAR.toFixed(3);
        grandTotalMDU = val.MDU_LENGTH;
        grandTotalMDU = grandTotalMDU.toFixed(3);

        var tr = "<tr id='" + val.ITEM + "'><td> " + val.ITEM + "</td><td class='text-center'> " + val.UG_LENGTH + "</td><td class='text-center'> " + val.AR_LENGTH + "</td><td class='text-center'> " + val.MDU_LENGTH + "</td><td class='text-center'> " + grandTotalUG + "</td><td class='text-center'> " + grandTotalAR + "</td><td class='text-center'> " + grandTotalMDU + "</td></tr>";

        table.append(tr);
    });

    table.append('</tbody>');
}

//var footer = "<tfoot><tr><th colspan='1' style='text-align:center'><b>Total:</b></th><th class='text-center'></th><th class='text-center'></th><th class='text-center'></th><th class='text-center'></th><th class='text-center'></th><th class='text-center'></th><th class='text-center'></th><th class='text-center'></th></tr></tfoot>";

var footer = "<tfoot><tr><th colspan='1' style='text-align:center'><b>Total:</b></th><th class='text-center'></th><th class='text-center'></th><th class='text-center'></th><th class='text-center'></th><th class='text-center'></th><th class='text-center'></th></tr></tfoot>";

table.append(footer);

oTable = $(table).dataTable({
    dom: 'tp',
    "dom": 'tp<"bottom"B><"clear">',
    "searching": false,
     responsive: true,
    "autoWidth": true,
    "bDestroy": true,
    "pageLength": 6,
    paging: false,
    "columnDefs": [
        { "width": "38.4%", "targets": 0 },
        { "width": "7.7%", "targets": 1 },
        { "width": "7.7%", "targets": 2 },
        { "width": "7.7%", "targets": 3 },
        { "width": "7.7%", "targets": 4 },
        { "width": "7.7%", "targets": 5 },
        { "width": "7.7%", "targets": 6 },
        { "width": "7.7%", "targets": 7 }

    ],
    buttons: [            
        {
            "extend": "excelHtml5", "text": "Export to Excel", "filename": _reportType + "_Fttx_SignOffSheet_" + _month,
            title: 'Sign Of Sheet of ' + _reportType + ' Circle for ' + _month + ' Month',
            messageBottom: '',
            exportOptions: {
                columns: ':visible',
                format: {
                    header: function (data, columnindex, trDOM, node) {                            
                        return GetColumnPrefixFTTX(columnindex) + data;
                    }
                }
            }
        }
    ],
    "footerCallback": function (row, data, start, end, display) {
        var api = this.api(), data;

        // converting to interger to find total
        var intVal = function (i) {
            return typeof i === 'string' ?
                i.replace(/[$,]/g, '') * 1 :
                typeof i === 'number' ?
                i : 0;
        };

        // computing column Total of the complete result 
        var FTTXUGTotal = api
            .column(1)
            .data()
            .reduce(function (a, b) {
                return intVal(a) + intVal(b);
            }, 0).toFixed(2);

        var FTTXARTotal = api
            .column(2)
            .data()
            .reduce(function (a, b) {
                return intVal(a) + intVal(b);
            }, 0).toFixed(2);

        var FTTXMDUTotal = api
            .column(3)
            .data()
            .reduce(function (a, b) {
                return intVal(a) + intVal(b);
            }, 0).toFixed(2);

        var TotFTTXUGTotal = api
            .column(4)
            .data()
            .reduce(function (a, b) {
                return intVal(a) + intVal(b);
            }, 0).toFixed(2);

        var TotFTTXARTotal = api
            .column(5)
            .data()
            .reduce(function (a, b) {
                return intVal(a) + intVal(b);
            }, 0).toFixed(2);

        var TotFTTXMDUTotal = api
            .column(6)
            .data()
            .reduce(function (a, b) {
                return intVal(a) + intVal(b);
            }, 0).toFixed(2);

        // Update footer by showing the total with the reference of the column index 
        $(api.column(0).footer()).html('Total');
        $(api.column(1).footer()).html(FTTXUGTotal);
        $(api.column(2).footer()).html(FTTXARTotal);
        $(api.column(3).footer()).html(FTTXMDUTotal);
        $(api.column(4).footer()).html(TotFTTXUGTotal);
        $(api.column(5).footer()).html(TotFTTXARTotal);
        $(api.column(6).footer()).html(TotFTTXMDUTotal);
    },
    initComplete: function () {
        var btns = $('.dt-button');
        btns.addClass('btn btn-danger button');
        btns.removeClass('dt-button');


    }

});

if (CurrentGroupName == UserGrouop.NHQPMO) {
    $('.buttons-pdf').css("display", "none");
} else {
    $('.buttons-excel').css("display", "none");

}

}

Execute the same javascript function from different onclick events

I have the following javascript code that plays a video when I click the “play” button in HTML.

How can I play different videos (multiple play buttons in HTML) without duplicating the JavaScript code?

$('#video-icon').on('click', function(e) {
  e.preventDefault();
  $('.video-popup').css('display', 'flex');
  $('.iframe-src').slideDown();
});

$('.video-popup').on('click', function(e) {
  var $target = e.target.nodeName;
  var video_src = $(this).find('iframe').attr('src');
  if ($target != 'IFRAME') {
    $('.video-popup').fadeOut();
    $('.iframe-src').slideUp();
    $('.video-popup iframe').attr('src', " ");
    $('.video-popup iframe').attr('src', video_src);
  }
});
<a class="video-section prelative text-center white" role="button" id="video-icon" aria-hidden="true">
  Play
  <div class="video-popup">
    <div class="video-src">
      <div class="iframe-src">
        <iframe src="the video link" allowfullscreen></iframe>
      </div>
    </div>
  </div>
</a>

Installing Deno with CLI error Permission on ubuntu 22.04

I got error when I install Deno with cli on ubuntu 22.04

curl -fsSL https://deno.land/install.sh | sh

I got error message

warning: Failed to open the file /home/USER/.deno/bin/deno.zip: Permission   
Warning: denied

I try to change home root directory ubuntu Owner & permissions

sudo chown -R $USER:$USER ~/.deno
chmod -R u+rwx ~/.deno

trying install with CLI againt, but still got error permission.

I try to change home root directory ubuntu Owner & permissions
trying running with sudo :

sudo -E bash -c 'curl -fsSL https://deno.land/install.sh | sh'

Refreshing Google access token causes loss of oauth scope

I have a scenario where I am obtaining access/refresh tokens via oAuth consent. When the access token expires, the refreshed token returned after refresh is losing scopes previously acquired.

Summary of the interesting parts of the code look like this:


// I'm using google-auth-library
import { OAuth2Client } from "google-auth-library";

...

// I create an OAuth2Client like this. Let's assume the parameters are correct (they are)
new OAuth2Client(
  clientId,
  clientSecret,
  redirectUri
);

When obtaining consent, I generate a URL like this (this.newOAuth2Client just creates the client as described above):

// Generate a url that asks permissions for the Drive activity scope
const authorizationUrl = this.newOAuth2Client(redirectUri).generateAuthUrl({

  // 'online' (default) or 'offline' (gets refresh_token)
  access_type: 'offline',

  prompt : 'select_account',

  // Pass in the scopes array.
  scope: scopes,

  // Enable incremental authorization. Recommended as a best practice.
  include_granted_scopes: true,

  // The value to be passed to the redirect URL.
  state: state
});

When it comes time to refresh the token, it looks like this:

const client = this.newOAuth2Client(redirectUri);
client.setCredentials({ refresh_token: refresh_token });
return await client.getAccessToken();

The token returned produces a 401 error against the (Drive) API I am accessing, for requests that worked just fine prior to the refresh.

This is how I’m pulling the updated tokens from the refresh:

/** 
 * The client.getAccessToken() returns something called a GetAccessTokenResponse, 
 * which seems to be undocumented (?). Hunting and pecking...
 */
const result = client.getAccessToken();
const response = result.res;
if(response.status == 200) {
  const credentials = response.data;
  const accessToken = credentials.access_token; // <== This seems broken
  const refreshToken = credentials.refresh_token;
}

The only other piece of relevant data might be that these lost scopes were originally obtained after initial consent. In my particular case, I am first requesting these scopes:

'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'

Later, I add the following scopes:

'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.appfolder',
'https://www.googleapis.com/auth/drive.file'

After the refresh, the scopes seem to revert to only the initial set. After this subsequent grant, there is an update to the access_token (as expected) and if there is a refresh_token present I will persist it, but generally a refresh_token is not provided on this incremental grant.

Is it expected that refreshing an access token would wipe out scopes, or is there something wonky with my approach? (or perhaps my problem is elsewhere entirely?)

Custom camera sizes in regula liveness web SDK

I’m using this library @regulaforensics/vp-frontend-face-components for user’s liveness and it works good, but the size of camera is too small and I can’t handle it

enter image description here

I want to increase the camera size and also remove the shadow (juste above the abandon button)

Sortable js on change the drag element source it impact the dragged element

I am using sortable js

The issue occurs because the filterValue state you use for the search functionality applies a hidden class to the drag source items, but this hidden state affects the dropped items

for example
Example action for drag and drop and search

"use client"; 

import {WEB_FUNC,SAP_FUNC,CONTROLS} from "./options"; 
 
Sortable.mount(new MultiDrag(), new Swap()); 
export default function Home() {

  function addChildFunctions(evt:any) {
    const draggedElement = evt.item.cloneNode(); // The dragged DOM element
    
    evt.item.replaceWith(draggedElement)
    if(!draggedElement) return;
    const draggedIndex = draggedElement.getAttribute("data-el-id"); // Retrieve index
    const draggedGroup = draggedElement.getAttribute("data-group"); // Retrieve index
    const draggedData = CONTROLS.find(
      (group ) => group.id == draggedGroup && group.items.find(item=>item.id==draggedIndex)?.hasChild
    );
     
    if (draggedData ) {
      // Make the dropped element a drop container dynamically
      const childContainer = document.createElement("ul");
      childContainer.className = "dynamic-drop-area bg-blue-50 drop-area p-5";
      draggedElement.appendChild(childContainer);

      // Initialize Sortable on the new container
      Sortable.create(childContainer, {
        handle: ".drag-handle",
        group: {
          name: "shared",
          pull: "clone",
        },
        forceFallback:  true,
        animation: 200,
        sort: true,
        multiDrag: true, // Enable multi-drag
        selectedClass: "selected",
        onAdd: addChildFunctions,
      });
    }
  }
  const dragElement = useRef([]);
  const dropArea = useRef(null); // Single reference for the drop area
  const searchInput = useRef([]);
   
  useEffect(() => {
    dragElement.current.forEach((a) =>
      Sortable.create(a, {
        animation: 200,
        group: {
          name: "shared",
          pull: "clone",
          put: false,
        },
        forceFallback:  true,dragoverBubble: false,
        sort: false,
      })
    );
    if (dropArea.current) {
    Sortable.create(dropArea.current, {
      handle: ".drag-handle",
      animation: 200,
      group: {
        name: "shared",
        pull: false, // Drop area should not pull items
        put: true, // Accept items
      },
      forceFallback:  true,dragoverBubble: false,
      sort: true,
      multiDrag: true, // Enable multi-drag
      selectedClass: "selected",
    
   
    });
  }
  }, []);
  
   
  const [filterValue,setFilterValue]=useState("");
 
  return (

    <> 
      
      <div className={  "flex flex-row "}>
        <div className="basis-1/5  p-5 max-h-screen overflow-auto">
        <div className="flex items-center rounded-md bg-white pl-3 outline outline-1 -outline-offset-1 outline-gray-300 has-[input:focus-within]:outline has-[input:focus-within]:outline-2 has-[input:focus-within]:-outline-offset-2 has-[input:focus-within]:outline-indigo-600">
      
        <input type="text" name="price" id="price" onChange={()=>{
          setFilterValue(searchInput.current.value)
        }} ref={searchInput} className="block min-w-0 grow py-1.5 pl-1 pr-3 text-base text-gray-900 placeholder:text-gray-400 focus:outline focus:outline-0 sm:text-sm/6" placeholder="Search" />
     </div>
          {[...CONTROLS,...WEB_FUNC ] .map((group, index) => {
            return (
              <div className="border-b border-slate-200" key={group.id}>
                <button
                  onClick={() => toggleAccordion(index)}
                  className="w-full flex justify-between items-center py-5
          text-slate-800"
                >
                  <span>{group.group}</span>
                  <span
                    id={"icon-" + index}
                    className="text-slate-800 transition-transform duration-300"
                  >
                   -
                  </span>
                </button>
                <div
                  id={"content-" + index}
                  className="open  overflow-hidden transition-all duration-300 ease-in-out"
                >
                  
                  <div className="pb-5 text-sm text-slate-500 connect">
                    <ul ref={(el) => (dragElement.current[index] = el)}>
                      {
                        
                        group.items.map((a, i) => (
                        <li
                          className={"gap-x-6 p-2 my-2 bg-gray-50 " +  ((filterValue===""?"":  a.label.toLowerCase().includes(filterValue?.toLowerCase?.())?"":"hidden"))}
                          data-el-id={a.id}
                          data-group={group.id}
                          key={group.id+"_"+a.id}
                          data-id={group.id+"_"+a.id}
                        >
                          <div className="flex px-2  items-center drag-handle">
                            {a?.icon}
                            <span className=" px-2">{a.label}</span>
                          </div>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <ul
          className="drop-area  min-h-screen  bg-red-50 basis-4/5  p-5"
          ref={dropArea}
        ></ul>
      </div>
       

    </>
  );
}

Initial state:

  1. drag source contains items like Item 1, Item 2, and Item 3.
  2. drop area contains Item 1 (dragged from the source).
    Search action:
  3. i search for Item 2.
  4. in the source list, only Item 2 is shown, and Item 1 and Item 3 are hidden by applying the hidden class.
    Unexpected Behavior:
  5. the hidden class is also applied to Item 1 in the drop area because it shares the same DOM attributes and filtering logic.

role based access control in nextjs using authjs and database with google oauth

I have a condition where certain pages can be accessed according to their role in database

I have followed the tutorial on the Authjs site, and it seems like there is a lack of information, because there is an error in my coding

I use mongoose (mongodb), nextjs, and Google provider (OAuth)

My auth config:

import GitHub from "next-auth/providers/github"
import type { NextAuthConfig } from "next-auth"
import Google from "next-auth/providers/google"
import Credentials from "next-auth/providers/credentials"

export default {
    providers: [
        Google({
            profile(profile) {
                return { role: profile.role ?? "user", ...}
            }
        }),
    ]
} satisfies NextAuthConfig

Callbacks:

  callbacks: {
        async session({ session, token, user }) {
            // `session.user.address` is now a valid property, and will be type-checked
            // in places like `useSession().data.user` or `auth().user`
            return {
                ...session,
                user: {
                    ...session.user,
                },
            }
        },
    },

The Error:

... Expression expected.

Middleware:

// export { auth as middleware } from "@/auth";

import NextAuth from "next-auth"
import authConfig from "./libs/auth-js/auth.config"

export const { auth: middleware } = NextAuth(authConfig)

Calling dispatchEvent(clickEvent) on a textbox doesn’t work

I want to programmatically generate a click event on a textbox when a user clicks on a button. I can see that the textbox gets the event but the focus doesn’t change to the textbox.
What am I doing wrong?

function handleClick(event)
{
    let textbox = document.getElementById('text');
    let rect = textbox.getBoundingClientRect();            

    let newEvent = new MouseEvent('click', {
        clientX: rect.x + 5,
        clientY: rect.y + 5,
        x: rect.x + 5,
        y: rect.y + 5,
        pageX: rect.x + 5,
        pageY: rect.y + 5
    });

    textbox.dispatchEvent(newEvent);
}
<input type="text" id="text" onclick="console.log('clicked')" /> 

<button onclick="handleClick(event)">Click</button>

Next.js 14: ReferenceError: window is not defined when using intl-tel-input-react

I’m trying to implement a phone input component in my Next.js 14 application using the intl-tel-input library. However, I’m getting a ReferenceError: window is not defined error during server-side rendering.

Environment:

  • Next.js: 14.2.5
  • React: ^18
  • intl-tel-input: ^25.2.0
  • Node: 18

Code:

Here’s my phone input component:

'use client';

import IntlTelInput from 'intl-tel-input/react/build/IntlTelInputWithUtils.cjs';
import './PhoneInput.css';

export function PhoneInput() {
  return (
    <IntlTelInput />
  );
}

Error:

ReferenceError: window is not defined

The error occurs when trying to render the page containing this component. I understand this is likely due to Next.js’s server-side rendering trying to access the window object which isn’t available on the server, but I’ve already added the 'use client' directive to make it a client component.

What I’ve Tried

  1. Added ‘use client’ directive at the top of the file
  2. Wrapped the component with dynamic import using Next.js’s dynamic function (but wasn’t sure about the correct configuration)

How can I properly implement this phone input component in Next.js while avoiding the SSR-related window reference error?

Any help would be greatly appreciated!

Remove button focus state after click

I’m trying to remove the focus state of a button once it is clicked. The issue is once I click a button and after that instead of clicking on anywhere else if I just press ENTER the click event on that button works again.

button focus issue

Below is my code –

<style>
button { outline: none } /** Many solutions mentioned this but this is just removing the view state */
</style>
<button type="button" onclick="test()">Click</button>
<script>function test() { console.log(1) }</script>

I tried adding outline: none to the CSS but this is not removing the actual functionality of the button on focused state.

What can be the solution for this?

Browser not setting cookies with SameSite=None when interacting with Web API

When developing a React web application that interacts with a server via a Web API, I encountered an issue where the browser does not store cookies with the SameSite=None attribute.

My React application, running at https://localhost:3000, sends POST requests to an API server at https://localhost:7000. The server responds with a Set-Cookie header, attempting to set a cookie with the attributes SameSite=None; Secure. However, despite the presence of this header in the response, the browser does not store the cookie, and subsequent requests lack the necessary authentication data.

If I use the same domain, the cookies are stored.

I tried:

fetch('https://localhost:7000/api/login', {
  method: 'POST',
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ username: 'user', password: 'password' })
})
  .then(response => {
    // Handle response
  });

aspnet:

//Cookies
cookies.Append("AccessToken", accessToken, new CookieOptions
        {
            HttpOnly = true,
            Secure = true,
            SameSite = SameSiteMode.None,
            Expires = DateTimeOffset.UtcNow.AddMinutes(15)
        });
        
        cookies.Append("RefreshToken", refreshToken, new CookieOptions
        {
            HttpOnly = true,
            Secure = true,
            SameSite = SameSiteMode.None,
            Expires = DateTimeOffset.UtcNow.AddDays(7)
        });

//Cors
 public static IServiceCollection AddAppCors(this IServiceCollection services)
    {
        return services.AddCors(options =>
        {
            options.AddPolicy(CorsPolicies.Base, policy =>
            {
                policy.WithOrigins("https://localhost:3000")
                    .AllowCredentials()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });
    }

//Program.cs

...
builder.Services.AddAppCors(); //ADD MY CORS
...
var app = builder.Build();

app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(CorsPolicies.Base); //USE MY CORS
app.UseAuthentication();
app.UseJwtSecurityStampValidation();
app.UseAuthorization();
app.MapControllers();

app.Run();

Why are different divs being created on each iteration?

I’m new to programming in javascript and I’m trying to create a 16 x 16 grid. I have coded in python and java before and neither of which really uses elements and tags like you do for web development.

screenshot

I found a tutorial but I’m trying to understand how all the divs are individually created when the reference is the same each time. Is a new location allocated in memory for each iteration of the loop? In the tutorial they also put event listeners inside the loop. Wouldn’t that not work because after the loop concludes the event listeners stop working?

Maybe this is a stupid question but I cannot understand things unless they are deeply explained.