webpack, jquery and dynamic form field

I’m using webpack and jQuery in my symfony project.
I configured webpack and jquery as follows :

// webpack.common.js
const path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: {
    main: "./src/default/index.js"
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
  module: {
    rules: [
      { 
        test: /datatables.net.*/, 
        use: [{
          loader: 'imports-loader',
          options: {
            additionalCode: 
              "var define = false;"
          }
        }]
      },
      {
        test: require.resolve("jquery"),
        loader: "expose-loader",
        options: {
          exposes: ["$", "jQuery"],
        },
      },
      {
        test: /.(scss)$/,
        use: [{
          // inject CSS to page
          loader: 'style-loader'
        }, {
          // translates CSS into CommonJS modules
          loader: 'css-loader'
        }, {
          // Run postcss actions
          loader: 'postcss-loader',
          options: {
            // `postcssOptions` is needed for postcss 8.x;
            // if you use postcss 7.x skip the key
            postcssOptions: {
              // postcss plugins, can be exported to postcss.config.js
              plugins: function () {
                return [
                  require('autoprefixer')
                ];
              }
            }
          }
        }, {
          // compiles Sass to CSS
          loader: 'sass-loader'
        }]
      },
      {
        test: /.css$/i,
        use: ["style-loader", "css-loader"],
      }
    ]
  },
  resolve: {
    alias: {
      jquery: "jquery/src/jquery"
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery"
    })
  ]
}
// index.js
import 'bootstrap';

import './scss/app.scss';

import '@fortawesome/fontawesome-free/js/fontawesome';
import '@fortawesome/fontawesome-free/js/solid';
import '@fortawesome/fontawesome-free/js/regular';
import '@fortawesome/fontawesome-free/js/brands';

require('select2');

require('jquery-ui/ui/widgets/datepicker');
require('jquery-ui/ui/i18n/datepicker-fr.js')

import 'datatables.net';
import dt from 'datatables.net-bs5';

import 'datatables.net-bs5/css/dataTables.bootstrap5.min.css';

dt(window, $);

My project needs to load external javascript script (old style) so I need to access $ outside of webpack. This scripts use Select2 plugin for initialize autocompletion on select form element.

So far so good.

I’m facing a problem when I want to add dynamically a field that use jQuery select2 Plugin (after page loading).

When I do this (adding new select2 field in my form) and initialize select field with select2 :

if ( "undefined" !== typeof jQuery ) {
    (function($, window, document) {
        $(function() {
           $('.select2-element').select2(config);
        });
    }(window.jQuery, window, document));
}

The result is : “Select2 is not defined.”

First test

When I do :

if ( "undefined" !== typeof jQuery ) {
    (function($, window, document) {
        $(function() {
           console.info($.fn);
        });
    }(window.jQuery, window, document));
}

The result shows me that select2 is in the $.fn list ($.fn.select2). But the same code invoked after page loading show me that select2 is not in the list.

Second test

When I do on page loading :

if ( "undefined" !== typeof jQuery ) {
    (function($, window, document) {
        $(function() {
           console.info(jQuery);
           console.info($);
        });
    }(window.jQuery, window, document));
}

The return of console.info(jQuery) is not the same as console.info($). In the first I don’t have select2 in jQuery.fn but it is present in $.fn .

I identified that the $ object used after page loading is same as jQuery object above not $ object above.

Thanks for your help.

File System Access API + WebWorker + Recording Webm video and audio sample

Is there a sample that can encode a ReadableStream transferred to a worker into a webm format with audio and stream it to the file system using the new File System Acccess API? I was able to use one of the samples which has a modified webm-writer2.js file and achieve everything video related on a worker, but I am stuck on finding an encoder and muxer that can do both audio and video streams in the worker using the new WebCodecs API.

This example has a workaround for audio, but it relies on AudioContext which can only be used on the main thread. This can become problematic and cause interruptions on the main loop as it needs to constantly read chunks from an event.
https://github.com/xiph/opus/issues/221

My goal is to record a video/audio stream, transfer the MediaStream entirely off the main thread for processing and stream, mux it all into a single webm container, and save it to the file system without any memory limits. Does anyone have a working solution that can build off that sample and include audio?

Here’s some references:

webm-writer2.js (video only so far)
https://github.com/w3c/webcodecs/tree/main/samples/capture-to-file

Audio encoding problem?
https://github.com/xiph/opus/issues/221

Transferring media stream to worker via track processor
https://github.com/w3c/webcodecs/issues/43

Best way to use same variables on Object Destructuring in JavaScript

I have these two custom react hooks using as below passing the same variables in object destructuring.

const {data, loading, error} = useFetch(url);
const {data, loading, error} = usePostForm(url);

of course, this won’t work because it’s using the same variables.
what’s the best way to change this codes? without changing original custom hooks

Only way I can do is as below codes; but my problem is there is no way to know what are the objects/data are returning from custom hooks.

const fetch1 = useFetch(url)
const fetch2 = usePostForm(url)

fetch1.data fetch1.error fetch1.loading
fetch2.data fetch2.error fetch2.loading

Anyone has better idea ? please let me know

How to get particular element with a className?

I am using target.getElementsByClassName('numerical')) to get the list of elements with classname of numerical . I want to further filter only th from the list. How can i do that?

0: th.ant-table-cell.numerical
1: th.ant-table-cell.numerical
2: td.ant-table-cell.numerical
3: td.ant-table-cell.numerical

How to make soft triangle in CSS?

I want to create a soft triangle like here:

enter image description here

But what I get is:

span {
  display:inline-block;
  padding:50px;
  position:relative;
  background: linear-gradient(135deg, transparent 15px , #ff4369 20px, #ff4369 50%, white 51%),radial-gradient(circle at 20px 20px, #ff4369 20px, transparent 22px);
}
span+span {padding:75px;}
span:last-of-type {padding:28px;}
span:before {
  display:block;
  content:'padding';
  white-space:nowrap;
  position:absolute;
  transform:rotate(-45deg);
  top:calc(50% - 1.2em);
  left:0;
}
span + span:before {content:'instead background-clip';}
span:last-of-type:before {content:'56px'}
<span></span>
<span></span>
<span></span>

Or on: https://codepen.io/gc-nomade/pen/wjgBQL

Have somebody some idea how to make it?

Cypress method for choosing an if section depending on a string

How can I write this method correctly in cypress so that when I call for example setToOffService('Online booking') it knows how to go to the correct if and call the appropriate id for that string.

I hope I have provided all the important details

 setToOffService(name: string) : void {
    
        cy.get('#Service_IsActive').then(($name) => {
    
            if ($name.text().includes('Service is available')) {
                cy.get('#Service_IsActive').click({force:true});
            }
            else if ($name.text().includes('Online booking')) {
                cy.get('#Service_AllowOnlineScheduling').click({force:true});
            }
        })
    }

Putting all characters of a sentence into a array elements by using Javascript [closed]

I have an array exercise that have to use array to use, that is simply to put a sentence into characters, and store them in an array. Below is my program:

However, a message

Uncaught TypeError: abc.CharAt is not a function

appears in the console. Could you tell me which part I had done wrong and how to correct it? The prerequisite criteria is to solve this question using array.

strarray = []
abc = "hello"
for (i = 0; i < abc.length; i++) {
  strarray.push(abc.CharAt(i))
}
console.log(strarray)

passing inquirer value from one js filde to another js file using nodejs /javascript

I am trying to pass the inquire value from one js page to another js from which I can pass this value to another js file which contain the function and I want to pass same value from one function to another function which also pass the value from one function to another function

but the problem is I can’t pass the value even inside the userDetils

so flow chat be like

index.js -> userDetails.js -> userHandler.js

index.js

const userDetails= require("./userDetails");

module.exports = userValue = async () => {
  inquirer
    .prompt({
      type: "input",
      name: "userInput",
      message: messages.promptFileName,
      validate: (userInput) => {
        if (!userInput || userInput.trim() === "") {
          console.log("Please insert userInput!");
          return false;
        }
        this.name = userInput;
        return true;
      },
    })
    .then(async (answer) => {
      await userDetails.run(answer.userInput);
    });
};

userDeatils.js

const userHandler= require("./userHandler.js);

class UserDetails extends command{
 async run(data){
  console.log(data);
  
  // await userHandler.start(data);
  // .. other code here
 }
}

userHandler.js

class userHandler{
  async start(data){
   // some code here
   this.cmdUser()
   .then((msgData) => {
    return resolve(msgData);
    })
    .catch((error) => {
    return reject(error.errorMessage);
    });
 }

 async cmdUser(){
  return new Promise(async (resolve,reject)=>{
   await datacmd.run(data);
  })
 }
}

how I can pass value from index.js to userHandler.js (datacmd())

liveui option of videojs seeking is not working on Chrome browser of android (rest all platforms its working good)

I am unable to see the liveui seek bar in android.
As given in official documentation of videojs ;
“Note: This user interface will not work on Android due to the native live HLS implementation not supporting seekable ranges during live streams. We recommend overriding the native hls implementation with @videojs/http-streaming; this will make the new liveui work.”

But I coundnt find anything to do the same.

These are the options which i have given.

var options = {
    preload: true,
    autoplay: false,                       
    controls: true,
    liveui: true,
    preloadWebComponents: true,
    techOrder: [ 'chromecast', 'html5' ],
    controlBar: {
        'liveDisplay': true,
        'pictureInPictureToggle': false,
        'subsCapsButton': false,
    },
   
};'''

https://docs.videojs.com/tutorial-live.html
[1]: https://i.stack.imgur.com/xs3bP.png

Imgur image uploading through api not working

I’m trying to build a blog website, so I wanted to upload images to imgur and retrieve the link for the image. But when I try to upload image using the below code, the images are not uploading. Is there anything wrong in my code? Or is there any better way to do the same?

This is the code that I’m using.

<input type="file" accept="image/*">


        <script src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js'></script>
        <script type="text/javascript">
            $('document').ready(function () {
            $('input[type=file]').on('change', function () {
                var $files = $(this).get(0).files;

                if ($files.length) {
                // Reject big files
                if ($files[0].size > $(this).data('max-size') * 1024) {
                    console.log('Please select a smaller file');
                    return false;
                }

                // Begin file upload
                console.log('Uploading file to Imgur..');

                // Replace ctrlq with your own API key
                var apiUrl = 'https://api.imgur.com/3/image';
                var apiKey = 'b985f2a2610584c';

                var settings = {
                    async: false,
                    crossDomain: true,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    url: apiUrl,
                    headers: {
                    Authorization: 'Client-ID ' + apiKey,
                    Accept: 'application/json',
                    },
                    mimeType: 'multipart/form-data',
                };

                var formData = new FormData();
                formData.append('image', $files[0]);
                settings.data = formData;

                // Response contains stringified JSON
                // Image URL available at response.data.link
                $.ajax(settings).done(function (response) {
                    console.log(response);
                });
                }
            });
            });
        </script>

Btw i’m using flask to build my website.
Thanks in advance.

Creating Two Modals With the same Style

Good day all.

So I have been trying to create an additional modal for my website. The first modal is on the home page, and the second modal is on the service page. but after writing the codes, only the first one works fine, and the second modal on my service page doesn’t work well.

Here are the codes:

  1. Html for modal 1 on home page

     <div class="nippy-modal-header">
       <h3 style="font-weight: bold;">More Technologies & Frameworks <span id="nippy-closeBtn" class="nippy-closeBtn">&times;</span></h3>
    
     </div>
    
     <div class="nippy-modal-body">
       <p>
         The technologies and applications that is use varies, depending on the nature of the Job.
         I can use Wix or Shopify to create the perfect E-Commerce for you.
       </p>
       <p>
         The list goes on. Javascript frameworks include: React.js, Node.js, Express.js and we keep exploring this wonderful technology.
       </p>
     </div>
    
     <div class="nippy-modal-footer">
       <a href="services.html"><button type="button" class="nippy-button">See My Services<i class="fa-solid fa-arrow-right"></i></button></a>
     </div>
    
  2. HTML for modal 2 on service page:

       <div class="gModalHeader">
         <h3 style="font-weight: bold;">Graphics & Branding <span id="gModalCloseBtn" class="gModalCloseBtn">&times;</span></h3>
    
       </div>
    
       <div class="gModalBody">
         <ol>
           <li>Logos</li>
           <li>UI Interface Design and Development</li>
           <li>Flyers</li>
           <li>Branding</li>
           <li>Buisness/Complementary Cards</li>
           <li>Merchs and Mockups</li>
         </ol>
       </div>
    
       <div class="gModalFooter">
         <a href="index.html#hire-me"><button type="button" class="nippy-button">Hire Me<i class="fa-solid fa-arrow-right"></i></button></a>
       </div>
    
     </div>
    
  3. Javascript for modal one:

    // Get All Elements
    const modal = document.getElementById(“nippy-modal”);
    const seeMoreBtn = document.getElementById(“nippy-modalBtn”);
    const closeBtn = document.getElementById(“nippy-closeBtn”);

    // Listen for open click
    seeMoreBtn.addEventListener(“click”, openModal);
    // Listen For Close click
    closeBtn.addEventListener(“click”, closeModal);

    // function to open modal
    function openModal() {
    modal.style.display = “block”;
    }
    // function to Close modal
    function closeModal() {
    modal.style.display = “none”;
    }

  4. Javascript for modal Two:

    var gModal = document.getElementById(“gModal”);
    var gSeeMoreBtn = document.getElementById(“gModalBtn”);
    var gCloseBtn = document.getElementById(“gModalCloseBtn”);

    // Listen for open click
    gSeeMoreBtn.addEventListener(“click”, gOpenModal);
    // Listen For Close click
    gCloseBtn.addEventListener(“click”, gCloseModal);

    // function to open modal
    function gOpenModal() {
    gModal.style.display = “block”;
    }
    // function to Close modal
    function gCloseModal() {
    gModal.style.display = “none”;
    }

Add AOS attributes by Javascript

I am trying to add the attributes to launch AOS animations via javascript, but it is not working correctly. Now, adding the attributes by js, when the animation is launched, instead of showing the element, it hides it. I think it may be because the element is rendered first, and js acts after adding the AOS attributes, so the animation does it in reverse for me. this is my code to add AOS attr:

var hero = document.getElementById('main-hero');
hero.setAttribute('data-aos', 'fade-up');

Is there any way to add AOS by js and have it work? add it on HTML is currently unvailable for accessibility.

The JavaScript array not showing expected result in HTML [duplicate]

<!DOCTYPE html>
<html>
<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">
    <title>遊戲選購</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    
</head>
<body>
    <script>
        var name = new Array("PS4","Switch","Xbox")
        var price = new Array(9980, 12999, 11000)
        var imgfile = new Array("ps4.jpg", "switch.jpg", "xboxone.jpg")
        document.write("<table class='table table-hover'>");
        document.write("<tr class='table-warning'>");
        document.write("<td>品名</td>");
        document.write("<td>單價</td>");
        document.write("<td>產品圖示</td>");
        document.write("</tr>");
        for (var i = 0; i < name.length; i++) {
            document.write("<tr>");
            document.write("<td>" + name[i] + "</td>");
            document.write("<td>" + price[i] + "</td>");
            document.write("<td><img src='images/" + imgfile[i] + "' class='img-thumbnail' width='150'></td>");
            document.write("</tr>");
        }
        document.write("</table>");
   </script>

    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

When I try to create an array name with 3 items inside, the array splits into each letter instead of three elements only. In the table, I am going to show the three items in document.write("<td>" + name[i] + "</td>"); that each item uses a row instead of breaking each letter. Anyone knows where is the problem?