How to control grid size with dropdown menu?

I am making a project where I have to create a grid of equally sized images can be controlled with dropdown menus.
One dropdown menu should control the amount of rows and the other should control the amount of columns.
The grid should be filled as well, so the number of divs inside is the product of the number of rows and columns.

For example if you set one dropdown to 3 and the other to 5, the grid should be 3 by 5 with 15 divs.

I think the solution is to wipe the grid every time one of the dropdown menus are changed, and then creating divs (maybe with a for loop) to fill it. And then you would change the grid-template-rows and grid-template-columns to fit the dropdowns.

But I can’t seem to get it working.

Thanks in advance!

Adding animations to expandable folders

I have a 4 expandable containers in a single row.
After clicking the title the container expands and the other containers collapse/shrink.

I’m struggling with adding some animation/transition to the action of expanding/collapsing/shrinking to all of them.

Nothing I tried works.

Anyone knows how to add some animations to expand/collapse these containers to look smoothly?

This is the code: https://codepen.io/Micha-Molka/pen/BaGrzpw

<div class="row">
  <div class="container">
    <div class="header">
      <h3 class="title">Title 1</h3>
    </div>
    <div class="content">
      <div class="color color1"></div>
      <div class="opis">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sed ex turpis. Vivamus malesuada ante sit amet ullamcorper hendrerit.
      </div>
    </div>
  </div>
  <div class="container">
    <div class="header">
      <h3 class="title">Title 2</h3>
    </div>
    <div class="content">
      <div class="color color2"></div>
      <div class="opis">
        Sed vestibulum posuere dictum. Aliquam erat volutpat. Ut sodales odio mi, nec interdum felis lobortis a.
      </div>
    </div>
  </div>
  <div class="container">
    <div class="header">
      <h3 class="title">Title 3</h3>
    </div>
    <div class="content">
      <div class="color color3"></div>
      <div class="opis">
        Nullam bibendum, velit vel feugiat vestibulum, quam turpis dictum mauris, non iaculis tellus sem ac mi.
      </div>
    </div>
  </div>
  <div class="container">
    <div class="header">
      <h3 class="title">Title 4</h3>
    </div>
    <div class="content">
      <div class="color color4"></div>
      <div class="opis">
        Phasellus sodales pharetra diam at luctus. In egestas nisi eu urna ullamcorper, at tempus lacus ultrices.
      </div>
    </div>
  </div>
</div>


html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.row {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  height: 100%;
}

.container {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 100%;
  box-sizing: border-box;
  transition: max-width 13s;
}

.header {
  cursor: pointer;
}

.content {
  flex: 1;
  position: relative;
  display: flex;
  flex-direction: row;
}

.container .color {
  flex: 1;
  min-height: 200px; /* Wysokość kwadratów - dostosuj według potrzeb */
}

.container .color1 {
  background-color: #ff0000;
}

.container .color2 {
  background-color: #00ff00;
}

.container .color3 {
  background-color: #0000ff;
}

.container .color4 {
  background-color: #ff00ff;
}

.container.expanded {
  flex-basis: 40%;
}

.container.collapsed {
  flex-basis: auto;
}

.container .opis {
  display: none;
  opacity: 0;
  background-color: #f0f0f0;
  padding: 10px;
  line-height: 1.5;
  max-width: 50%;
  transition: opacity 3s;
}

.container.expanded .opis {
  display: block;
  opacity: 1;
  animation: fadeIn 3s forwards;
}
@keyframes fadeIn {
  0% {
    opacity: 0;
    display: none;
  }
  1% {
    opacity: 0;
    display: block;
  }
  100% {
    opacity: 1;
    display: block;
  }
}

const containers = document.querySelectorAll(".container");

containers.forEach((container) => {
  const header = container.querySelector(".header");
  const content = container.querySelector(".content");

  header.addEventListener("click", () => {
    containers.forEach((c) => {
      if (c !== container) {
        c.classList.add("collapsed");
        c.classList.remove("expanded");
      }
    });
    container.classList.toggle("collapsed");
    container.classList.toggle("expanded");
  });
});

javascript Failed to execute ‘querySelector’ on ‘Document’: The provided selector is empty

I get the error Failed to execute ‘querySelector’ on ‘Document’: The provided selector is empty. when I call the method for the second time and there on forwards when i use this.#email = document.querySelector(this.#email).value however when i use the parameter passed to the method as in document.querySelector(email_input_id).value everything works fine. I should add that the function is triggered by click event.

buttonClicked(email_input_id,passowrd_inpiut_id,password_repeat_input_id){
        this.clear_error_div();
        let email_input_id2 = this.#email;
        this.#email = document.querySelector(email_input_id2).value; // works first time only
        this.#password = document.querySelector(passowrd_inpiut_id).value; // works
        this.#password_repeat = document.querySelector(password_repeat_input_id).value; // works
        console.log(typeof this.#email);  // output is string
        console.log(typeof email_input_id); // output is string
        console.log(this.#email); // output is #email_inp
        console.log(email_input_id); // output is #email_inp
        //this.#email = document.querySelector(this.#email).value; // first time only then error
        // this.#password = document.querySelector(this.#password).value; // same
        // this.#password_repeat = document.querySelector(this.#password_repeat).value; // same
        this.#password_strength();
        this.#passwords_equality();
        this.#password_proper_length();
        this.#error_container.innerHTML += this.error_message;
        
        return this.#password_email_okay();
        for (var key in this.errors) {
            var value = errors[key];
            console.log(key + " = " + value + '');
        }
    }

Ive tried logging everything, im stuck as stated. Thank you so much for any help.

svelte and sortable js, how to handle a dynamic array

I’m new to svelte and am working on a simple drag and drop list using sortablejs as the base. I load the data from a nested array of objects to instantiate the lists, and want any changes from sortable to be replicated to the array, but I can’t get it to stop behaving oddly.

I binded the array to the components so that they can send the Sortable order to update the array. The array seems to update correctly, but the actual list becomes very janky: double moving items and undoing moves. I can’t wrap my head around what exactly is causing this.

REPL

App.svelte

<script>    
    import List from "./List.svelte";
    let items = [
        [
            {id: 1,name: "one"},
            {id: 2,name: "two"},
        ],
        [
            {id: 3,name: "three"},
            {id: 4,name: "four"},
        ]
    ]
</script>

{#each items as category, i}
    <h2>Category {i}</h2>
    <ul>
        <List bind:fullArr={items} index={i}>
            {#each category as item}
                <li data-id={item.id} >{item.name}</li>
            {/each}
        </List>
    </ul>
{/each}

{JSON.stringify(items)}

List.svelte

<script>
        import Sortable from 'sortablejs';
        import { onMount } from 'svelte';

        export let fullArr;
        export let index;

        let arr = fullArr[index];
    
        let list;
        let sortable;
        onMount(() => {
            sortable = new Sortable(list, {
                group: "list",  
                onSort: onSort,
            });
        })
        function onSort(){
            
            const order = sortable.toArray() 
            fullArr[index] = order.map(id => {
                
                //id is searched from full array to account for item going between lists
                return fullArr.flat().find(item => item.id == id)
            })
        }


</script>

<div bind:this={list}>
    <slot></slot>
</div>

There is this similar question, but the solution seems to only apply to a singular list and not a group of lists

JS Typewriter twice on page with different string not working

I have on 2 different pages of my website a typewriter effect, once with a string in spanish, another location string in english. But I cannot get this to work.

My HTML in one part is the following, this works.

<div class="container">    
    <div id="typewriter"></div>                    
</div>    

The 2nd part where it isnt working is

<div class="container">
    <div id="english-typewriter" class="medium-text serif"></div>                    
</div> 

The JS is the following

const spanishInstance = new Typewriter('#typewriter', {
  strings: ['hoteles', 'restaurantes'],
  autoStart: true,
  loop: true,
});

const englishInstance = new Typewriter('#english-typewriter', {
  strings: ['hotels', 'restaurants'],
  autoStart: true,
  loop: true,
});

How can I get the English part to work as well?

I have tried changing the IDs to something completely different, but this doesnt work either.

How to convert string using a map, by finding the longest matching key possible?

I have a string which I need to convert into another string using the following mapping:

"a": "X",
"b": "Y",
"c": "MN",
"ab": "P",
"<>": "Q",

For example:

"acb<>ab" -> "XMNYQP"

and its reverse:

"XMNYQP" -> "acb<>ab"

The issue is that if I traverse the string characters, and check the map for each character, let’s say for a, I also need to check if map contains other keys starting with a and the next character of my string is such that it matches one of the keys. I want to match the longest key possible.

How to do this in optimised way?

Not getting user details on google signin in JS

I am using the new way of google login mentioned here. However I am getting only the client_id, cliendId, credential(token), and select_by: “btn” as response. I would also like to get details such as user email in response, as we need it to verify the email. Given below is the HTML code I’m using, and the call back function:

<div id="g_id_onload"
     data-client_id="MY_CLIENT_ID"
     data-callback="handleCredentialResponse"         
</div>
<div class="g_id_signin" data-type="standard"></div> 

The callback is simply:

function handleCredentialResponse(data){
    console.log(data)
}

Currently the login page opens up in a new tab, I would like to get it as a popup. Any help is greatly appreciated!

Load npm packages using require.js

Note: I have already found this SO question that appears to be a duplicate, but the answer does not seem to be correct: using requirejs to load npm packages

If I understand the require.js documentation here (second paragraph) correctly it should be possible to include npm packages without any special configurations. It even essentially says “don’t touch anything and it should work”.

All I should have to do is install require.js via npm and in my html file call the main script via require.js:
<script data-main="js/main" src="node_modules/requirejs/require.js"></script>

Now I have this module in require.js format that does stuff that requires the mat4 from glMatrix (installed via npm):

define(["gl-matrix/mat4"], function(mat4) {
    return function() {
        //...
        const projectionMatrix = mat4.create();
        //...
    }
});

But when I run it I get an error like: GET file:///X:/projname/js/gl-matrix/mat4.js net::ERR_FILE_NOT_FOUND which to me very much looks like it tries to use the normal js folder where the main script is, rather than making any attempt at loading any node packages.

Does anyone know if there is anything else I have to configure for it to also read npm packages?

Share const let object from another file

I have an Object {} in node, const or I can do it and let example:

f.js

const fe = {};

function doSomething(string1, string2){
  fe[string1] = string2; // fe {string1 = string2}
}

With this way I fill my Object with values witch working just fine I can see the value fine.

Now I want to access this fe from another .js in node and read the values from it example:

e.js

function doSomethingElse(){
const Val = fe{};
console.log(Val); // The values from the fe in f.js
}

I try different ways with no luck.. any suggestions will be useful

Thanks in advance!

How to find multi variables inside the array in Javascript? [closed]

I have an array and I want the values of my variables to change true if the values I wanted were in the array. I did this by writing several somes, but I think it is not optimal. Can you guide me what should be done in the most optimal way to find the variables inside the array?

It is possible that the number of variables may be even more than 10

myArr = ['a','b', 'c','d','e','f'];

 this.has_a=  myArr.some((element: string) => element == 'a');
 this.has_b=  myArr.some((element: string) => element == 'b');
 this.has_f=  myArr.some((element: string) => element == 'f');

How can I pass a string into a javascript function? [duplicate]

I can’t figure out how to pass a string into a javascript function… how to do it?

onclick="functionName(1, "Text goes here!")"

I’ve tried:

onclick="functionName(1, ""Text goes here!"")"
onclick="functionName(1, ""Text goes here!"")"
onclick="functionName(1, "Text goes here!")"

Nothing works, I keep getting the “unexpected token” error…

Dynamic CSS classes with Vue 3

The class don’t change However the reactive ref is changed
this is js code

   watchEffect(()=>{
          window.addEventListener("scroll", () => { 
              if (window.scrollY > 100) {
              Show.value = true
             }else{
              Show.value= false
             }
            console.log(window.scrollY ,Show.value) 
          })
           return () => {
        window.removeEventListener("scroll")
      }
        });

html code

  <div class="nav" :class="{'nav_black': Show }">
</div>

I don’t Know where is problem to solve

How to access a fetched Resource in a SolidJS Component before returning the JSX?

My SolidJS component fetches a JSON object from a server and I understand how to render it using the returned JSX.

But how do I play with the fetched data before returning the JSX?

const fetchData = async url => {
  let results = await fetch(this.path + url)
  return await results.json()
}

function User() {
  const handleSubmit = e => {
    e.preventDefault()
    signIn({email: "Foo", password: "Bar"})
  }
  const signIn = obj => {
    if (obj.email && obj.password) {
      const [user] = createResource(() => fetchData("json/sign-in/" + obj.email + "/" + MD5(obj.password) ))
      
      console.log(user())
      /* undefined */
      console.log(user().name)
      /* Uncaught TypeError: Cannot read properties of undefined (reading 'name') */

    }
  }
  return (
    <>
      <button onClick={ handleSubmit }>Sign In</button>
    </>
  )
}

export default User

In the example above, the console log returns undefined or an error when trying to access a property. So how do I access this data once it has loaded? Is there a more elegant way of handing this than resorting to setTimeout?

Is there a way to use a string from an array as a JSON field name?

I have an ASP.NET Page with a dropdownlist control – I want to eliminate a post back so I have wired the onclient change event to a js function. Since this drop down feeds a lot of controls with data, I am sending the JS an array of clientIds and the associated JSON field name from the returned data (which is acquired via a WebMethod call which returns JSON data for the record).

Below is just a subset of the amount of clientIds I am dealing with (probably 25 total)

        protected override void OnRegisterScript()
        {
            UxSellerShareholderDdl.OnChange =
                $"SellerShareholder_OnChange(this,{getAllClientIds()});";
        }
        protected struct ClientId
        {
            public string fieldName;
            public string clientId;
        }
        protected string getAllClientIds()
        {
            List<ClientId> ids = new List<ClientId>();
        ids.Add(new ClientId{fieldName = "StreetAddress", clientId = SAddresslbl.ClientID});
        ids.Add(new ClientId{fieldName = "PostalCode", clientId = SZiplbl.ClientID});
        ids.Add(new ClientId{fieldName = "ContactName", clientId = SMainContactlbl.ClientID});
            return new jsonScriptSerializer().Serialize(ids);
        }
function SellerShareholder_OnChange(ddl, ctrlList) {
    waitOn();
    PageMethods.UpdateShareholderInfo(GetSelectedOptionValue(ddl), onSuccess, onError);

    function onSuccess(result) {
        const data = JSON.parse(result);
        console.log(data);        
        for(let i = 0; i < ctrlList.length; i++) {
            let obj = ctrlList[i];
            let fld = obj.fieldName;
            if (fld === "PostalCode") {
                var id= document.getElementById(obj.clientId);
                var idhdn = document.getElementById(obj.clientId+"hdn");
                idhdn.value = data.PostalCode;
                id.innerHTML = data.PostalCode;
            }
            if (fld === "StreetAddress") {
                var id= document.getElementById(obj.clientId);
                var idhdn = document.getElementById(obj.clientId+"hdn");
                idhdn.value = data.StreetAddress;
                id.innerHTML = data.StreetAddress;
            }
            if (fld === "ContactName") {
                var id= document.getElementById(obj.clientId);
                var idhdn = document.getElementById(obj.clientId+"hdn");
                idhdn.value = data.ContactName;
                id.innerHTML = data.ContactName;
    }
      }
        waitOff();
    }

    function onError(result) {
        waitOff();
        alert('Something wrong.');
    }
}

Instead of all the fld === "Address" then ctrl.innerHTML = data.Address can this be simplified in the loop to do something like ctrl.innerHTML = data.{fld} (so it equates to data.Address)?

Are there better ways in general to achieve what I am trying to accomplish here?