My function does not work, how can i make it work?

I am learning Js, and when trying to make a system that: 1. Take the user speed> 2. Compare with the speed allowed on road 3. > ask the user if he was within speed or not. however, when I perform absolutely nothing happens, I have reviewed it thousands of times, looked for syntax errors and still does not run. You can help me?

<!DOCTYPE html>
<html lang="pt-br">
<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>Sist. De Multas</title>
</head>
<body>

    <h1>DETRAN</h1>
    
    
Velocidade de tráfego: <input type="number" name="txtvel" id="txtvel"> Km/h>

    <input type="button" value="Verificar" name="button">

    <div id="res">
        Resultado da verificação:
    </div>

    <script>
   
        function calcular(){
        var calcular = valor.addEventListener('click', calcular)
        var txtv = document.getElementById(txtvel)
        var conversor = Number(txtv.value)
        res.innerHTML = <p>`Sua Velocidade é de ${conversor}`</p>
            if(conversor > 60){
                res.innerHTML = <p>`Multa pendente no sitema por excesso de velocidade ${conversor}Km/h`</p>
            }else{
                res.innerHTML = 'Sem multa pendente'
            }
        }
    </script>

</body>
</html>

Vue3 Dynamically Create a Service Component

In Vue2 I could create and instantiate a Component like this


var service = new Vue({
   data() {
     return {
       example:2,
     }
   },
   computed:{
     score() {
        return this.example * 10;
     }
   }
})

//Returns 20
console.log(service.score)

I understand that this functionality has been removed from Vue 3. But i still require the ability to instantiate components with reactivity, computed functions etc without adding them to the DOM.

Is there a way to do this in Vue3?

I’ve tried createApp, defineComponent, defineAsyncComputed to no avail. And don’t really want to write my own javascript class with reactivity and getters, setters and event listeners…

Node.js + Express.js Cannot read properties of undefined

I’m learning Javascirrpt and I want to build a simple web app using forms.
At first the forms load nicely, but when I want to add something and click “add” an error pops up: Cannot read properties of undefined
Cannot read properties of undefined (reading ‘autor’) I do not really know why it can not “load the autor class”.

Basically, only the one line (marked in index.ejs class) is incorrect.
But, I’ve been wondering about this for a long time now and still have no idea how to fix it.
If someone could give me a hint, I would appreciate it.

app.js

const http = require('http');
const express = require('express');
const app = express();


var globalId = 0;
var person = [];

const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });

app.set('view engine', 'ejs'); 


app.get('/', function(req, res) {
    res.render('index',{data:person}); 
});

app.post('/add',urlencodedParser, function(req, res) {
    console.log("LN:" + req.body.LastName);
    console.log("FN:" + req.body.FirstName);
    console.log("T:" + req.body.Title);
    var os = new os.autor();      ////////this line is wrong///////////
    os.id = globalId++;
    os.lastname = req.body.LastName;
    os.name = req.body.FirstName;
    os.title = req.body.Title;
    person.push(os)
    res.render('index', {data:person}); 
});

const server = http.createServer(app);
const port = 8000;
server.listen(port);
console.debug('Server listening on port ' + port);

index.ejs

<!DOCTYPE html>
<html lang="pl">
<head>
<title>Messages</title>
</head>
<body>
    Autor:
    <ul>
        <% data.forEach(function(msg) { %>
         <li>
             </form action="/del/" method="post">
             <%= msg.Sur %>&nbsp;<%= msg.Name %>&nbsp;Tit:<%= msg.Title %>&nbsp;
             <input id="Id" type="hidden" name="Id" value="<%= msg.id %>">
             <input type="submit" value="-">
             </form>
         </ll>>
        <% }); %>    
    </ul>  

    <%if (data.length == 0) { %>
        <p>&lt;no data!&gt;</p>
    <% } %>

    <br></br>
    
    <form action="/add/" method="post">
        <label for="frontmessage">Sur: </label>
        <input id="LastName" type="text" name="LastName" value="Last Name...">
        <label id="frontmessage">Name: </label> 
        <input id="FirstName" type="text" name="FirstName" value="First Name...">
        <label id="frontmessage">Tit: </label> 
        <input id="Title" type="text" name="Title" value="Title...">
        <input type="submit" value="Add">
    </form>
</body>
</html>

autor.js

exports.autor = function(){
    id:Number;
    lastname:String;
    firstname:String;
    title:String;
};
exports.sum = function(a, b) {
    return a + b;
};

Store ethereum transaction id (metamask) in php variable

I’m not used to javascript and I am using the code below to send an ethereum transaction via metamask, and it looks like it is all working fine, I can print the transaction’s hash after it is sent with document.write, but can’t find a way to store the hash in a php variable to afterwards deal with it in a database and whatever.

I need the value of ‘txHash’ in a php variable. Would appreciate a lot some help! Thanks

sendEthButton.addEventListener('click', () => {
  ethereum
    .request({
      method: 'eth_sendTransaction',
      params: [
        {
          from: accounts[0],
          to: '< - RECEIVING ACCOUNT - >',
          value: '0xDE0B6B3A7640000',
        },
      ],
    })
.then((txHash) => document.write(txHash))
.catch((error) => console.error);
});

Why I can’t get teh data from the user’s input on the page?

Can’t seem to update the location details when I click on one of the cities on the panel or when I search in the search bar. It keeps throwing that catch erro at the end of the fetchWeatherData function “Location not found, please try again”.
I get the data in the console though, I’m new with javascript. Can’t seem to find a solution for this issue

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" />
    <title>Weather</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Rubik:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="./styles.css" />
    <script src="./script.js" defer></script>
    <script
      src="https://kit.fontawesome.com/4e3cd221df.js"
      crossorigin="anonymous"
    ></script>
  </head>
  <body>
    <div class="weather-app">
      <div class="container">
        <h3 class="brand">the weather</h3>
        <div>
          <h1 class="temp">20&#176;</h1>
          <div class="city-time">
            <h1 class="name">Tunis</h1>
            <small>
              <span class="time">00:00</span>
              -
              <span class="date">Monday Mar 16</span>
            </small>
          </div>
          <div class="weather">
            <img
              src="./icons/day/113.png"
              alt="icon"
              class="icon"
              width="50"
              height="50"
            />
            <span class="condition">Clear</span>
          </div>
        </div>
      </div>
      <div class="panel">
        <form id="locationInput">
          <input type="text" class="search" placeholder="Search location" />
          <button class="submit" type="submit">
            <i class="fas fa-search"></i>
          </button>
        </form>

        <ul class="cities">
          <li class="city">Algiers</li>
          <li class="city">Berlin</li>
          <li class="city">Rio</li>
          <li class="city">Moscow</li>
        </ul>
        <ul class="details">
          <h4>Weather Details</h4>
          <li>
            <span>Clear</span>
            <span class="cloud">78%</span>
          </li>
          <li>
            <span>Humidity</span>
            <span class="humidity">42%</span>
          </li>
          <li>
            <span>Wind</span>
            <span class="wind">5km/h</span>
          </li>
        </ul>
      </div>
    </div>
  </body>
</html>

Javascript:

const app = document.querySelector('.weather-app');
const temp = document.querySelector('.temp');
const dateOutput = document.querySelector('.date');
const timeOutput = document.querySelector('.time');
const conditionOutput = document.querySelector('.condition');
const nameOutput = document.querySelector('.name');
const icon = document.querySelector('.icon');
const cloudOutput = document.querySelector('.cloud');
const humidityOutput = document.querySelector('.humidity');
const windOutput = document.querySelector('.wind');
const form = document.getElementById('locationInput');
const search = document.querySelector('.search');
const btn = document.querySelector('.submit');
const cities = document.querySelectorAll('.city');

let cityInput = "Moscow";

cities.forEach((city) => {
    city.addEventListener('click', (e) => {
        cityInput = e.target.textContent;
        fetchWeatherData();
        app.style.opcaity = "0";
    });
})

form.addEventListener('submit', (e) => {
    if (search.value.length == 0) {
        alert('Please enter a city name');
    } else {
        cityInput = search.value;
        fetchWeatherData();
        search.value = "";
        app.style.opcaity = "0";
    }
    e.preventDefault();
})

function dayOfTheWeek(day, month, year) {
    const weekday = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
    ];
    return weekday[new Date(`${day}/${month}/${year}`).getDay()];
};

var api = `https://api.weatherapi.com/v1/current.json?key=edfdd9e1ff7a462f99104631221003&q=${cityInput}`

function fetchWeatherData() {
    fetch(api)
        .then(response => response.json())
        .then(data => {

            console.log(data);

            temp.innerHTML = data.current.temp_c + "&#176;";
            conditionOutput.innerHTML = data.current.condition.text;


            const date = data.location.localtime;
            const y = parseInt(date.substr(0, 4));
            const m = parseInt(date.substr(5, 2));
            const d = parseInt(date.substr(8, 2));
            const time = date.substr(11);


            dateOutput.innerHTML = `${dayOfTheWeek(d, m, y)} ${d}, ${m}, ${y}`;
            timeOutput.innerHTML = time;

            nameOutput.innerHTML = data.location.name;

            const iconId = data.current.condition.icon.subtr(
                "//cdn.weatherapi.com/weather/64x64/".length);
            icon.src = "./icons" + iconId;

            cloudOutput.innerHTML = data.current.cloud + "%";
            humidityOutput.innerHTML = data.current.humidity + "%";
            windOutput.innerHTML = data.current.wind_kph + "km/h";

            let timeOfDay = "day";
            const code = data.current.condition.code;

            if (!data.current.is_day) {
                timeOfDay = "night";
            }

            if (code == 1000) {
                app.style.backgroundImage = `
                url(./images/${timeOfDay}/clear.jpg1)`;
                btn.style.background = "#e5ba92";
                if (timeOfDay == "night") {
                    btn.style.background = "#181e27";
                }
            } else if (
                code == 1003 ||
                code == 1006 ||
                code == 1009 ||
                code == 1030 ||
                code == 1069 ||
                code == 1087 ||
                code == 1135 ||
                code == 1273 ||
                code == 1276 ||
                code == 1279 ||
                code == 1282
            ) {
                app.style.backgroundImage = `
                url(./images/${timeOfDay}/cloudy.jpg1)`;
                btn.style.background = "#fa6d1b";
                if (timeOfDay == "night") {
                    btn.style.background = "#181e27";
                }
            } else if (
                code == 1063 ||
                code == 1069 ||
                code == 1072 ||
                code == 1150 ||
                code == 1153 ||
                code == 1180 ||
                code == 1183 ||
                code == 1186 ||
                code == 1189 ||
                code == 1192 ||
                code == 1195 ||
                code == 1204 ||
                code == 1207 ||
                code == 1240 ||
                code == 1243 ||
                code == 1246 ||
                code == 1249 ||
                code == 1252
            ) {
                app.style.backgroundImage = `
                url(./images/${timeOfDay}/rainy.jpg1)`;
                btn.style.background = "#fa6d1b";
                if (timeOfDay == "night") {
                    btn.style.background = "#325c80";
                }
            } else {
                app.style.backgroundImage = `
                url(./images/${timeOfDay}/snowy.jpg1)`;
                btn.style.background = "#4d72aa";
                if (timeOfDay == "night") {
                    btn.style.background = "#1b1b1b";
                }
            }
            app.style.opcaity = "1";

        })

        .catch(() => {
            alert('Location not found, try again please');
            app.style.opcaity = "1";
        });
}

fetchWeatherData();

app.style.opcaity = "1";

Scrape dynamic website using requests by headers

The website I am working on is dynamic with javascript. When directly using requests, it gives me message <noscript>Javascript is required. Please enable javascript before you are allowed to see this page.</noscript>. I have used this link https://curlconverter.com/# copy the cURL (bash) to it to get the python code. the python code works fine for this approach. I began to remove unnecessary lines of headers, and finally let two of the lines of cookies sucuri_cloudproxy and cookiesession1. The code is working fine.
But I need to get the cookies each time I execute the code, so I used selenium for once to get the cookies. But this doesn’t work as expected and I got the same message posted at the beginning of the question
Here’s my try till now

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import requests
from bs4 import BeautifulSoup

url = 'https://www.moi.gov.kw/mfservices/immigration-fines/residency/295010900353'

opts = Options()
opts.headless = True
driver = webdriver.Chrome(executable_path='D:/Webdrivers/chromedriver.exe', options=opts)
driver.get(url)
cookies = driver.get_cookies()

for cookie in cookies:
    if 'sucuri_cloudproxy' in cookie['name']: x1=cookie['name'] + '=' + cookie['value']
    if cookie['name'] == 'cookiesession1': x2=cookie['name'] + '=' + cookie['value']

sessionlist = []
sessionlist = list([x1, x2])
sessionid = ';'.join(sessionlist)
print(sessionid, 'n')

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36',
    'cookie': "'" + sessionid + "'",
}

mylist = ['236033100148', '295010900353']
for item in mylist:
    response = requests.get(f'https://www.moi.gov.kw/mfservices/immigration-fines/residency/{item}', headers=headers)
    print(response.text)

What is the name of such UI component? [closed]

I am very new to the front-end development and I am trying to improve my skills by building different UI components that I see on some websites. I came across this very nice looking component and I want to start looking for tutorials on how to build something like that but I don’t know how it is called so I don’t know what I should be looking for.

Maybe someone could suggest how such component is called so I can start looking for some tutorials? UI Component

This component shows up after user clicks on a button.

How to use webpack to join JS files?

I have to merge several files from my website with webpack, and for that I need to work with JS modules.

This is a child file.

export default () =>  {
    $('[data-direction]').on('click', switchFeatured)
    function switchFeatured (event) {
        const icon = $(event.currentTarget);
        if (icon.data().direction === 'right') {
            if (featuredCurrent < featuredTotal) {
                featuredCurrent++;
            }
        } else {
            if (featuredCurrent > 1) {
                featuredCurrent--;
            }
        }
        $('#featured-list').css('left', ( (featuredCurrent - 1) * -100) + '%');
    }
}

This is the main file.

window.$ = require ('jquery')

import Default from './pages/default'
import Home from './pages/home'

Default();
Home();

It’s working this way, but is the way I export and use the imported modules correct? Got a better way?

Javascript counter not stoping

for this counter I made, I used the setInterval, and when every digit is equal to zero I expect this to clear the interval, but it’s not working! Can someone help me out?

const counterHTML = document.querySelector("#counter");
const timeString = localStorage.getItem("Time");

function timeToAdd(stringTime) {
  const timeArray = stringTime.split(":");
  const hoursInMiliseconds = timeArray[0] * 60 * 60 * 1000;
  const minutesInMiliseconds = timeArray[1] * 60 * 1000;
  const TIME_IN_MILISECONDS = hoursInMiliseconds + minutesInMiliseconds;
  return TIME_IN_MILISECONDS;
}

const actualTime = Date.now();
const finalTimeDateObj = new Date(actualTime + timeToAdd(timeString));
const finalTime = finalTimeDateObj.getTime();

const time = (myTimerInterval) => {
  const timeNow = Date.now();
  const diference = finalTime - timeNow;
  let displayTimeArray = msToTime(diference);
  console.log(diference);
  const hours = String(displayTimeArray[0]).padStart(2, "0");
  const minutes = String(displayTimeArray[1]).padStart(2, "0");
  const seconds = String(displayTimeArray[2]).padStart(2, "0");
  if (hours == "00" && minutes == "00" && seconds == "00") {
    clearInterval(myTimerInterval);
  }
  counterHTML.innerText = `${hours}:${minutes}:${seconds}`;
};

function msToTime(millis) {
  let h, m, s;
  h = Math.floor(millis / 1000 / 60 / 60);
  m = Math.floor((millis / 1000 / 60 / 60 - h) * 60);
  s = Math.floor(((millis / 1000 / 60 / 60 - h) * 60 - m) * 60);
  return [h, m, s];
}

var myTimerInterval = setInterval(time, 1000);

chrome addon VueJS element disappears when rendered

I have a successfully running developer mode addon that works in Chrome.

I would like a button on the page running Vue (which I’ve used for years). Here is my code:

    let isletCtl = document.createElement('div')
    isletCtl.id = "islet-ctl"
    isletCtl.innerText = 'isletCtl: '

    let isletVue = document.createElement('div')
    isletVue.id = 'islet-vue'
    isletVue.innerText = 'isletVue: {{ response }}'
    isletCtl.appendChild(isletVue)
    document.body.appendChild(isletCtl)

    window.setTimeout(function(){
        new Vue({
            el: "#islet-vue",
            data: function(){
                return {response: 'hello vue'}
            }
        })
    }, 25000)

The 25s delay was just to figure out what is going on. the button renders just fine, but when the Vue({ ... }) piece renders, the #islet-vue div just disappears from the DOM!

Anyone have an answer as to why this is happening?

Queryselector removing wrong item

I’m working on an e-commerce site, and I’m trying to implement a delete button. Currently, the delete button is not working correctly, sometimes I have to double-click for it to work, and when it does it doesn’t remove the selected product. It seems to delete a product based on when it was added i.e oldest added product to latest.

enter image description here
enter image description here

The delete button kinda works, it doesn’t remove the selected product, instead, it the deletes product based on the oldest added to the newly added. does someone know?

 <div class="table-responsive-sm">
  <table class="table">
    <thead>
      <tr>
        <th scope="col">Picture</th>
        <th scope="col">Title</th>
        <th scope="col">Brand</th>
        <th scope="col">size</th>
        <th scope="col">Price</th>
        <th scope="col">Actions</th>
      </tr>
    </thead><% if (products.length> 0) { %><% products.forEach(product=> { %> <tbody id="table-body">
      <tr>
        <td>
          <img src="/uploads/resized/<%= product.picture%>" style="width: 10%; height: auto;">
        </td>
        <!--move style to css later //Karwan-->
        <td class="table-title">
          <p><%= product.title %> </p>
        </td>
        <td>
          <p><%= product.brand %> </p>
        </td>
        <td>
          <p><%= product.size %> </p>
        </td>
        <td>
          <p><%= product.price %> </p>
        </td>
        <td>
          <div class="px-2 mt-3">
            <!--Modal pop up to delete a  product -->
            <a class="single" data-toggle="modal" data-target="#deleteProduct">
              <!--make sure these are correct -->
              <button class="btn btn-form-productt" type="submit">Delete</button>
              <!--add icon-->
            </a>
            <!--Delete product modal-->
            <div class="modal fade" id="deleteProduct">
              <div class="modal-dialog">
                <div class="modal-content">
                  <div class="modal-header">
                    <h5 class="modal-title">Click on delete to confirm your deletion</h5>
                    <!--Delete btn -->
                    <a class="single">
                      <button class="btn btn-form-productt">
                        <a class="delete" data-doc="<%= product._id %>">
                          <i class="fa-solid fa-trash"></i>
                        </a>
                      </button>
                    </a>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </td><% }) %><% } else { %> <p>There are no products to display...</p><% } %>
      </tr>
    </tbody>
  </table>
</div>

// Javascript code

         <script>
 //Delete product
 const trashcan = document.querySelectorAll('a.delete');
 trashcan.forEach(function(el) {
   el.addEventListener('click', function() {
     const endpoint = `/shop/delete/${el.dataset.doc}`;
     fetch(endpoint, {
       method: 'DELETE',
     }).then(response => response.json()).then((data) => window.location.href = data.redirect).catch(err => console.log(err));
   })
 })
  </script>

React connecting Metamask and passing signer to multiple contracts

I’m trying to figure out how to share signer between multiple js files. I have a file walletConnect.js where I connect to Metamask and get ERC20 token contract. This works fine.

async function connect(){
  try{
    const accounts = await ethereum.request({
      method: "eth_requestAccounts",
    });
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();

    // ERC20 token contract
    const tokenContract = new ethers.Contract(
        tokenAddress,
        tokenAbi,
        signer
     );
  } catch (e) {
    console.log(e);
  }
}

and then I have another file stake.js where I deposit a token into a contract

async function stakeToken() {
   try {
     const stakingContract = new ethers.Contract(
        contractAddress,
        contractAbi,
        signer
    );
    
    // approve contract
    await tokenContract.approve(stakingContract.address, maxAmount);

    // stake tokens
    await stakingContract.stakeTokens(
      tokenContract.address,
      amount
    );
  } catch (e) {
    console.log(e);
  }
}

Everything works fine if I have all code in one file. I use useState hook and all is good. However I will have multiple staking contracts I would like to keep in separate javascript files. How do I do it when having multiple files?

When on Click radio button refresh the page without reloading using jquery or javascript

<div><label class="STAA0-radio-btn mr-3">
<input type="radio"  id="new" name="Condition" value="1" onchange="conditionType(this.value)" >
<span>New Material</span
</label>
<label class="STAA0-radio-btn mr-3">
<input type="radio" id="used"name="Condition"value="2"onchange="conditionType(this.value)"
checked>
<span>Used Material</span'
</label>
</div>

on selecting(check) radio button. the page should refresh without reloading and select radio button should checked using Javascript or jquery .new solution ?