How to generate a lines inside of vue-accordion on each checkbox click in Vuejs?

data: function () {
    return {
      show: false,
    };
  },
  methods: {
    toggleItem: function () {
      this.show = !this.show;
    },
  },
  <div class="wrapper">
    <div class="accordion">
      <input type="checkbox" @click="toggleItem" />

      <h2 class="title">
        <slot name="title"></slot>
      </h2>
    </div>
    <div v-show="show" class="content">
      <slot name="content"></slot>
    </div>
  </div>

I want to generate a lines like below, inside of the vue-accordion. every time. When ever user click on each checkbox separately.

So to achieve like above, do i need any other plugins or with css can i achieve that.

Working code snippet:- https://codesandbox.io/s/vue-accordion-component-forked-vwpi8?file=/src/components/Accordion.vue

generate lines like this

JavaScript Two Sum Debugging (n time complexity)

I am trying to achieve n-time-complexity for a two sum function via utilization of hashes in JavaScript. I’ve come up with the code below, but for some reason it does not capture all of the paired indices. The function is supposed to return pairs of indices of integers in an array that add up to zero.

Array.prototype.twoSumHash = function () {
    let newArr = [];
    const hash = {};
    this.forEach((ele, idx) => {
        if (hash[ele * -1]) {
            const pair = [hash[ele * -1], idx];
            newArr.push(pair);
        }
        hash[ele] ? hash[ele].push(idx) : hash[ele] = idx;
    });
    return newArr;
};

console.log([1, -1, 2, 3, 4, -2].twoSumHash());

This function only seems to return the 2 and -2 ([2,5]), but not the 1 and -1 ([0, 1]). Please help, and thank you!

Get updated node list after manipulating the DOM

I’m trying to click on either the 0th index of the node list, and move that item down after its next sibling. Or the 2nd index and move that above its previous sibling which I’ve working for the first go:

https://i.gyazo.com/8918c506d526a8dd2f77602c65d68c2a.mp4

However once I’ve clicked these two elements I believe their positions as far as my JavaScript is concerned is still the same. So I end up getting a console error:

Uncaught TypeError: Cannot read properties of null (reading 'after')

This is my JS currently. As you can see I’m moving the elements up and down depending on index:

export const reviewsUtil = () => {
    const allReviewCards = document.querySelectorAll('.reviews__cardInner');
const allDescriptions = document.querySelectorAll('.reviews__descWrapper');

allReviewCards.forEach((e, index) => {
    e.addEventListener('click', (review) => {
        if (review.target.classList.contains('inactive')) {

            //Get's all reviews that aren't the clicked and hides them
            allDescriptions.forEach(desc => {
                desc.classList.add('reviews__infoInactive');
                desc.style.removeProperty('display');
            });

            //Loops through all instances and removes the active class
            allReviewCards.forEach(e => {
                e.classList.remove('active');
                e.classList.add('inactive');
                e.nextElementSibling.classList.remove('reviews__infoActive');
            })

            //Set's clicked as active
            review.target.style.removeProperty('display');
            review.target.classList.remove('inactive');
            review.target.classList.add('active');

            //Set's clicked review text as active
            e.nextElementSibling.classList.add('reviews__infoActive');
            e.nextElementSibling.style.removeProperty('display');

            if (index === 0) {
                e.parentElement.nextElementSibling.after(review.target.parentElement);
            } else if (index === 2) {
                index = 1;
                e.parentElement.previousElementSibling.before(review.target.parentElement);
            }
            
        }
    })
  })
}

export default reviewsUtil;

What I’d like to try and achieve is potentially having an updated list returned to me once the DOM has been manipulated. Is there a way I can monitor this or is my approach somewhat off?

Any help greatly appreciated.

Create and implement (in any programming language) an algorithm to manage passwords

Create and implement (in any programming language) an
algorithm to manage passwords. This program must:

  1. Step 1 – store the user password
    a. Request a password from the user(s)
    b. The user enters his password
    c. The program generates a random salt for each user.
    d. It adds the salt (at the middle) to the user’s password
    and the hash the password + salt and stores the hashed
    password and the salt to a file (may store the user’s
    name or ID if any).
  2. Step 2 – verify the password
    a. Request the user password
    b. Read the saved salt, add it to password and hash salt +
    password.
    c. Compare the result obtained with the stored hash. If
    they are the same the user is authenticated.

HTML FORM – setting form action on javascript

i’ve been having a problem where i have a form in which several entities within an unordered list are displayed, a name and a button dinamically with vanilla javascript. The problem is, im changing the action value from the html form, from javascript this so i can add an id that i get in a JSON from a http request so i can manipulate a specific object, but it doesnt send the “delete” request, which is actually a post request that im managing from my server side correctly (tested in postman and works like a charm), but when calling from the front-end it stops working. Here are my html and script.

PANEL.HTML

<!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">
    <!-- <meta http-equiv="Content-Security-Policy" content="default-src https://cdn.example.net; child-src 'none'; object-src 'none'"> -->
    <link rel="stylesheet" type="text/css" href="css/panel-style.css">
    <script defer src="panel-script.js"></script>
    <title>Panel de Control</title>
</head>

<body>
    <header>
        <img src="assets/mrvapeslogo.png" alt="mrvapes logo">
        <a href="index.html"></a>
    </header>
    <section>
        <form id="files-form" accept-charset="UTF-8" enctype="multipart/form-data" action="#" autocomplete="off" method="POST" onsubmit="return validate(this);">
            <label for="user">Banners Activos</label><br/>
            <ul id="files-container">

            </ul>
        </form>
        <form accept-charset="UTF-8" enctype="multipart/form-data" action="http://localhost:3000/banner" autocomplete="off" method="POST" target="_blank">
            <div class="container">
                <div class="button-wrap">
                    <!-- <label class="button" for="upload">Subir</label> -->
                    <input type="text" id="name" placeholder="Nombre de Archivo" value="" name="name" required>
                    <input id="image" name="file" value="Subir" placeholder="Subir Archivo" type="file" required>
                    <button id="upload" value="post-request" type="submit">Enviar</button>
                    <!-- <input id="upload" type=" submit " value="Enviar " onclick="submit() "> -->
                </div>
            </div>
        </form>
    </section>
</body>

PANEL-SCRIPT.JS

const list = document.getElementById("files-container");
const filesForm = document.getElementById("files-form");

fetch('http://localhost:3000/banner')
    .then(response => response.json())
    .then(json => {
        console.log(json)
        console.log(json.message)
        for (let i = 0; i < json.message.length; i++) {
            var item = `<li>${json.message[i].name}
                            <button id="delete-button" onclick="deleteButton('${json.message[i].name}','${json.message[i]._id}')">Borrar</button>
                        </li>`;
            list.innerHTML += item;
        }
    });

function deleteButton(name, id) {
    var answer = confirm(`Seguro que deseas borrar ${name}?`);
    if (answer) {
        filesForm.action = `http://localhost:3000/banner/${id}`;
        alert('Borrado Correctamente!');
        window.location.reload(true);
    } else {
        validate();
    }
}

function validate() {
    return false
}

HAPPY HOLIDAYS! 😀

CSP preventing image from rendering

I am using the Polaris library to render a component that emits image markup like:

<img class="Polaris-VideoThumbnail__PlayIcon" src="data:image/svg+xml;base64,PHN2Zy....">

This triggers a Content Security Directive issue that precludes the image from rendering. I’ve tried applying a number of policies but have not found one that works when the app is deployed.

Presently the policy is applied via a meta tag like:

<meta http-equiv="Content-Security-Policy" content="img-src 'self' data: https:; script-src *.twimg.com *.twitter.com 'self' 'unsafe-inline'; style-src *.twimg.com *.twitter.com 'self' 'unsafe-inline'">

This works locally – even if I fudge my HOSTS file to use a non-localhost URL to emulate an external request. But when I deploy my app the play icon is broken and I get:

Refused to load the image 'data:image/svg+xml;base64,PHN2ZyB...' because it violates the following Content Security Policy directive: "default-src https: 'unsafe-eval' 'unsafe-inline'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.

The issue is presently manifesting itself at https://witty-ocean-02e42dd0f-168.eastus2.azurestaticapps.net/vaccineinfo

When I enter the contents of my meta tag into the CSP evaluator, I get:

img-src All Good

Why is my browser (Chrome) complaining that img-src isn’t set on my deployed instance?

Why is code giving error if I try to access the array returned by str.split(), immediately in next line

Why does it happen that the below code throws the error Uncaught ReferenceError: Cannot access 'arr' before initialization

function swap(str,a,b){
    let arr = str.split("")
    [arr[a],arr[b]] = [arr[b],arr[a]]
    return arr.join("")
}
swap("abcde",2,4) // throws error "Uncaught ReferenceError: Cannot access 'arr' before initialization"

But as soon as I insert any dummy statement between line 2 and 3, surprisingly code starts to work

function swap(str,a,b){
    let arr = str.split("")
    23456; // this could be anything like a variable declaration, or any valid javascript statement
    [arr[a],arr[b]] = [arr[b],arr[a]]
    return arr.join("")
}
swap("abcde",2,4) // returns "abedc" as expected

I am surprised to see why does this even work now ? It should have given error in both the cases, or should have worked in both cases.
I’m sure that in the 1st case, split is not finishing it’s work till the time line 3 is executed and in 2nd case, it is getting enough time because of 1 extra statement in between.
But I would still love to get a clear explanation as to why it is behaving like this.
I’m not sure if this is same for all browsers, but I’ve tried it on Chrome and Safari on mac, and both of them gave same error.

Creating form for products. Mongodb, NodeJs

Technologies I am using are:

  1. NodeJs
  2. MongoDB

My idea is to create a form which is taking Product.Scheme(
type: String,
model: String,
skus: [Here to be multiple products from same type, but for example, different colors]).

When that product is created. I want to get that data and retrieve it from MongoDb and show it as product in another page. Example /products/office-paper. And in this page to show all skus from type Paper.
Second things is to manage that data from AdminPanel(I have it), but don’t know how to create, edit, remove data.(Still new, but really want to learn).
Thanks in advance. And if someone help me I’ll get him something.

Why the output of the two writing methods are inconsistent?

The first way to write:

    const LazyMan = function (name) {
      const array = []
      const fn = () => { console.log("Hi! This is " + name + '!'); next() }
      const next = () => {
        const fn = array.shift()
        fn && fn()
        // array.shift() && array.shift()()
      }
      array.push(fn)
      setTimeout(() => { next() }, 0)
      const api = {
        sleep: (number) => {
          array.push(() => {
            setTimeout(() => { console.log('Wake up after ' + number); next() }, number * 1000)
          })
          return api
        },
        eat: (content) => {
          array.push(() => {
            console.log('eat ' + content); next()
          })
          return api
        },
        sleepFirst: (number) => {
          array.unshift(() => {
            setTimeout(() => { console.log('Wake up after ' + 5); next() }, number * 1000)
          })
          return api
        }
      }
      return api
    }
    LazyMan("Hank").sleep(2).eat("dinner").sleepFirst(1);
    // Wake up after 5
    // Hi! This is Hank!
    // Wake up after 2
    // eat dinner

The second way to write:

    const LazyMan = function (name) {
      const array = []
      const fn = () => { console.log("Hi! This is " + name + '!'); next() }
      const next = () => {
        const fn = array.shift()
        // fn && fn()
        array.shift() && array.shift()()
      }
      array.push(fn)
      setTimeout(() => { next() }, 0)
      const api = {
        sleep: (number) => {
          array.push(() => {
            setTimeout(() => { console.log('Wake up after ' + number); next() }, number * 1000)
          })
          return api
        },
        eat: (content) => {
          array.push(() => {
            console.log('eat ' + content); next()
          })
          return api
        },
        sleepFirst: (number) => {
          array.unshift(() => {
            setTimeout(() => { console.log('Wake up after ' + number); next() }, number * 1000)
          })
          return api
        }
      }
      return api
    }
    LazyMan("Hank").sleep(2).eat("dinner").sleepFirst(1);
    // Wake up after 2

const fn = array.shift() fn && fn();
array.shift() && array.shift()();

The console output results of the first method and the second method are inconsistent, The second method only outputs the result of “Wake up after 2”, which is not what I want,I want to know why?

Replace select options with ajax?

i have three dropdowns and 1 depends on 2 and 2 depends on 3. This is how it works. I have an issue with the 3rd one, when users changes something on 2 then 3 appends new options along with the old options. How to just replace the old ones with new ones ?

my code:

<script>
    $("#id_name").change(function () {
      var url = $("#create_application_form").attr("data-cities-url"); 
      var nameId = $(this).val();  
      var temp_intakes = null
      $.ajax({                       
        url: url,                    
        data: {
          'name': nameId 
        },
        success: function (data) { 
            temp_intakes = data.data;
            $.each(data.data, function(index, name){
                $('select[id=id_course]').append(
                $('<option></option>').val(name.id).html(name.name)
                );
              });
            }
      });
      $("#id_course").change(function () {
          
          var selected = $(this).val()
          var data = temp_intakes.filter(v => v.id === parseInt(selected ));
          $.each(data, function(index, name){
            $.each(name.intakes, function(index, test){
                $('select[id=id_intakes]').append(
                    $('<option></option>').attr("value",test).text(test) // problem on here
                )
            })
          });
      })
    });
  </script>

And my data for the above look like this

{id: 2, name: 'John', intakes: Array(3)} // the third option using this "intakes" array as options.

Please help.

Nextjs importing a commonjs module (@theatrejs/core) that depends on a ES module (lodash-es) is causing [ERR_REQUIRE_ESM]

As explained in the title, I created a fresh Nextjs project (v12), installed @theatrejs/core npm package, upon import the package and using it in the code my build started showing errors, more specifically:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/projects/nextjs-xtxeun/node_modules/lodash-es/get.js
require() of ES modules is not supported.
require() of /home/projects/nextjs-xtxeun/node_modules/lodash-es/get.js from /home/projects/nextjs-xtxeun/node_modules/@theatre/dataverse/dist/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename get.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/projects/nextjs-xtxeun/node_modules/lodash-es/package.json

In a nutshell, nextjs 12 app -> @theatrejs/core (commonjs) -> lodash-es (ESM).

you can see a reproduction of the error here: https://stackblitz.com/edit/nextjs-xtxeun?file=node_modules%2Flodash-es%2Fpackage.json

Can anyone point me toward a way to make it work?

Javascript Delay/Sleep function

I am writing a vanilla javascript function to add a page scrolling animation to my website. The problem is that I want the event listener to pause for the specified millisecond time to give time for the animation to complete since if I scroll normally, the animation will happen multiple times one after the other.

/*  Event handler for scroll event  */

// This is a function which allows a time to be passed in miliseconds. This function will then cause a sleep effect for the specified ms time
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// Initial state
var iniState = 0;

// Adding scroll event
window.addEventListener('scroll', function(){
    // Detects new state and compares it with the old one
    if ((document.body.getBoundingClientRect()).top > iniState)
        console.log('up');
    else
        console.log('down');
    
    // Saves the new position for iteration.
    iniState = (document.body.getBoundingClientRect()).top;

    sleep(2000).then(() => { console.log("test"); });
});

I tried the timeout function, but this only delayed the event listener instead of pausing for the period of time. This is a link to the console in browser if that makes the problem easier to understand.

In summery, I am trying to make a event listener to listen for a scroll event, then wait 2000 milliseconds to wait for the animation to complete. After this the event listener will then start listening again for a scroll event again.

JavaScript: Chrome and Safari trigger no mouse events when already-selected of is clicked

I’m trying to respond when the user re-clicks the currently-selected <option> in a <select>. Current desktop FF (v95.0.2) fires mousedown, mouseup, and click on the <option> element itself, and everything captures down and bubbles up through the entire HTMLDocument hierarchy, including the containing window.

In the same situation, current desktop Chrome (96.0.4664.110) and Safari (14.1.2) don’t seem to fire any events at all.

<html lang="en" id="thehtml">

<head>
</head>

<body id="thebody">
  <select id="theselect">
    <option id="option1" value="1">one</option>
    <option id="option2" value="2">two</option>
  </select>
</body>

<script>
  function logEvent(ev) {
    console.log(
      ev.type +
      '   target: ' + (ev.target.localName ? `${ev.target.localName} #${ev.target.id}` : `(${ev.target.constructor.name})`) +
      '   this: ' + (this.localName ? `${this.localName} #${this.id}` : `(${this.constructor.name})`)
    );
  }

  var eventList = ['change', 'click', 'dblclick', 'input', 'mousedown', 'mouseup'];
  var elementList = ['thehtml', 'thebody', 'theselect', 'option1', 'option2'];

  for (let ev of eventList) {
    window.addEventListener(ev, logEvent, true); // capture
    window.addEventListener(ev, logEvent, false); // bubble

    document.addEventListener(ev, logEvent, true); // capture
    document.addEventListener(ev, logEvent, false); // bubble

    for (let id of elementList) {
      document.getElementById(id).addEventListener(ev, logEvent, true); // capture
      document.getElementById(id).addEventListener(ev, logEvent, false); // bubble
    }
  }
</script>

</html>

Is there any way on Chrome or Safari to detect the user clicking the mouse on the currently-selected <option>?

What is the difference between `document` and `document.body`?

What is actually the difference between document and document.body?

For example, I have the following code:

document.addEventListener('click',function(){ 
document.write('You click me!') 
})
<div>Click anywhere</div>

What will be the difference if I use document.body instead of document ?

And what is actually the difference between document and document.body?

I tried to search online, but couldn’t find any useful information.

Thanks for any responds!

How does a React application start without explicit references to its JS implementation files?

I’m learning React. In the tic-tac-toe game ( https://reactjs.org/tutorial/tutorial.html ) the index.html file had some event handlers and a div pointing at id=root. But nothing about an index.js file, which has a ReactDOM.render.

What tells the browser to run the index.js code if there is no tag loading it?

This link ( Where’s the connection between index.html and index.js in a Create-React-App application? ) says:

Our configuration specifies that Webpack uses src/index.js as an “entry point”. So that’s the first module it reads, and it follows from it to other modules to compile them into a single bundle.

When webpack compiles the assets, it produces a single (or several if you use code splitting) bundles. It makes their final paths available to all plugins. We are using one such plugin for injecting scripts into HTML.

But if this is the answer, then why should a browser know about webpack, especially as this isn’t mentioned in the minimal index.html file?