Getting the file size of a file in javascript

<input id="archivo" name="archivo" type="file">

So my field of type file is called archivo which parent is formIncidencia, so what i’m doing to find it is:

$('#formIncidencia').find("[id='archivo']");

This works fine but when i’m trying to do:

 $('#formIncidencia').find("[id='archivo']").files[0].size; 

it’s not working like that, and i’m uploading a file so don’t know what it’s happening..

Created animation for title and subtitle transform translateY () with css

I am working on a project with vuetify I have created a background image cover over background image I have a title, subtitle and a button.

I should to created same effect animation with css:
Firstly, I should to display title with transform translate Y()
to be coming with animation

Secondly, I should to display subtitle with transform translate Y()
to be coming with animation with the same logic that first, but subtitle should, will be coming after title with some seconds.

For button, we don’t need for anyone animation transform translate Y() just to display in the same position after subtitle with same seconds.
I have done until now to create effect animation for all three element display together, I am sharing my code:

.slide-fade-1-enter-active {
    transition: all .7s ease-out;
}
.slide-fade-1-enter {
    transform: translateY(200px);
    opacity: 0;
}

.slide-fade-2-enter-active {
    transition: all 1s ease-out;
}
.slide-fade-2-enter {
    transform: translateY(200px);
    opacity: 0;
}

.slide-fade-3-enter-active, .slide-fade-3-leave-active {
    transition: opacity 1s;
}
.slide-fade-3-enter, .slide-fade-3-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
}
    <div class="hero-inner">
        <transition name="slide-fade-1" appear>
            @if ($block->input('title') != '')
                <h1 class="text-white "> {{ $block->input('title') }} </h1>
            @elseif($block->image('title_image'))
                <img class="hero-title-img" src="{!!$block->image('title_image', 'default', ['fm' => null])!!}">
            @endif
        </transition>
        <transition name="slide-fade-2" appear>
            @if ($block->input('subtitle') != '')
                <h3 class="text-white  mt-15"> {{ $block->input('subtitle') }} </h3>
            @endif
        </transition>
        <transition name="slide-fade-3" appear>
            @if ($block->input('cta_label') != '')
                <v-cta link="{!!$block->input('cta_link')!!}" label="{!!$block->input('cta_label')!!}"></v-cta>
            @endif
        </transition>
    </div>

But we want to  create exactly  affect animation transform translate  by UI/UX design in the Figma. enter link description here

Nodejs + Mysql, How do I find a name if already exist before inserting the name?

Hi I’m learning nodejs with mysql. I have crated a method to post a name in database. But now I want to execute another method which first check if name does not exist then run post name method

NOTE My table only containes ‘nick_names’ column

Here is my route in router file router.post(‘/’, NickNamesController.createName)

Actual result-> I can post names here: Controller.js

exports.createName = (req, res) => {
  const reqData = new NickNamesModel(req.body);
  NickNamesModel.addNewName(reqData , (err, name) => {
            if (err){
                return res.status(400).send(err.code);
            }
            res.status(201).send({success: true, message: 'Name has been inserted successfully', data: name});
        });
  
}

Expected: Controller.js Please have a look here This is what I want to achieve

exports.createName = (req, res) => {
  const reqData = new NickNamesModel(req.body);

// first check if name exist or not?
  const ifExist = NickNamesModel.getNameIfExist(reqData.nick_name, (err, name) => {
       if(err){
           return err.code;
        }
      return name;
})

// checking if ifExist has 1 then value already exist. If 0 then not exist
  if(ifExist != 0) {
    return res.status(400).send({success: false, message: Duplicate Name});
} else {
  NickNamesModel.addNewName(reqData , (err, name) => {
            if (err){
                return res.status(400).send(err.code);
            }
            res.status(201).send({success: true, message: 'Name has been inserted successfully', data: name});
        });
  }
  
}

NickNamesModel.js

NickNamesModel.addNewName = (reqData, result) => {
    dbConn.query('INSERT INTO nick_name_table SET ? ', reqData, (err, res) => {
        if (err) {
            console.log('Error while inserting name', err);
            result(err, null);
        }else {
            console.log('Name inserted successfully');
            result(null, res);
        }
    })
}

// Method to check if nick name already exist then return 1 else 0
NickNamesModel.getNameIfExist = (nick_name, result) => {
    dbConn.query('SELECT EXISTS('SELECT station_name FROM stations SET WHERE station_name=? LIMIT 1)', nick_name, (err, res) => {
        if (err){
            console.log('Error while fetching stations', err);
            result(null, err);
        } else {
            console.log('Stations fetched successfully');
            result(null, res)
        }
    })
}

Uncaught SyntaxError: Unexpected token u in JSON at position 0 while fetching data from localstorage [duplicate]

I’m new to react and in this simple ToDo app, I’m trying to fetch notes from localStorage and if they exist, assign it to react notes initial state. Here is the code:

import React, {useState, useEffect}   from 'react';
import ReactDOM from 'react-dom';


 
 const NoteApp = () => {
   const notesData = JSON.parse(localStorage.getItem('notes'));
   const [notes, setNotes ] = useState(notesData || []);
   const [title, setTitle] = useState('');
   const [body, setBody] = useState('');

   const addNote = (e) => {
     e.preventDefault();
    const note =  {
      id:Math.random(),  
      title: title,
       body: body}

     setNotes([...notes, note]);
     setTitle('');
     setBody('');
   }

   const removeNote = (title) => {
     setNotes(notes.filter(note=> (note.title !== title) ));
   }
   useEffect(()=> {    
   localStorage.setItem('notes', JSON.stringify(notes))
  });
  

   return ( 
     <div>
      <h1>Notes </h1>
      {notes && notes.map((note) => (
        <div key={note.id}>
          <h3>{note.title}  </h3>
          <p>{note.body}</p>
          <button onClick={()=> removeNote(note.title)}>x</button> <br />
        </div>
      ))}
 
     <form  onSubmit={addNote}>
       <input type="text" value={title} onChange={e => setTitle(e.target.value)} /><br /> <br /> 
       <textarea value={body} name="body" id="" cols="30" rows="10" onChange={e => setBody(e.target.value)}></textarea>
       <br /><br />
 
       <button>add note</button>
     </form>     
     </div>
    );
 }

 
ReactDOM.render(
  <React.StrictMode>
    <div>
      <NoteApp />
    </div>
  </React.StrictMode>,
  document.getElementById('root')
);

However I get a blank page and this massive error:

VM19427:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at NoteApp (index.js:7:1)
    at renderWithHooks (react-dom.development.js:14985:1)
    at mountIndeterminateComponent (react-dom.development.js:17811:1)
    at beginWork (react-dom.development.js:19049:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
NoteApp @ index.js:7
renderWithHooks @ react-dom.development.js:14985
mountIndeterminateComponent @ react-dom.development.js:17811
beginWork @ react-dom.development.js:19049
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22776
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:65
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7
react-dom.development.js:20085 The above error occurred in the <NoteApp> component:

    at NoteApp (http://localhost:3000/static/js/bundle.js:28:26)
    at div

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:20085
update.callback @ react-dom.development.js:20118
callCallback @ react-dom.development.js:12318
commitUpdateQueue @ react-dom.development.js:12339
commitLifeCycles @ react-dom.development.js:20736
commitLayoutEffects @ react-dom.development.js:23426
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
commitRootImpl @ react-dom.development.js:23151
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority$1 @ react-dom.development.js:11276
commitRoot @ react-dom.development.js:22990
performSyncWorkOnRoot @ react-dom.development.js:22329
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:65
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7
react-dom.development.js:4005 Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information.
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4005:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
    at workLoopSync (react-dom.development.js:22707:1)
    at renderRootSync (react-dom.development.js:22670:1)
    at performSyncWorkOnRoot (react-dom.development.js:22293:1)
    at scheduleUpdateOnFiber (react-dom.development.js:21881:1)
    at updateContainer (react-dom.development.js:25482:1)
    at react-dom.development.js:26021:1
invokeGuardedCallbackDev @ react-dom.development.js:4005
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22776
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:65
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7

React wrong result on the change of state

I’m new to react and working on simple eCommerce application. I am changing the quantity of in the cart when it is added more than one times but it gives wrong result(As we can see in the output the ‘quantity’ I print and in the object are different eg. before:1 after:2 but in the object it is 3).I’ll appreciate any help. Thank You!!

here is my reducer.js

export const initialState = {
    basket : [],

}


const reducer = (state, action) => {
    switch(action.type){
        case "ADD_TO_BASKET":
            const newIndex = state.basket.findIndex((basketItem)=> basketItem.id==action.item.id)
            if(newIndex >= 0){
                const newBasket = [...state.basket];
                console.log(newBasket);
                console.log("quantity "+newBasket[newIndex].quantity);
                newBasket[newIndex].quantity+=action.item.quantity;
                console.log(newBasket);
                console.log("quantity "+newBasket[newIndex].quantity);
                return{
                    ...state,
                    basket: [...newBasket]
                }
            }
            return{
                ...state,
                basket: [...state.basket ,action.item]
            }
            .
            .
            .

export default reducer;

here is my checkout.js:

import { useStateValue } from "./StateProvider"
function Checkout() {
    const [{basket}, dispatch] = useStateValue();
return (
        <div className='checkout'>
            <div className="checkout__left">
                <img src="https://images-na.ssl-images-amazon.com/images/G/02/UK_CCMP/TM/OCC_Amazon1._CB423492668_.jpg" alt="" className="checkout__ad" />
                <div>
                    <h2 className='checkout__title'>
                        Your Shopping Basket
                    </h2>
                    {basket.map(item => (
                        // console.log("checkout product quantity: "+JSON.stringify(item.quantity)),
                        <CheckoutProduct 
                            key={i++}
                            id = {item.id}
                            title = {item.title}
                            image = {item.image}
                            price = {item.price}
                            rating = {item.rating}
                            quantity = {item.quantity}
                        />
                    ))}
 .
 .
 .

StateProvider.js:

import React, { createContext, useContext, useReducer } from 'react'

//prepares the data layer
export const StateContext = createContext();

//wrap our app and provide the data layer
export const StateProvider = ({ reducer, initialState, children }) => (
    <StateContext.Provider value={useReducer(reducer, initialState)}>
        {children}
    </StateContext.Provider>
);

//pull infromation from the data layer
export const useStateValue = () => useContext(StateContext);

Output in console:

-> [{…}]0: {---, quantity: 3}length: 1[[Prototype]]: Array(0)
-> quantity 1
->[{…}]0: {---, quantity: 3}---
-> quantity 2

How to solve ERR_TOO_MANY_REDIRECTS that is happening due to one middleware that forces https connection?

My middleware

exports.redirectToHTTPS = (req, res, next) => {
    if (req.protocol == "https") {
        return next()
    }
    const redirect_not = req.query.redirect
    
    console.log("!!!!! Connection not secure")
    const redirect_url = ['https://', req.get('host'), req.originalUrl].join('')
    console.log("REDIRECT_URL:- " + redirect_url)
    return res.redirect(redirect_url)
}

in index.js

app.use(redirectToHTTPS)

I am using express.js and node.js

Need to wait for Google API but sleep function doesn’t work

I need to load Google Maps API in my svelte project.
I’m using js-api-loader npm package.

Here’s the peace of code that I use to load the Google API:

loader.js

import { Loader } from '@googlemaps/js-api-loader';

let googleIsLoaded = false;

async function loadGoogleMapsAPI() { 
  if (!googleIsLoaded) {
    const libraries = ['places'];
    try {
      const loader = new Loader({
        apiKey: API_KEY,
        version: 'weekly',
        libraries,
      });
      console.info('Loading Google API ...'); // LOGGED 1st -> OK
      await loader.load();
      console.info('Google API is loaded'); // LOGGED 6th -> KO
      googleIsLoaded = true;
    } catch (error) {
      throw new Error(`Google API Loader failed ${error.message}`);
    }
  }
}

When a page loads, it first hits the route defined below
route/index.svelte:

<script context="module">
  export const ssr = false;
</script>

<script>
  import MyComp from '$components/MyComp.svelte';
  import { loadGoogleMapsAPI } from '$lib/loader.js';

  init();

  async function init() {
    try {
      await loadGoogleMapsAPI();
    } catch (e) {
      console.error(e);
    }
  }

  <MyComp />

Then, MyComp.svelte below is loaded:

import { onMount } from 'svelte';

let google;
onMount(() => {
    console.log('mounted'); // LOGGED 2nd -> OK
    google = window.google;
    if (google === undefined) {
      console.log('google is undefined'); // LOGGED 3rd -> OK
      sleep(5000, init());
    } else {
      console.log('google is defined');
    }
});

async function init() {
    ...
    autocompleteWidget = new google.maps.places.Autocomplete(input, options); 
/////////// LOGGED 5th -> KO: EXCEPTION GOOGLE IS NOT DEFINED /////////
}

and here the helper function to make the sleep

helpers.js


export async function sleep(time, fn, ...args) {
  console.info('sleep ' + time + 'ms');  // LOGGED 4th -> OK
  await timeout(time);
  console.info('woken'); // LOGGED 7th -> KO
  return fn(...args);
}

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

But for whatever reason, the init() function is triggered ignoring the sleep(5000, init()) call :/

Thank you for your help.

console

loader.js: Loading Google API ...
MyComp.svelte: mounted
MyComp.svelte: google is undefined
helpers.js: sleep 5000ms
MyComp.svelte:106 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'maps')
helpers.js: Google API is loaded
helpers.js: woken

Get site-URL-parameter from iframe (same domain)

I’ve got two html pages (site, sub).
sub.html is embeded in the site page as an iframe.
On the sub page I am running the following js:

    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const param1 = urlParams.get('param1')
    const param2 = urlParams.get('param2')
    alert (param1 + param2)

It works fine. When I open …/sub.html?param1=hello&param2=world, I end up with “Hello World”.
But the URL-parameters are on “site.html” not on sub.html.
So I open site.html?param1=hello&param2=world how do I get those URL parameters?
I read that that is not possible if both sites are not on the same domain. In my case – they are on the same domain, so that should not a problem. At the time I am just testing it locally.

nested unique flat in javascript

Is there some super new ES JavaScript magic that can achieve this ? (I can write a function to achieve this, was just wondering if any new ES202* technique exists )

let arr = [
    ['cb', ''],
    ['cb', '34'],
    ['cb', '35'],
    ['rb', '1']
];

/*
Required Output : 
[['cb', ['34', '35']], ['rb', '1']]
*/

console.log([...new Set(arr.flat(1))])

IF else && statement in React JSX

Hey guys I am having trouble understanding how to create an IF else & statement in React. All documentation, videos and questions that I find online only show the method of doing one of them, either an IF else or an &&

Basically the IF statement I am trying to create within the JSX looks like this.

If(data.AP == "1" && data.MP == "1")
{
set.Text("Both")
}
else if(data.AP == "0" && data.MP == "1")
{
set.Text("Manager")
}
else if(Data.AP == "1" && data.MP == "0")
{
set.Text("Payroll")
}
else{
setText("Not Approved)
}

A fairly simple IF statement in Java but I can’t seem to find a way to translate this into JSX. So far this is the furthest I have got and it keeps giving me errors whenever I chop and change it depending on the documentation I am reading. I know how to use ?? Ternary operators and && operators but using them together doesnt seem to work for me.

 return (

   {
  data.MP == "1" && data.AP == "1" && (
     <td colSpan="1">{"Both"}</td> ) : null
  }

)

export json data as csv in react

Hey guys I’m trying to add a download button in order to export some Json data as csv but this is not working for me. The data i want to export is inside shareFilterHead and shareFilterRows and the data is in Json. I’m using the CsvDownloader from ‘react-csv-downloader’.

import React, {Component} from "react";
import DynamicTable from '@atlaskit/dynamic-table';
import styled from 'styled-components';
import CsvDownloader from 'react-csv-downloader';

export default class ShareFilter extends Component {

constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      shareFilterRows: []
    };
  }

componentDidMount() {
    fetch(AJS.contextPath() + "/rest/securityrestresource/1.0/results?check=ShareFilter")
    .then((res)=>{
        if(res.ok) {
            return res.json();
        }
    }).then((res)=>{
  this.setState({
    isLoaded: true,
    shareFilterRows: res.map((row, index) => ({
      key: `row-${index}-${row.filterID}`,
      cells: [{
        key: `${row.filterID}`,
        content: row.filterID,
        },
        {
        key: `${row.author}`,
        content: row.author,
        },
        {
        key: `${row.filtername}`,
        content: row.filtername,
        },
        {
        key: `${row.jql}`,
        content: row.jql,
        },]}))
  })
  })
  }

render() {
const { error, isLoaded, shareFilterRows } = this.state;
if (error) {
  return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
  return <div>Loading Shared Filters...</div>;
} else {
  return (<Wrapper>
    <div>
    <DynamicTable
      head={shareFilterHead}
      rows={shareFilterRows}
      rowsPerPage={10}
      defaultPage={1}
      loadingSpinnerSize="large"
      isLoading={false}
      isFixedSize
      defaultSortKey="filterID"
      defaultSortOrder="ASC"
      onSort={() => console.log('onSort')}
      onSetPage={() => console.log('onSetPage')}
      
      />
  </div>
  </Wrapper>
  );
  }
}
}

AJS.$(document).on("click", "#downloadShareFilterCheck", function(){

    <CsvDownloader
    filename="myfile"
    extension=".csv"
    separator=";"
    wrapColumnChar="'"
    columns={shareFilterHead}
    datas={shareFilterRows}
    text="DOWNLOAD" />


}); 

PurgeCSS: how to match css with backslash

I am using csspurge using the config file. I have css written as
lg:right-40 and in js it is referred as lg:right-40.
in js backslash is escaped hence purgecss is not able identify all the that contain

cssfile

.lg:right-40 {
    right: 10rem;
}
.lg:right-44 {
    right: 11rem;
}
.lg:right-48 {
    right: 12rem;
}
.lg:right-52 {
    right: 13rem;
}
.lg:right-56 {
    right: 14rem;
}

purgecss.config.js

   const TailwindExtractor = (content) => {
  // Treat every word in the bundle as a CSS selector
  return content.match(/[w-/\:]+(?<!:)/g) || []
}
    new PurgeCSS().purge({
      content: ['./src/**/*.jsx', './src/**/*.js'],
      css: ['./src/login/tailwind_backup.css'],
      safelist:{
        greedy:[/\/]
      },
      extractors: [{
        extractor: TailwindExtractor,
        extensions: ['js', 'jsx'],
      }],
      output: './src/login/tailwind.css'
    })

I want to match css classes with with js classes without

rrestrict the direct url file name with javascript?

hello I’m new to javascript

I just created my first website with 2 pages, eg page1.html and page2.html

if the user is not logged in (page1.html) still they can have access to other pages (page2.html) through URL

I want to stop url access with javascript

Please suggest me how to do it

Click event not working when using arrow functions (jQuery) [duplicate]

I want to add a class to an <h1> element when I click on it. I am using an arrow function, but it is not working.

Here is my code:

<!DOCTYPE html>
    <html lang="en">
    <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">
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.0.min.js"></script>
        <link rel="stylesheet" href="css/style.css">
        <title>Test</title>
    </head>
    <body>
        <h1>Click me!</h1>
        <script src="js/script.js"></script>
    </body>
</html>
$(document).ready(start)

function start(){
    $('h1').click(()=>{
        $(this).toggleClass('h1-click')
    })
}