Shorten the text and prevent it from wrapping

I have problem with flexbox in Bootstrap.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>

<div class="list-group">
<a href="#" class="list-group-item list-group-item-action"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1">lorem ipsum dolor sit amet abcdefg</h5><small class="text-muted"><i class="bi bi-calendar3 text-muted"></i>&nbsp 21.05.2022</small>
  </div>
  <p class="mb-1">333 PLN</p>
  <small class="text-muted">lorem ipsum</small>
  </a>
</div>

When I use it on mobile device, text wraps and it looks weird. Picture
How can I shorten this text and get something like “lorem ipsum dol…” and make date label look normal?

How to remove duplicate number in array jquery?

I want to create random number generator. I have a quantity array. So I push when I create a random number.
quantityArray.push([Math.floor(Math.random() * (endRange - startRange + 1)) + startRange]);

It’s work but this array elements are must be unique. So I write check method like this:

let uniqueSites = quantityArray.sort();
                    let temp = uniqueSites[0];

                    for(let z =1; z<=uniqueSites.length; z++)
                    {
                        if(temp == uniqueSites[z])
                        {
                          uniqueSites.pop(uniqueSites[z]);
                        }
                    } 
    ```

But doesn't work. In my opinion, I removed element and I check length after if length same array is unique else create a random number and push array.

Less not loaded with package

I build npm package to use in other react project,
the components are working byt without less style

inside storybook its working with less
here is the package
npm i @linkne/react-storybook-antdesign

and here is storybook parameters

const path = require('path');
// Export a function. Accept the base config as the only param.
module.exports = {
  "stories": ['../src/**/*.stories.@(js|mdx)'],

  "addons": ["@storybook/addon-links", "@storybook/addon-essentials", "@storybook/addon-interactions"],
  "framework": "@storybook/react",
  core: {
    builder: "webpack5"
  },    
  webpackFinal: async (config, { configType }) => {
    // `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
    // You can change the configuration based on that.
    // 'PRODUCTION' is used when building the static version of storybook.

    // Make whatever fine-grained changes you need
    config.module.rules.push({
      test: /.less$/,
      use: ['style-loader', 'css-loader', 'less-loader'],
      include: path.resolve(__dirname, '../'),
    });

    // Return the altered config
    return config;
  },
};

webpack.config.js

var path = require('path');

module.exports = {
    entry: './components/App.js',
    mode: 'development',
    output: {
        path: path.resolve(__dirname, './public/dist'),
        filename: 'main.js'
    },
    module: {
        rules: [
            {
                test: /.js$|jsx/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-react']
                    }
                }
            },
            {
                test: /.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /.less$/,
                use: ['css-loader', 'postcss-loader', 'less-loader',
                    {
                        loader: "less-loader",
                        options: {
                            lessOptions: {
                                javascriptEnabled: true,
                            }
                        }
                    }
                
                ]
            }
        ]
    }
}

package.json

{
  "name": "react-storybook",
  "version": "0.2.5",
  "description": "Storybook design systems with AntDesign",
  "license": "MIT",
  "private": true,
  "dependencies": {
    "@mdx-js/react": "^2.1.1",
    "@storybook/preset-create-react-app": "^1.2.0",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^14.2.0",
    "antd": "^4.21.2",
    "babel-loader": "^8.2.5",
    "min-indent": "^1.0.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "^5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "storybook": "start-storybook -p 6006 -s public",
    "build-storybook": "build-storybook -s public"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ],
    "overrides": [
      {
        "files": [
          "**/*.stories.*"
        ],
        "rules": {
          "import/no-anonymous-default-export": "off"
        }
      }
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@pmmmwh/react-refresh-webpack-plugin": "^0.5.7",
    "@storybook/addon-actions": "^6.5.9 ",
    "@storybook/addon-essentials": "^6.4.22",
    "@storybook/addon-interactions": "^6.5.9 ",
    "@storybook/addon-links": "^6.5.9 ",
    "@storybook/builder-webpack5": "^6.5.9 ",
    "@storybook/cli": "^5.1.11",
    "@storybook/manager-webpack5": "^6.5.9 ",
    "@storybook/node-logger": "^6.5.9 ",
    "@storybook/react": "^6.5.9 ",
    "@storybook/testing-library": "^0.0.13",
    "babel-plugin-named-exports-order": "^0.0.2",
    "css-loader": "^6.7.1",
    "less": "^4.1.3",
    "less-loader": "^11.0.0",
    "prop-types": "^15.8.1",
    "react-refresh": "^0.14.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.73.0"
  }
}

and this is the package.json from the different project, webpack its exacly the same

{
  "name": "argoportal",
  "version": "1.0.0",
  "description": "",
  "main": "index",
  "directories": {
    "test": "tests"
  },
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://bitbucket.org/linkmobility/argoportal.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "homepage": "https://bitbucket.org/linkmobility/argoportal#readme",
  "dependencies": {
    "@ant-design/icons": "^4.7.0",
    "@ant-design/pro-card": "^1.20.2",
    "@ant-design/pro-components": "^1.1.5",
    "@ant-design/pro-descriptions": "^1.10.71",
    "@ant-design/pro-form": "^1.67.1",
    "@ant-design/pro-layout": "^6.38.0",
    "@ant-design/pro-list": "^1.21.59",
    "@ant-design/pro-skeleton": "^1.0.5",
    "@ant-design/pro-table": "^2.74.1",
    "@babel/core": "^7.17.8",
    "@babel/preset-react": "^7.16.7",
    "@linkne/react-storybook-antdesign": "^0.2.8",
    "@react-keycloak/web": "^3.4.0",
    "activity-detector": "^3.0.0",
    "antd": "^4.20.2",
    "axios": "^0.24.0",
    "babel-loader": "^8.2.4",
    "buffer": "^6.0.3",
    "css-loader": "^6.7.1",
    "highcharts": "^10.1.0",
    "highcharts-react-official": "^3.1.0",
    "html-react-parser": "^1.4.9",
    "moment": "^2.29.3",
    "moment-timezone": "^0.5.34",
    "multiselect-react-dropdown": "^2.0.21",
    "path": "^0.12.7",
    "postcss-loader": "^6.2.1",
    "prop-types": "^15.8.1",
    "react": "^17.0.2",
    "react-confirm-alert": "^2.8.0",
    "react-csv": "^2.2.2",
    "react-date-range": "^1.4.0",
    "react-datepicker": "^4.7.0",
    "react-datetime-picker": "^3.5.0",
    "react-dom": "^17.0.2",
    "react-ga": "^3.3.0",
    "react-gtm-module": "^2.0.11",
    "react-icon-base": "^2.1.2",
    "react-icons": "^4.3.1",
    "react-moment": "^1.1.1",
    "react-paginate": "^8.1.2",
    "react-router-dom": "^6.2.2",
    "react-select": "^5.2.2",
    "react-switch": "^6.0.0",
    "react-timezone-select": "^1.3.1",
    "style-loader": "^3.3.1",
    "umi": "^4.0.0",
    "validator": "^13.7.0",
    "webpack-watch-server": "^1.2.1"
  },
  "devDependencies": {
    "@types/react": "^18.0.14",
    "less": "^4.1.2",
    "less-loader": "^7.3.0",
    "ts-loader": "^9.3.0",
    "typescript": "^4.7.2",
    "webpack": "^5.70.0",
    "webpack-cli": "^4.9.2"
  }
}

How to properly edit a value of a fetched data on react

I have an edit caption of a post feature on my app. I am fetching a get request and then save that data in a state that will display on screen. The problem here is that it take a few second to load that data on screen. After editing the caption, which I have a onChange function that will update the state with the new edited caption. The new edited caption is followed by a put request that will update the caption of the post.
The problem here is that I am getting an error saying to change it to either a controlled or uncontrolled state. What is the right way of doing it?

Below is my code

const PostDetail = () => {
    const navigate = useNavigate();
    const [inputs, setInputs] = useState({ caption: "" });
    const { id } = useParams();

    // once data is fetched, update the edited caption to the post
    useEffect(() => {
        const fetchDetails = async () => {
            const res = await api.get(`/post/${id}`)
                .catch((error) => console.log(error.message))
            const data = await res.data;
            return data;
        }
        fetchDetails()
            .then((data) => {
                setInputs({
                    caption: data.post.caption
                });
            });
    }, [id]);


    const sendRequest = async () => {
        const res = await api.put(`/post/update/${id}`, {
            caption: inputs.caption
        })
            .catch(error => console.log(error));
        const data = await res.data;
        return data;
    }

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log(inputs);
        sendRequest()
            .then((data) => console.log(data))
            .then(() => navigate('/myposts'))
    }

    const handleChange = (e) => {
        setInputs({ caption: e.target.value })
    }

    return (
        <div>
            {inputs &&
                <form onSubmit={handleSubmit}>
                    <Box display="flex" flexDirection="column" alignItems="center" justifyContent="center" boxShadow=" 10px 10px 20px #ccc" maxWidth={500} margin="auto" padding={3} marginTop={10} borderRadius={5}>
                        <Typography fontWeight={"bold"} padding={3} textAlign={"center"} fontSize={22} fontFamily="georgia">Edit Your Post</Typography>
                        <InputLabel sx={{ mb: 1, mt: 2, fontSize: 15 }}>Caption</InputLabel>
                        <TextField value={inputs.caption} name="caption" onChange={handleChange} fullWidth />
                        <Button variant="contained" type="submit" color="warning" sx={{ marginTop: 3 }}>Submit</Button>
                    </Box>
                </form>
            }
        </div>
    )
}

“Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.”

I came across this error int he console. I had a look through the previous questions but they were not much help. Anyone know how I have caused this infinite loop?

“Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.”

import logo from './logo.svg';
import './App.css';
import Movie from './components/Movie'
import React, { useEffect, useState } from 'react';

  const FEATURED_API = "https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1"
  const IMG_API = "https://image.tmdb.org/t/p/w1280"
  const SEARCH_API = "https://api.themoviedb.org/3/search/movie?&api_key=04c35731a5ee918f014970082a0088b1&query="


  function App() {
    const [movies, setMovies] = useState([]);

    useEffect(() => {
      fetch(FEATURED_API)
      .then((res) => res.json())
      .then((data) =>  {
        console.log(data)
        setMovies(data.results);
      });
    },[])
    setMovies(movies)
  

    return <div>{ movies.length > 0 && movies.map((movie) =>  <Movie/>)}</div>
    
}
export default App;

Can’t put more than 3 numbers in an input in ReactJS

I’ve got a big issue on my ReactJS code. I have an input to enter only number “EC” is suppose to be a number. The user can enter his data directly in the put or he can press the button + or – to add or remove 1000. The button +/- works but my input wont work.

Errors :

  • when I press delete in my keyboard, the “000” of 4000 are all delete at once
  • I can’t put more that 4 numbers in the input
  • when I delete everything an “NaN” appear and I can’t put anthing else in the input.

I tried a lot of things such as:

  • pass my input in a type=’number’
  • put the function directly in the onChange{}
  • put Number() instead of parseInt()

Nothing works. Can you help me ?

function Resistance() {
  const [EC, setEC]= React.useState(2000)

  function handlePressEC() {
    const testEC=EC-1000
    if(testEC<=0) {
      setEC(0)
    }
    else {
      setEC(testEC)
    }
  }

  function handleChangeEC(e) {
    const EC = parseInt(e.target.value)
    setEC(EC)
    console.log(EC)
  }

  return (
    <div>
      <div className='flexLigneOF flexLigneV'>
        <div className='textOF'>Economie de charge</div>
        <div className='flexSaisie'>
           <button className='buttonPM' onClick={handlePressEC} > 
              <div className='TextPM'> - </div>
           </button>
           <input className='inputResi'value={EC.toLocaleString().toString()} onChange={handleChangeEC} keyboardType='number-pad'/>
           <button className='buttonPM' onClick={() => {setEC(parseInt(EC)+1000)}}> 
             <div className='TextPM'> + </div>
          </button>
      </div>
     </div>
    </div>
  );
}

export default Resistance;

How to listen for close event of datetime-local in pure JavaScript?

I have an input of type datetime-local where the text field is hidden and showPicker() is used to open the browser interface for the picker GUI. showPicker() is triggered via an onclick event of a custom calendar icon. What I want is to run a function when the picker is closed.

I know that you can do this in jQuery via onClose on their Datepicker widget, but my project does not use jQuery and I am not interested in adding that framework dependency.

The onclose event does not trigger when the datetime-local element loses focus, due to the picker being in the shadowDOM and not the regular document hierarchy. The onblur and onfocusout did not work either.

Here is a minimal example of what I want to see trigger:

const picker = document.getElementById("datePicker");
const icon = document.querySelector("img");    

icon.onclick = function() {
  picker.showPicker();
};

picker.onclose = function() {
  alert("This does not work!");
};

picker.onblur = function() {
  alert("This does not work either!");
};

picker.addEventListener("focusout", (event) => {
  alert("Neither does this!");
});
#datePicker {
  width: 1px;
  height: 1px;
  border: none;
}

img {
  width: 32px;
  height: 32px;
  cursor: pointer;
}
<img src="https://static.vecteezy.com/system/resources/previews/002/387/838/original/calendar-icon-flat-style-isolated-on-white-background-free-vector.jpg" />
<input id="datePicker" type="datetime-local" />

It doesn’t work on Stack Overflow or JSFiddle due to the SecurityError about a cross-origin iframe, so to view the code in action you will likely need to run it locally.

Principles behind DOM element direct selection (dot notation)

Background info: I’m studying JavaScript, currently trying to understand DOM interactions, specifically direct selection (dot notation). It is worth noting that i’m a very theoretical learner and need to understand the principles in order to remember how things work and be able to use them properly.

The 3 classic examples given to clarify how direct selection (dot notation) works are:

  • document.documentElement
  • document.head
  • document.body

W3C says that these are the SOME of the most popular ways to select elements directly. So what are the rest? How do i find a full list of all possibilities to select elements via dot notation, and the principles behind how this works?

For example, i tried document.head.title, but that seems to be wrong… And some places suggest it is document.title, while other sources suggest it is limited to only those 3 options in the classical examples.

How does this whole DOM direct selection (dot notation) work? Can’t i navigate fully like this? Do i need to include the whole path or not? Does it work only on unique HTML tag elements? Or any HTML tag elements?

What are the principles behind this? I can’t find any information that actually explains this, except maybe MDN, but i find the language there is very unclear, so any clarification is very welcome.

Thanks in advance.

functionality to check the flag=='[object]’ is working in IE5 but not in chrome or edge

I am migrating an old IE application to support latest browser.

came across strange issue, In IE the same code return the true while in chrome its returning the False Please check the attached images.

IE Screenshot
If condition returning the true in IE

delFlag is defined as
var delflag='';

but in chrome
same code is returning the False

in IE its considered as object but in chrome its not, I guess.
I am not sure, if eval function has anything to do with this object.
Thanks in advance

Iframe with js random display imagenot working

guys pls help to fix this. I need to add a random image refreshing when using iframe.try tried my best to find solution but it’s not worked.pls help me to fix this.

here is my html

<iframe class="img-responsive center-block element-spacing-md" id="banner" width="970" height="250" frameborder="0" scrolling="no" allowfullscreen="true" style="width: 970px; height: 250px;" ></iframe>

here is the js

var imagee = new Array ();
    imagee[0] = "//s0.2mdn.net/dfp/370694/4408939339/1629903098931/index.html";
    imagee[1] = "//s0.2mdn.net/dfp/370694/4823240283/1652207585517/index.html";
    imagee2] = "//s0.2mdn.net/dfp/370694/4823240283/1652207585517/index.html";
    var size = imagee.length
    var x = Math.floor(size*Math.random())

    $('#banner').attr('src',imagee[x]);

$('#refresh').click(function() {
    location.reload();
});

codepen-https://codepen.io/mithun-deshan/pen/VwQozrQ

how can I create and use unique custom_id for any element of laravel-grapesjs?

In laravel 8 app with “jd-dotlogics/laravel-grapesjs”: “^3.3.0”, I need to extend its functionality :

  1. To add new custom button at toolbar

  2. By clicking on this custom button to open JS prompt method

  3. If prompt method was closed with success to save entered value(external url) with unique id of selected
    element in db with request to server.

  4. For any element on the form I need some unique custom_id and sending saving request save unique custom_id/Entered value

Next time when editor is opened by manager request to db must be send and these Entered value created prior sessions
must be tied to any element by these unique custom_id. Can I create somehow these unique custom_id ?

Manually editing public/vendor/laravel-grapesjs/assets/editor.js file I made 3 first points(last without posting request to server).
https://prnt.sc/rhIrgNpV_JS7
I know usually it is supposed that this file is not edited manually, but I do not see any other way to implement it.

Unpacked version is 37 K lines of code, so I pasted it in :
https://zerobin.net/?bf6a96ac404ac3b1#oVMCXPuQUJVxzm9kuLAa/7tAQ9Kj1Gjhw0y/4aGR+BE=

Any ideas how can I create and use these unique custom_id ?

Thanks!

Updating password using ‘PUT’ method

can someone help me to understand how to use the query function created to update a password in my database?

here is the query function in question

async function updatePassword(req, res) {
var email = parseInt(req.params.email);
return db.none('UPDATE user_account SET password = $1 WHERE email = $2',
        [ req.body.password, email ])
    .then(function () {
        res.status(200)
            .json({
                status: 'success',
                message: 'Updated user'
            });
    })
    .catch(error => {
        console.log(error)
    });

}

here is what I tried to do with fetch method put

resetPassword(){
            fetch('http://url/example', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    params: JSON.stringify({
                        email: this.email,
                    }),
                    body: JSON.stringify({
                        password: this.passwordReset,
                        
                    }),
            })
        // Converting to JSON
        .then(response => response.json())
        // Displaying results to console
        .then(json => console.log(json));       
        },

no error “{status: ‘success’, message: ‘Updated user’}”

but nothing has changed in my database

datalist on mobile browsers

I am new in HTML and javascript.
I have the following html code which works perfect on desktop browsers.
It allows the user to type freely or/and to choose from the list at the same time,
but it doesn’t work well on mobile browsers.
The problem is that when I type, I can’t see the list and when I have access in the list, the mobile’s keyboard disappears.
I will appreciate if someone could help me.

<form>
  <input list="browsers" name="browser" id="browser">
  <datalist id="browsers">
    <option value="Edge">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
</form>