how can i use javascript to generate random svg shapes?

I am trying to develop a font using inkscape but it follows patterns to create characters and i wanted to see how many characters can be generated following the pattern. i tried copying different random word generator codes and edit them but it never worked because i don’t know how i can make the javascript to generate the characters(which are in svg format) randomly. The characters are 6 bars; 3 verticle and 3 horizontal like one bar,two bars n three bars (| || |||),then 7 circles that are given unique positions around the bars.

Own individual price of products for each parameter in javascript

I’m making a pizza delivery website, each pizza comes in three sizes, each size has its own price. How can I write a code so that each pizza has its own price, and also the price differs depending on the size of one pizza with vanila javascript.
In html I have two pizza models similar to each other, but they cost the same. In order not to clutter up the code and not make it readable, I added only one

        <div class="card" >
            <div class="productInCart">
                <img src="/images/picca/4-seasons.png" width="250px" alt="">
                <h3 class="title">Four seasons</h3>
                <p class="description">
                    Bacon, Ham, Mushrooms, Chicken, Onion, Olives,
                    Pickled Cucumbers, Hunting sausages, Pepperoni
                </p>
                <div class="picca_size">
                    <label  data-size="small"   class="btnActive">20sm</label>
                    <label  data-size="medium" class="btnActive">28sm</label>
                    <label  data-size="large"   class="btnActive">33sm</label>
                </div>
                    <div class="wrapperPrice">
                    <p class="price">$<span>0</span></p>
                    <button class="button-30 addToCart" role="button" data-product-id="1">
                        add to cart
                    </button>
                </div>
            </div>
        </div>

      

Javascript file

window.addEventListener( 'click', function(event){

// buttons for size picca and price
if (event.target.closest('.card')){
const cardWrapper = event.target.closest('.card')
const btnActiveSmall = cardWrapper.querySelector('[data-size="small"]')
const btnActiveMedium = cardWrapper.querySelector('[data-size="medium"]')
const btnActiveLarge = cardWrapper.querySelector('[data-size="large"]')
price = cardWrapper.querySelector('.price span')


if (event.target.className == 'btnActive'){

    // active off buttons
    btnActiveSmall.classList.remove('active')
    btnActiveMedium.classList.remove('active')
    btnActiveLarge.classList.remove('active')

 if(event.target.dataset.size == "small"){
    event.target.classList.add("active")
    price.textContent = '12';
 }
 else if(event.target.dataset.size == 'medium'){
    event.target.classList.add('active')

    price.textContent = '16';
 }

 else if(event.target.dataset.size == 'large'){
    event.target.classList.add('active')
    price.textContent = '20';   
 }
}

How to use multiple CSS modules with Tailwind in Remix.js?

I’m using Remix with Tailwind css.
currently I followed the tailwind and remix docs to add a global css file:

"scripts": {
  "dev:css": "tailwindcss -i ./styles/tailwind.css -o ./app/styles/tailwind.css -w"
}

But what if I want to have a tailwind css file for a single component? like so:

# app/components/button.css
.button-primary {
  @apply bg-slate-400;
}
// app/components/Button.jsx
import './button.css'

export function Button() {
  return <button className='button-primary'>My Button</button>
}

Remix doesn’t throw any errors but the styles are not applied, not sure if this is related to tailwind not parsing the button.css file or remix’s issue

How to remove letters from string? [duplicate]

I need to write a function that returns a string without the characters ‘a’ and ‘s’. For example, the string ‘SAverageSsA’ will be returned by the function ‘verge’. And the string ‘AsaAAs’ will return an empty string. How can i do this?

let testString = "AsSverage";

function removeAs(string) {}

removeAs(testString);

else if statement not responding

Basically, I have a project with a form that I validate with useForm from react-hook-form. Everything Is working fine, I have an onSubmit function which checks if the validation is correct and transfers the user to the next page. I have an if statement in that onSubmit function, which works fine, however, If I put an else if statement or an else statement in the same function, I get no response whatsoever, no errors, no bugs, just nothing and I’m wondering why that’s happening. Here’s the onSubmit function :

const [background, setBackground] = useState(false)
const onSubmit = (data) => {
    if(data.name.length >= 2 && data.email.includes("something")){
        setState(true);
        setCorrect(true);   
    }else if(data.name.length < 2){
        setBackground(true)
    }
}

the If statement still works, but the else statement doesn’t respond. Here’s the shortened version of the form : “

<form onSubmit={handleSubmit(onSubmit)}>
       {errors.name && 
       <Card classname="card1" text="Please enter a valid name" title="Name" />} 
       <div className='tickDiv'>
           <input style={{backgroundColor: background ? "red" : null}} value={values.name} 
            name="name" type="text" placeholder="Name*"
            {...register("name",{onChange:handleChange, required:true, minLength:2})} />
            {correct? <img className='tick' src={tick} /> : null}
        </div>
        <button type='submit' onClick={handleClick} className='next-button'><span>Next</span> 
        </button>
</form>


I just want to be able to change the background color of the input If the characters of value is less than 2 . Thank you in advance.

How many times a string containes in substring – JavaScript

I have an array:

var textWord = [ 'FORTWO', 'ELECTRIC' ];

and a json object:

var modelsList = {
    'FOR FOUR' : null,
    'FOR FOUR DIESEL' : null,
    'FOR FOUR EV' : null,
    'FORTWO CABRIO ELECTRIC DRIVE' : null,
    'FORTWO Cabrio' : null,
    'FORTWO Cabrio Diesel' : null,
    'FORTWO Coupe' : null,
    'FORTWO Coupe Diesel' : null,
    'ROADSTER' : null,
    'ROADSTER Coupe' : null,
}

I want to find how many times find the word of array into json object. The null of object represent the times it was found.
My code is:

var textWord = [ 'FORTWO', 'ELECTRIC' ];
var modelsList = {
    'FOR FOUR' : null,
    'FOR FOUR DIESEL' : null,
    'FOR FOUR EV' : null,
    'FORTWO CABRIO ELECTRIC DRIVE' : null,
    'FORTWO Cabrio' : null,
    'FORTWO Cabrio Diesel' : null,
    'FORTWO Coupe' : null,
    'FORTWO Coupe Diesel' : null,
    'ROADSTER' : null,
    'ROADSTER Coupe' : null,
}
var counter = 0;
 for(let i=0; i < textWord.length; i++){
    for (let modelsListText in modelsList) {
        if (modelsListText.toUpperCase().includes(textWord[i].toUpperCase())) {
            modelsList[modelsListText] = counter++;
        }
    }
}
console.log(modelsList);

The result is:

{
  'FOR FOUR': null,
  'FOR FOUR DIESEL': null,
  'FOR FOUR EV': null,
  'FORTWO CABRIO ELECTRIC DRIVE': 5,
  'FORTWO Cabrio': 1,
  'FORTWO Cabrio Diesel': 2,
  'FORTWO Coupe': 3,
  'FORTWO Coupe Diesel': 4,
  ROADSTER: null,
  'ROADSTER Coupe': null
}

But the result I want to get is:

{
  'FOR FOUR': null,
  'FOR FOUR DIESEL': null,
  'FOR FOUR EV': null,
  'FORTWO CABRIO ELECTRIC DRIVE': 2, //Match and FORTWO and ELECTRIC
  'FORTWO Cabrio': 1, //Match ONLY FORTWO
  'FORTWO Cabrio Diesel': 1, //Match ONLY FORTWO
  'FORTWO Coupe': 1, //Match ONLY FORTWO
  'FORTWO Coupe Diesel': 1, //Match ONLY FORTWO
  ROADSTER: null,
  'ROADSTER Coupe': null
}

How to run a code when a button(div) is hold and stop when not holding?

Html (js, css) code

I want to make the code run when the button is hold(long press)

Here is the code i tried:

Html

<div class="console">
     <input id="console" type="button" value="Console log" onmousedown="hold()" onmouseup="stop()">
</div>

JavaScript

var holdup;
function hold() {
               holdup = setInterval(function() {
                    console.log(2);
                  }, 100);
                }
function stop() {
  clearInterval(holdup)
}

But this code didn’t work, how to make it work?

Save current date from Lambda function but get past date in MongoDB

I write a nodejs code to run it on Lambda. The function mainly doing craw data from other sites and save to my MongoDB. I have a problem when saving date value. In code I have date like this which is current time.

const date = new Date(new Date()).toISOString()

then insert to DB

await db.collection("videos").insertOne(dataObj) // dataObj contains date field

I do the log on Lambda and get the correct date. But when saving to MongoDB with code below, it has been insert to DB but with wrong date value, date is in the past. I also try with new Date() but get same issue.

Here you can see the screenshot, the log data and inserted data.
enter image description here

Hope you can help me to resolve this problem.

Thank you

regex to filter JSX?

I am building a website that compiles UI/UX design into JSX code. The compiled JSX, however, needs to be polished in order for it to be copy and pasted into code editors. I am an absolute beginner to regex reaching for help.

Below is the original JSX that I want to polish.

<div
    className="KawzbsFu6Gq5HC7iTbxA"
    style={{
      top: 1000,
      left: 1000,
      width: 390,
      height: 800,
      cursor: "default",
    }}
  >
    <div
      className="OJf6lzDx8YDbym6BV0sB"
      draggable="false"
      style={{
        top: 159,
        left: 92,
        height: 61,
        width: 86,
        backgroundColor: "rgb(226, 226, 226)",
      }}
    />
    <div
      className="OJf6lzDx8YDbym6BV0sB"
      draggable="false"
      style={{
        top: 305,
        left: 88,
        height: 133,
        width: 143,
        backgroundColor: "rgb(226, 226, 226)",
      }}
    />
    <div
      className="WBzerzDgrM32AmgQJbEw"
      style={{ top: 234, left: 270, fontSize: 12, color: "rgb(226, 226, 226)" }}
    >
      asdasdsad
    </div>
  </div>

My goal is to,

  1. remove all className='...'s.
  2. remove parent div‘s top=..., left=... from its style.
  3. add position='relative' to parent div‘s style.
  4. add position='absolute' to all child divs’ style.

The outcome is expected to be like this.

<div
    style={{
      width: 390,
      height: 800,
      position: 'relative', /* added */
      cursor: "default",
    }}
  >
    <div
      draggable="false"
      style={{
        top: 159,
        left: 92,
        height: 61,
        width: 86,
        backgroundColor: "rgb(226, 226, 226)",
        position: 'absolute', /* added */
      }}
    />
    <div
      draggable="false"
      style={{
        top: 305,
        left: 88,
        height: 133,
        width: 143,
        backgroundColor: "rgb(226, 226, 226)",
        position: 'absolute', /* added */
      }}
    />
    <div
      style={{ top: 234, left: 270, fontSize: 12, color: "rgb(226, 226, 226)" }}
      position: 'absolute', /* added */
    >
      asdasdsad
    </div>
  </div>

I went to regex 101 and did some tries but I couldn’t go further than (?:className=")

React Native How to convert fetch to axios?

I’m trying to change my project from using fetch to axios. When I tried to change it, I wasn’t able to make it work just like it should be when I used fetch.

Using Fetch:

        fetch(URLs._dashboard, {
        method: "GET",
        headers: {
            'Content-Type': 'application/json',
            "Accept": "application/json",
            'Authorization': myToken,
        },
        signal: abortCont.signal,
        }).then((response) => response.json())
        .then(async (result) => {
            setApiData(result); 
            AsyncStorage.setItem('@code', result.code);
        })
        .catch((error) => {
            if(error.name === 'AbortError'){
                console.log('fetch aborted');
            } 
        });

Using Axios

    axios({
        method: 'get',
        url: URLs._dashboard,
        headers: {
            'Content-Type': 'application/json',
            "Accept": "application/json",
            'Authorization': myToken,
        }, 
        signal: abortCont.signal,
    }).then((response) => response.json())
    .then(async (result) => { 
            setApiData(result); 
            AsyncStorage.setItem('@code', result.code);
    })
    .catch((error) => {
        if(error.name === 'AbortError'){
            console.log('fetch aborted');
        }  
    });

Get brower network requests with Selenium for JavaScript

I’m using Selenium with chromeDriver for JavaScript and I want to get all network logs from the Browser with their payload.
I searched a lot but, there are ways to get the requests, but only the URL and not the payload.
The Chrome Devtools are able to record and track the requests in all of their details, why is there no simple way to do it in JavaScript?

Any help is appreciated!

Uncaught TypeError: Cannot read properties of undefined while calling object from api [duplicate]

function App() {
  const [test,setTest]=useState([]);
  
  const [lest,setLest]=useState("hello");
  
  useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/comments')
   .then(res=>res.json())
   .then(data=>setTest(data))
  },[]);
  console.log(test[1]);
  test[0].id<test[1].id?console.log('Yeah'):console.log('nah');
}

This shows the following error in the browser console:-
The error pics

javascript : why ajax in function return undefined?

I have a function with ajax in it :

    function get_cart_count(){
      $.ajax({
        url: "/cart/count",
        method: "get",
        async: false,
        success: function (count) {
            if (count > 0) {
                // console.log('count is :' + count);
                return count;
            }
        },
      });
    }

as you see the async is false.

the count is log is 1,
but when I console.log(get_cart_count()) , it give me undefined !
why this happening ?

thanks

uncaught typeerror cannot read property of null (reading ‘displayname’)

I know this question has been asked many times before and I have tried the answers, but my problem still persists.

I am making a website using ReactJS, Redux with Firebase Authentication and Realtime DB.
I am trying to fetch displayName and photoURL using props from redux. These are the relevant codes.

index.js

const store = createStore(combinedReducers)

const IndexRoutes = (props) => {

  useEffect(() => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        props.setUser(user)
        props.history.push("/");
      } else {
        props.setUser(null)
        props.history.push("/login");
      }
    })
  }, []);
  console.log(`user: ${props.currentUser}`)

  return (
    <Switch>
        <Route path='/login' component={Login} />
        <Route path='/register' component={Register} />
        <Route path='/' component={App} />
    </Switch>
  )
}

const mapStateToProps = (state) => {
  return {
    currentUser: state.user.currentUser
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    setUser: (user) => {dispatch(setUser(user))}
  }
}
const IndexRouter = withRouter(connect(mapStateToProps, mapDispatchToProps)(IndexRoutes))

root.render(
  <Provider store={store}>
    <Router>
      <IndexRouter />
    </Router>
  </Provider>,
  document.getElementById('root')
);

The console.log() returns user: null, which is causing the problem. I am positively loggedIn to the app, but still showing user null.

actions.js

export const SET_USER = 'SET_USER'

reducers.js

import { combineReducers } from "redux";
import { SET_USER } from "./Actions";

let defaultState = {
    currentUser: null
}

const userReducer = (state = defaultState, action) => {
    if (action.type === SET_USER) {
        let payload = action.payload
        state = {...payload}
        return state
    }
    return state
}

export const combinedReducers = combineReducers({user: userReducer})

creators.js

import { SET_USER } from "./Actions";

export const setUser = (user) => {
    return {
        type: SET_USER,
        payload: {
            currentUser: user
        }
    }
}

fetching displayName and photoURL using props

const UserInfo = (props) => {

    return (
            <div>
                <Box
                    display={'flex'}
                    flexDirection={'row'}
                    alignItems='center'
                    justifyContent={'center'}
                    color='white'
                    paddingTop={2}
                    paddingBottom={2}
                    sx={{height: '100%', flex: 1}}
                >
                    <Avatar
                        alt='profile-pic'
                        src={props.user.photoURL} 
                    />
                    <Typography
                        sx={{ml: 10}}
                    >
                        {props.user.displayName}
                    </Typography>
                </Box>
            </div>
        )
}

const mapStateToProps = (state) => {
    return {
        user: state.user.currentUser
    }
}

export default connect(mapStateToProps)(UserInfo)
        

But, whenever I refresh the page, I get this error uncaught typeerror cannot read property of null (reading 'displayname')

Also, I am using Firebase for backend, even if I use firebase.auth().currentUser.displayName to show data instead of props, it still shows the same error. (although I am already authenticated and signed in).