movement capability for each created div

How can I write in a structure that I can move each div I create as I press the button?

In this example code I run, when I move the divs after adding them, they all move at the same time.

It is necessary to make an addlistener that will work according to the different IDs of each created div.

index.html

<html>
  <head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" type="text/css" href="styles.css"/>
  </head>

  <body>
  

    <input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
    <script src="index.js"></script>
  </body>
</html>

style.css

body {
    font-family: sans-serif;
  }
  
  .box {
    height: 200px;
    width: 200px;
    background-color: black;
    cursor: move;
    position: absolute;
  }
  
  .box:active {
    background-color: aquamarine;
    opacity: 0.8;
  }

and index.js

    var mousePosition;
    var offset = [0,0];
    var div;
    var isDown = false;
    var count = 5;


    function doFunction() {
    
        count=count+1;
    
        let id = "id_";
        var div = document.createElement('div');
     
        divID = id+count;
        div.id = divID;
        div.className = 'box';
        document.body.appendChild(div);
        add(div); 
   }

        function add(div) {
    
        var divID = div.id;
    
        addEventListener('mousedown', function(e) {
            isDown = true;
            offset = [div.offsetLeft - e.clientX, div.offsetTop - e.clientY];
            console.log(offset);
        });
    
        document.addEventListener('mouseup', function() {
            isDown = false;
        });
        
        document.addEventListener('mousemove', function(event) {
            event.preventDefault();
            if (isDown) {
                
                mousePosition = {
            
                    x : event.clientX,
                    y : event.clientY
            
                };
                div.style.left = (mousePosition.x + offset[0]) + 'px';
                div.style.top  = (mousePosition.y + offset[1]) + 'px';
            }
        });
    }

Uncaught (in promise) TypeError: _Test__WEBPACK_IMPORTED_MODULE_2__.default.getOutletInfo is not a function

I only got this error as soon as I changed the last row of Test.js to use connect. This in order to implement reactredux and hooks in this class. After importing this class, Test.js, into another class, Zone.js, i get the following error:
enter image description here

my class Test.js which is being exported:

 import React, { Component } from 'react'
 import QrReader from 'modern-react-qr-reader'
 import {connect} from 'react-redux'
 import { activateQR } from "./actions";

class Test extends Component {

 constructor() {
    super();

    this.state = JSON.parse(window.localStorage.getItem('state')) || {
      outletId: '555',
      providerCode: '55'
    }
    this.handleError = this.handleError.bind(this);
    this.handleScan = this.handleScan.bind(this);
}

setState(state){
  window.localStorage.setItem('state', JSON.stringify(state));
  super.setState(state);
}

handleScan(data){
if (data) {
   /**CODE**/

      this.setState({...this.state, outletId: arr[3]})
      this.setState({...this.state, providerCode: arr[1]})
   
      this.props.activateQR();
  }
}

  async getOutletInfo(){
           /**code for fetching data **/
           //returns json string
  }

handleError = err => {
   console.error(err)

}

 render() {
  return (
  <div>
            //Code for QR
  </div>
    )
  }
}
const mapDispatchToProps = {
   activateQR,
}


export default connect(mapDispatchToProps)(Test)

my class Zone.js that imports Test.js in order to call the method getOutletInfo() ::

import { Component } from 'react'
import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';
import CancelIcon from '@mui/icons-material/Cancel';
import './Zone.css';
import Test from '../../Test';


export default class Zone extends Component {
  constructor(props){
  super(props);
  this.state={
  outletId: '',
  provider: '',
 }

}

 async componentDidMount(){
   let jsonstring = await Test.getOutletInfo();  //Zone.js:28 is here
   let getMessage = jsonstring.message;

  //code for extracting values from jsonstring
 }
  console.log(this.state.status);
}

render() {

return (
  
  //HTML CODE
    
    )
  }
}

Understanding the prototype created from a `new` instance

From the new MDN docs it says:

The new keyword does the following things:

  1. Creates a blank, plain JavaScript object.
  2. Adds a property to the new object (__proto__) that links to the constructor function’s prototype object

How exactly is the prototype defined then? My thought was it would be:

  • If it’s in a function (not using the class keyword), it would lookup to find if there is a [Constructor].prototype declared somewhere and use that, and if not it would fallback to…(not sure?). As an example if the constructor is named Range it would lookup to see if Range.prototype is defined and use that as the prototype.
  • If it’s in a class then it would use every method or property to build the prototype up.

Is that more-or-less a correct understanding, or what might I be missing?

JS How to filter only visible rows with ddtf.js

I’m a beginner with JS, and I have a question about the plugin ddtf.js

Simple jQuery Dropdown Table Filter Plugin – ddtf.js

I managed to correctly implement this in my code, but I have a question.

I have an HTML table with 3 columns. How to modify this code so that the ddtf filter populates the drop-down menus uniquely what is displayed in the table by exlude what is “display: none”

Example: when I select something from the drop-down menu of the first column, I would like the 2nd dropd-down menu to display only the remaining displayed data, same for the 3rd etc.

I hope my question is clear enough…. I’m very beginner with JS

Thanks for your help.

Here is the demo of the plugin

How can I pause or stop the audio in this working script?

This is a working script for start to play the desired audio.
Could anybody tell good a good solution for pause or stop the audio by clicking on the onclick paragraph again?

<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=script, initial-scale=sript">
    <title>English Homonyms</title>
    <link rel="stylesheet" href="css/style.css">
    
    <script type="text/javascript">
        function play(param) {

            const playlist = [
              "0 => nincs",
              "audio/audio_01.mp3",
              "audio/audio_02.mp3",
              "audio/audio_03.mp3"
            ];

            var list = param;
            var music = playlist[param];

            var audio = new Audio(music);
            audio.play();
        }
    </script>

</head>
<body>

<h1>ENGLISH PRONUNCIATON NONSENSES – HOMONYMS</h1>

<p onclick = "play(1)">1. The bandage was wound around the wound.</p>
<p onclick = "play(2)">2. The farm was used to produce produce.</p>
<p onclick = "play(3)">3. The dump was so full that it had to refuse more refuse.</p>

</body>
</html>

What does my instructor mean by declare each of the variables marked with “**” in the appropriate scope and using the appropriate type

I’m really lost and just don’t understand what I’m supposed to be doing here. The way my brain works I need some examples. I don’t want the answers. everything I’ve read just isn’t clicking.

The whole //declare each of the variables marked with “**” in the appropriate scope and using the appropriate type. Just doesn’t work out in my head and I cant find any examples of this. Usually pretty good at finding what I need here.

// declare each of the variables marked with "**" in the appropriate scope and using the appropriate type

// create an event listener that calls the curveGrade() function when the Curve It!! button is clicked

// create an event listener that resets the scores and grades to their defaults when the Reset button is clicked

function applyBell(grade, index, ary) {
    switch (true) {
        case grade >= (mean + (gradeSlice * 2)): 
            ary[index] = 'A'
            break
        case grade >= (mean + gradeSlice):  
            ary[index] = 'B'
            break
        case grade >= (mean):
            ary[index] = 'C'
            break
        case grade >= (mean - gradeSlice): 
            ary[index] = 'D'
            break
        default:
            ary[index] = 'F'
            break
    }
}

function convertArray(obj) {
    ary = obj.value.split(',')
    ary = ary.map(function (x) {
        return parseInt(x)
    })
    return ary
}

// Condense the number of lines within the curveGrade() function as much as possible by converting 
// the functions to arrow functions. You can also condense the number of lines by combining some 
// separate lines of code into single lines. It currently has 18 lines of code. Without counting  
// empty lines, can you get the number of lines down to 8?

function curveGrades() {
    **sum = function (accumulator, currentValue) {
        return accumulator + currentValue
    }

    **sumGrades = function(array) {
        return array.reduce(sum)
    }

    **aryGrades = convertArray(document.querySelector('#scores'))

    **minGrade = aryGrades.reduce(function(a, b) {
        return Math.min(a, b)
    })
    
    **maxGrade = aryGrades.reduce(function(a, b) {
        return Math.max(a, b)
    })
    
    **mean = sumGrades(aryGrades) / aryGrades.length

    **range = maxGrade - minGrade

    gradeSlice = range / 5

    aryGrades.forEach(applyBell)

    // write the value of aryGrades to the grades div in the HTML document
}

Lost student in search of help!

Setting Properties on Variable Creation JS C#

C# has a feature that we can set the class instance properties on the element creation (without a constructor). like this:

var Joe = new Person() {
    Age = 36,
    Weight = 83
}

Do we have a similar thing in JS and PHP?

JS something like:

var ActionBox = document.createElement("div") {
    className: "ActionBox"
};

Puppeteer: selecting table rows

enter image description here

I’m working with puppeteer. I have a table as in the screenshot. I need to be able to click on the button under action in a row after selecting the row based on the name column on the left.

In the dev tools console I tried:

$('table[class*="saved-search"] tbody tr')[0].outerHTML

which gives the correct html for the first table row as expected.

My puppeteer script has:

    const targetPage = page;
    targetPage.waitForNavigation({ waitUntil: "networkidle0" });
    const tableSelector = 'table[class*="saved-search"] tbody tr';

    const tableRows = await targetPage.$$(tableSelector);

I have checked a screenshot and the table is visible.

When I look at tableRows in the repl I get:

 []

How can I select the table rows in puppeteer?

how to nest async await in javascript?

I have three functions that should wait for css transition to finish.

the clickHandler() waits for attachTransition(),
and attachTransition() waits for attachListener().

how to implement with async/await ?

function clickHandler(){
  // calls element.attachTransition() and waits for attachListener() to complete
}


let element = {
  attachTransition : function (){
  // calls element.attachListener()
  // adds transition styles to element
  },
  
  attachListener : function (){
  // adds "transitionend" event to element
  // clickHandler() continues execution after this event fired
}
}

Cypress no request occurred

I am using Cypress in my NextJS application. I do 2 requests in my 2 scenarios:

cy.route('PUT', '/1', 'fixture:TEST/update').as('request');
cy.get('button[type="submit"]').click();
cy.wait('@request')
cy.route('PUT', '/1', 'fixture:TEST/update-bad').as('request');
cy.get('button[type="submit"]').click();
cy.wait('@request')

When i run Cypress locally everything is working fine. AFter pushing the changes to github, the CI fails the second test:

CypressError: Timed out retrying after 5000 ms: `cy.wait()`
timed out waiting `5000ms`
for the 1 st request to the route: `request`.No request ever occurred.

I know that there is an update with intercept, but is the same issue.
Why locally it is working but not on CI? How to change the code? Who faced the same issue?

Convert String to Object gives error due to double quotes at start and end

i have an object that is coming from the third party api. and it is in the form like this :

“{ “type”: “object”, “properties”: { “hostUrl”: {
“type”: “string”,
“description”: “hostUrl”, }, }, }”

due to the double quote in the start and the end i am getting error and json parse is also not being removed so kindly tell me how to remove this double quote which has wrapped my object inside it

Countdown won’t return “Kaboom!” when finished

Can someone please tell me what I did wrong and point me in the right direction? It should countdown from 5, 4, 3, 2, 1, Kaboom!

Problem to solve

Here is my code:

let count = 6;
let message = "Start over.";

const handleRequest = (request) => {
  const url = new URL(request.url);

  if (url.pathname.includes("count") && count > 0) {
    count--;
    return new Response(count);
  } if (url.pathname.includes("count") && count <= 0) {
      return new Response("Kaboom!");
  } else {
    return new Response(message);
  }
};

I get this error:

test output: 
Countdown is 5, 4, 3, 2, 1, Kaboom!
AssertionError: Values are not equal:


[Diff] Actual / Expected

-   0
+   Kaboom!

Thanks in advance.

VS code debug – is replacing object values with ellipses. How to show object values in debug?

How can I get the debug console to display the actual values of the sorted object?

The result in the VS Code debug console display as below and are non expandable:

[{…}, {…}, {…}, {…}, {…}, {…}]
No debugger available, can not send 'variables'

Here is a simple program outputting a sorted object that I have written in VS Code.

const items = [
    { name: 'Edward', value: 21 },
    { name: 'Sharpe', value: 37 },
    { name: 'And', value: 45 },
    { name: 'The', value: -12 },
    { name: 'Magnetic', value: 13 },
    { name: 'Zeros', value: 37 }
  ];

// sort by value
items.sort(function (a, b) {
    return a.value - b.value;
  });

// console.log(items);

Here is the launch.json file:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": []
}