How do I select a DOM element that has multiple classes?

I am trying to select a DOM element that has these classes:

mq-editable-field mq-math-mode mq-field

I have tried using:

document.getElementsByClassName('mq-editable-field mq-math-mode mq-focused')

This is not working, is there another document function I should be using? I am using vanilla javascript.

Parent state passed as props not updated when rendered in .map function

In the TableAndInfo Component, each row’s parent element is rendered by the renderEls function and the content is returned by the renderSection function. This passes in the content in the sections property as a parameter, as well as the class of the parent container. Passing the props value of date, time, and current in the sections array results in a successful initial render, but they do not continue updating when the state changes. I have inspected the code with the React Developer Tools and I see that the state is being updated by the functions defined in the App function and other components. How do I ensure that the grandchildren elements are re-rendered when the state is updated? Sorry if this doesn’t make sense, I was having trouble trying to explain the problem. Thanks in advance!

function App() {
    var [component, updateView] = useState('ServerFunctions');

    var updateDateAndTime = function(formatDate) {
        setInterval(function() {
            if (document.getElementsByClassName('date')[0] && document.getElementsByClassName('time')[0]) {
                updateDate(formatDate('date'));
                updateTime(formatDate('time'));
            }
        }, 1000);
    };

    useEffect(() => {
        updateDateAndTime(formatDate);
    });

    var [date, updateDate] = useState(formatDate('date'));
    var [time, updateTime] = useState(formatDate('time'));

    switch(component) {
        case 'Welcome':
            return (<Welcome updateView={updateView} date={date} time={time} backspacePinpad={backspacePinpad} />);
        case 'ServerFunctions':
            return (<ServerFunctions updateView={updateView} date={date} time={time} />);
        default:
            return null;
    }
}

class TablesAndInfo extends React.Component {
    sections = [[['info-row pct-space-b', 'flex between full-h'], {
        1: ['Menu', 'button', 'gray white-f clickable roundish quarter-w label clickable'],
        2: [this.props.current, 'div', 'f-override white-b small left three-quarter-w no-txt-overflow'],
    }], [['info-table full-h', 'flex full-h'], {
        1: ['Another Round', 'button', 'info-button blue white-f clickable'],
        2: ['Select All', 'button', 'info-button gray white-f clickable'],
        3: ['Name Check', 'button', 'info-button yellow clickable'],
    }], [['tables-section full-h', 'tables-section full-h white-b'], {
    }], [['new-table-b full-h', 'new-table-b med single round label full-h full-w'], {
        1: ['New Table', 'button', 'blue white-f med single clickable round label clickable full-h full-w']
    }]];

    renderEls(num, classes) {
        return (
            <div className={classes}>
                {this.sections[num].map((child, key) => {
                    if (typeof child === 'object' && !(child instanceof Array)) {
                        return (
                            <div className={this.sections[num][0][0]}>{this.renderSection(child, this.sections[num][0][1], key)}</div>
                        )
                    } else {
                        return null;
                    }
                })}
            </div>
        )
    }

    renderSection(obj, parentClass) {
        return (
            <div className={parentClass}>
                {Object.keys(obj).map((key, i) => {
                    if (obj[key][1] === 'button') {
                        return (
                            <button key={i} className={"flex center " + obj[key][2]}>{obj[key][0]}</button>
                        )
                    } else {
                        return (
                            <div key={i} className={"flex center " + obj[key][2]}>{obj[key][0]}</div>
                        )
                    }
                })}
            </div>
        )
    }

    render() {
        return (
            <div className="tables space-r">
                <div className="info tables-section">
                    {this.renderEls(0, 'info-table info-r')}
                    {this.renderEls(1, 'info-table info-b')}
                </div>
                {this.renderEls(2, 'table-view tables-section full-h pct-space-b')}
                {this.renderEls(3, 'new-table')}
            </div>
        )
    }

class ServerFunctions extends React.Component {
        return (
            <div className="App ServerFunctions">
                <Header signOff={this.signOff} renderBttnRow={this.renderBttnRow} />
                <div className="container order-control flex space-b">
                    <SelectedItems />
                    <TablesAndInfo current={this.state.current} date={this.props.date} time={this.props.time} />
                    <Functions current={this.state.current} />
                </div>
                <Footer current={this.state.current} renderBttnRow={this.renderBttnRow} />
            </div>
        )
    }
}

Cant show my features in openlayers. Does someone know how to solve this?

I have been struggling with my projections for a few weeks now. At the beginning I could show my features but they appear in jemen (they are supposed to be in Italy). After I realised my coordinates were being inversed, for example my coordinate [41.18702782291,15.450187402143] (which is in Italy) was displaying in [15.450187402143, 41.18702782291] (which is in jemen), I decided to invert the coordinates of the multipolygons of my geometries so that now I have the [15.450187402143, 41.18702782291] format. I don“t know what happened but now I cant see my features shown in the map.

I have an object geojson with my features and this is my code:


var myview = new View({
  center: [15.450187402143, 41.18702782291],
  projection: 'EPSG:4326',
  zoom: 6
})

var mylayer = new TileLayer({
  source: new OSM()
})

var layer = [mylayer]

const map = new Map({
  target: 'map',
  layers: layer,
  view: myview
}); 

const vectorSource = new VectorSource({
  format: new ol.format.GeoJSON(),
  features: (new ol.format.GeoJSON()).readFeatures(geoJson, {dataProjection: 'EPSG:4326',
  featureProjection: map.getView().getProjection()})
  //EPSG:32633 - WGS 84 / UTM zone 33N
  //features: new GeoJSON().readFeatures(geoJson, {dataProjection: 'EPSG:4326', FeatureProjection: map.getView().getProjection()})
});

console.log(geoJson);
console.log(vectorSource.getFormat());
vectorSource.addFeatures((vectorSource.getFormat()).readFeatures(geoJson));
console.log("1");
const vectorLayer = new VectorLayer({
  source: vectorSource
});

map.addLayer(vectorLayer);

const numFeatures = vectorLayer.getSource().getFeatures().length;
console.log("Count right after construction: " + numFeatures);

The final lines show that the features are in the source and it is correctly getting them.

How can I delete a user from my mongoose and node web app?

I have so far got an app where users can register and sign in. I have also implicated a role based system, However I am struggling when it comes to deleting a user. I have looked all over the web but nothing seems to work. I think my delete route is fine, but when I click the delete button nothing happens. I have identified the user id in the url but it doesn’t delete. Any help would be much appreciated.

in routes/admin.js

//Delete a user
router.delete('/delete/:id', (req, res, next) => {
  try {
    User.findByIdAndDelete({_id: req.params.id});
  // res.redirect('/admin');
  } catch (error) {
    res.redirect('/index');
  }
});

in views/manage-users.ejs

<form action="/admin/delete/:<%= user.id %>" method="delete">
          <button type="submit">DELETE</button>
      </form>

Full Page loader

I have created a ripple full page loader.

Am trying to create the one like here:https://templatemo.com/templates/templatemo_558_klassy_cafe/
I want the code to be simple with no plugins ideally.
I can load the page preloader but am wondering how I get the loading page to disappear once the main page has loaded? The page just will not fade! Have researched and tried all sorts of methods.
This is the code so far:

HTML:

      <div id="preloader">
        <div class="jumper">
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>  

CSS:

#preloader {
  overflow: hidden;
  background-color: #fb5849;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  position: fixed;
  z-index: 99999;
  color: #fff;
}

#preloader .jumper {
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  display: block;
  position: absolute;
  margin: auto;
  width: 50px;
  height: 50px;
}

#preloader .jumper > div {
  background-color: #fff;
  width: 10px;
  height: 10px;
  border-radius: 100%;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  position: absolute;
  opacity: 0;
  width: 50px;
  height: 50px;
  -webkit-animation: jumper 1s 0s linear infinite;
  animation: jumper 1s 0s linear infinite;
}

#preloader .jumper > div:nth-child(2) {
  -webkit-animation-delay: 0.33333s;
  animation-delay: 0.33333s;
}

#preloader .jumper > div:nth-child(3) {
  -webkit-animation-delay: 0.66666s;
  animation-delay: 0.66666s;
}

@-webkit-keyframes jumper {
  0% {
    opacity: 0;
    -webkit-transform: scale(0);
    transform: scale(0);
  }
  5% {
    opacity: 1;
  }
  100% {
    -webkit-transform: scale(1);
    transform: scale(1);
    opacity: 0;
  }
}

@keyframes jumper {
  0% {
    opacity: 0;
    -webkit-transform: scale(0);
    transform: scale(0);
  }
  5% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

The javascrip so far:

<script type="text/javascript">

    // Page loading animation
    $(window).on('load', function() {
        if($('.cover').length){
            $('.cover').parallax({
                imageSrc: $('.cover').data('image'),
                zIndex: '1'
            });
        }

        $("#preloader").animate({
            'opacity': '0'
        }, 600, function(){
            setTimeout(function(){
                $("#preloader").css("visibility", "hidden").fadeOut();
            }, 300);
        });
    });

</script>

hashing password to login. how can I join this?

I have a code for the login and a code for hassing the password, but dont know very well how to use them and to make them work in the server (how can I join them). Can some one please help me with this, making it work? it should be a register login to the web I’m making, I the password should be hashed. Can some one explain a bit what I have in the js (I found it on medium, but the post wasn’t very explainatory and dont know how to use it but it might help someone.

login dot html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
  <link rel="stylesheet" href="login.css">
  <script defer src="login.js"></script>
</head>

    <body>
      <main id="main-holder">
        <h1 id="login-header">Login</h1>
        
        <div id="login-error-msg-holder">
          <p id="login-error-msg">Invalid username <span id="error-msg-second-line">and/or password</span></p>
        </div>
        
        <form id="login-form">
          <input type="text" name="username" id="username-field" class="login-form-field" placeholder="Username">
          <input type="password" name="password" id="password-field" class="login-form-field" placeholder="Password">
          <input type="submit" value="Login" id="login-form-submit">
        </form>
      
      </main>
    </body>
    
    </html>

hashing-server.js

const express = require("express");
const bodyparser = require("body-parser");
const bcrypt = require('bcryptjs');

const app = express();
app.use(bodyparser.json());

//create mysql connection
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'raja',
  database: 'alead'
});

//define port
const port=3000;

app.get("/", (req, res) => {
res.json({message:'Root page'})
})


//login query example
app.get("/veify_password", (request, response) => {
const req=request.query
const query="SELECT password from user_master where username=?";
const params=[req.username]
connection.query(query,params,(err,rows) => {
  if(err) throw err;
  //
  var output={}
  if(rows.length!=0)
  {
    var password_hash=rows[0]["password"];
    const verified = bcrypt.compareSync(req.password, password_hash);
    if(verified)
    {
    output["status"]=1;

    }else{
    output["status"]=0;
    output["message"]="Invalid password";

    }

  }else{
    output["status"]=0;
    output["message"]="Invalid username and password";

  }
  response.json(output)

});
})


//run the application
app.listen(port, () => {
  console.log(`running at port ${port}`);
});

Is there an issue with react-native-video not playing external source?

I spun a react-native app using the react native cli. To play videos, I installed package ‘react-native-video’.

Problem statement – I am running the app in ios simulator. The video is playing for a local video file. But the video player is not playing an external video url. Why?

Please find below the code snippet –
– Working for a local video file

import video1 from '../src/assets/video.mp4'


<Video
  source={video1}
  style={{  height: 400, width: '100%' }}
/>

– Non-working code sample for external url

<Video
  source={{uri: 'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4'}}
  style={{  height: 400, width: '100%' }}
/>

Below are the versions of the dependencies
react-native-video: 5.2.0
react-native: 0.67.4
react: 17.0.2
xcode: 13.0
ios Simulator: 13.0

Vue 3 (composition API) get array length

I’m learning javascript and vue.js 3 composition API.
My question is I simply want to get an array length and render at

.
The array name : “getForms”

<script>.....
const forms_length = computed(() =>  getForms.value.length)

<template>....
<p> {{form_length}} </p>

I get an error “Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘length’)”

why? and what I should do?

Thank you for your help!

CORS: Browser not expsoing `location` header even though it’s allowed in the `Access-Control-Allow-Headers`

I’ve been doing some work to configure CORS on my API server to restrict access. I’m currently serving the following headers for Access-Control-Allow-Headers from the options preflight.

access-control-allow-headers: location,x-correlation-id,content-range,authorization,accept,content-type,origin

Full OPTIONS preflight response:
enter image description here

However, when doing a POST where it returns a 201 response, the location header is not visible in my Axios response object in javascript. This appears to be caused by the browser rejecting the location header based on the CORS policy. I’m not sure what I’m missing that would allow the location header to pass-through to the browser.

POST Response
enter image description here

console.log of the response object in code.
enter image description here

How to add user inputs on button click

Self taught coder here. Hopefully I can explain this problem adequately. The desired output is to have a button that, when clicked, will create another div that has user inputs. I have a website that allows a user to upload their own cooking guide. The guide takes things like name, author, ingredients etc. The hard part is when it gets to the steps of the recipe. Each recipe has a different number of steps. So I want a button the user can click to add a step. It looks like this

  await setDoc(doc(db, "guides", newId), {
      author: e.target.author.value,
      categoryId: '100',
      categoryName: e.target.categoryName.value,
      coverImg: data.img,
      id: newId,
      name: e.target.name.value,
      tags: e.target.tags.value,
      steps: [ <-- I need a button that will add another step + img below to this array
        {
          step: e.target.step.value,
          img: data.img
        }
      ]
    });
  };

I was thinking I could do something like this using state and a clickhandler, although the state is an empty array, but the counter is a number. Which method would make more sense?:

  const [stepsArray, setStepsArray] = useState([])

  const handleAddSteps = () => {
    setStepsArray(stepsArray + 1)
  };

Then I figured I could maybe map out the steps array in jsx somehow althought not sure if this will work.

stepsArray.map((step => {
 <div className="upload__card upload__card--addstep">
          <div className="upload__inputs">
            <label 
            className="upload__label">{steps.step + 1}</label>
            <input 
            className="upload__input upload__input--large"
            name="step"
            ></input>
          </div>
          <div className="upload__inputs">
            <div>
              <img src={file ? URL.createObjectURL(file) : ""}></img>
            </div>
            <label 
              htmlFor="file"
              style={{cursor:'pointer'}}
              className="upload__add">+ GIF
            </label>
            <input 
              id="file"
              onChange={e => setFile(e.target.files[0])}
              style={{display: "none"}}
              type="file">
            </input>
          </div>
        </div>
        <button }

This is how the user values are being uploaded to firebase. My question is also how would I get the STEPS array to update to add steps each time the ADD STEP button is clicked by the user? Hopefully my logic is heading in the right direction.

browserify not working on basic html and basic js

I’m trying to create an simple web page to test the crypto module in js, but even when i use browserify my brower returns Uncaught ReferenceError: require is not defined.

My script.js:

const { createHash } = require('crypto');


function hasher() {
    const password = document.getElementById("js_n_password").value;
    const hash = createHash(password);
    document.getElementById("hashed").innerHTML = password;
}

My index.html:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css">
        <script src="bundle.js"></script>
        <script src="script.js"></script>
    </head>
    <body>


        <h1>Web Hash</h1>
        <form class="input" id="input">
            <label for="n_password">Password:</label>
            <input type="password" id="js_n_password" name="n_password">
        </form> 
        <button onclick="hasher()">hash it</button> 

        <p class="hashed" id="hashed"> </p>

    </body>
</html>

Why browserify isn’t working and how can i make it work?

PS: add module.exports = function (n) { return n * 111 } to script.js doesn’t change anything.

How to handle the event propagation dilemma

I am trying to make 3 controls working together in my app and they are panel(can be open or closed from the page), modal and a color picker. Their relationship is the panel creates the modal by clicking some button in the panel and inside the modal, there is a color picker. The panel and the color picker comes from a library and the modal implemented myself. The panel has a has an event listener using the capture option on document.body (top-down event priority), so the panel will handle the mousedown event before it reaches the modal causing the panel to close while clicking on the modal created by the panel, thus closing the modal as well. To prevent this, the capture option to the mousedown event listener on the document to stop mouse down event propagate is added in the modal. Now I want to add a color picker to the modal, unfortunately, the color picker has event listeners to mouse down event to handle color selection in the color palette. If I have stop propagation on the document, the mouse down event never reaches the color picker therefore cannot pick color. I would like to know if there is any way to solve this problem(with cannot modify code in panel and color picker but modal is fine)? Thank you!

External Javascript is not working on router change in Angular

I’m using external javascript from my assets/js/script.js file in angular to enable buttons that are disabled by default. But it only works on the first page once l route to another component and comes back to the watch page the javascript is not loaded. check below my code.

my watch.html code

      <div class="buttons" *ngIf="video.video !== '/lessons/'">
        <div class="mybuttons">
          <button type="button" class="btn btn-secondary next" id="quizBtn" (click)="quiz(video.name)" disabled>
            <span class="ti-agenda"></span>
            QUIZ
          </button>
        </div>

        <div class="divider"></div>

        <div class="mybuttons">
          <button type="button" class="btn btn-secondary next" id="bookBtn" (click)="book(video.subtopic)" disabled>
            <span class="ti-calendar"></span>
            Book Tutor
          </button>
        </div>

      </div>

my script.js

 window.onload = function () {
  el = document.getElementById("video");

  if (el) {
    el.addEventListener("ended", videoEndHandler, false);
  }
};

function videoEndHandler(e) {
  document.getElementById("quizBtn").disabled = false;
  document.getElementById("bookBtn").disabled = false;
}

How do l make this external js file work even on router change?

Repostioning absolute position element based on a siblings change

I am working on some functionality where is user clicks a button it shows some “sub data” below a parent div. The markup looks similar to this,

<div class="row row-parent row-parent-index-1" style="top:20px">I am a parent (1)</div>
<div class="row" data-top="40px">I am a child (1)</div>
<div class="row" data-top="60px">I am a child (2)</div>
<div class="row" data-top="80px">I am a child (3)</div>
<div class="row row-parent row-parent-index-1" style="top:40px">I am a parent (2)</div>
<div class="row" data-top="top:40px">I am a child (1/2)</div>
<div class="row" data-top="top:60px">I am a child (2/2)</div>
<div class="row" data-top="80px">I am a child (3/2)</div>

Currently I have it working so that if a user clicks the row .row-parent-index-1 it takes the data-top attribute of all the elments between .row-parent-index-0and.row-parent-index-1and changes the top position to match that of thedata-top` the problem I need to reflect the change in all elements other wise I am going to get overlapping elements, if there a way to reposition absolute elements based on another elements position?

i.e if the element at index of 4 in the dom has top position of 80, we need to move all the following elements down 80px too?

Here is my attempt,

this.rowEl.addEventListener('click', (event) => {
    const target = event.currentTarget as HTMLElement;
    if(target.classList.contains("datagrid-parent-expanded")) {
      target.classList.remove('datagrid-parent-expanded');
    } else {
      target.classList.add('datagrid-parent-expanded');
      const indexOfCurrParent:any = parseInt(`${target?.dataset?.parentIndex}`);
      const targetClassList = target.classList.value;
      const siblings = helpers.nextUntil(document.querySelector(`.datagrid-main .datagrid-row-parent-index-${indexOfCurrParent}`), `.datagrid-main .datagrid-row-parent-index-${indexOfCurrParent+1}`);
      for (let rowIndex = 0; rowIndex < siblings.length; rowIndex++) {
        let currRow = siblings[rowIndex];
        currRow.style.setProperty("top", `${currRow.dataset.top}`);
        currRow.classList.add('datagrid-parent-expanded');
      }
      const nextSibling = siblings.pop().snextElementSibling as HTMLElement;
      const nextSiblingPosition = nextSibling.dataset.top!;
      nextSibling.style.top = parseInt(nextSiblingPosition, 10) + 20 + "px";
    }
  });

What I am trying to here is get the last element from the nextUntil function and take it’s siblings position and add on the appropriate difference?