How to click on a year in calendar with selenium using javaScript

I am trying to write Selenium test with javaScript but was unable to fill calendar data. It is using a dropdown menu

let calendar = driver.findElement(By.xpath(“//input[@id=’dateOfBirthInput’]”))
await calendar.click()
let month = driver.findElement(By.xpath(“//select[@class=’react-datepicker__month-select’]”))
await month.click()
await month.sendKeys(Key.DOWN, Key.DOWN, Key.RETURN)

let year = driver.findElement(By.xpath(“//select[contains(@class,’react-datepicker__year-select’)]”)).value = “1988”

How can i clcik on value that i need. Consol loging year gives me 1988 but idk how to select it in browser. Is there any other way besides pressing Key.DOWN 35 times. I cannot use Select class in js…

Scaling text to fit within Textbox when changing text value programmatically

I am using a Textbox in my canvas application to allow users to edit text. This is working fantastically for me, as I want text to wrap during editing, and wrap/unwrap as the width of the box is shrunken and expanded.

However, I have a secondary use case that I need some guidance on.

Occasionally, I need to replace the text in the textbox programmatically. In this scenario, I do not want the textbox to wrap text or expand when the text is too long for the width. Instead, I would like to reduce the fontSize so that the text fits on one line.

Note: I only do this text replacement once when the canvas is loaded (or just before in the JSON).

I currently handle this with IText using the following code, but I cannot seem to modify it in a way that works reliably with Textbox. I also lose out on the fantastic text wrapping if I use IText, which is why I’m evaluating this.

const handleTextChanged = ({ target }: { target: fabric.Object }) => {
  const { fixedWidth, width, fontSize } = target

  if (width > fixedWidth) {
    // Shrink the font size to stay within the max width
    target.fontSize = Math.round((fontSize * fixedWidth) / (width + 1))
  }

  target.width = fixedWidth
}

Is there a way to achieve something like this using just Textbox? That is, I would like to keep text wrapping and unwrapping functionality during normal editing, but I would also like to load text in programmatically and have the font size scale to fit the box when I load the canvas.

How can i delete this collection in firebase?

i recently began to use firebase and i ran into a problem, to get it straight, i want to make a e-commerce site, ofcourse it has cart, i used firebase for my back-end, for every user, i create a document in “users” collection, each user’s document id is the uid of that given user. On every document, i have a cart, and in the cart, the products, on my cart page, i want to have a “Empty Cart” that deletes all the products, meaning it deletes “cart” collection. How can i do that? I have left some photos below that will probably explain the problem better.

Image of the firebase tree

I tried this and it did not work!

const deleteCart = async () => {
    const cartDoc = `users/${user.uid}/cart`
    
    await deleteDoc(db, cartDoc)
    
    }

i get this error : ” TypeError: Cannot use ‘in’ operator to search for ‘_delegate’ in undefined “

Alternative languages for web development that offer the benefits of strong typing and efficient refactoring? [closed]

What are the available options for web development that allow for the use of a strongly typed language, while addressing the scalability, testing, and refactoring challenges that are commonly associated with using JavaScript?

Are there any languages or frameworks that provide a balance of the benefits offered by strongly typed languages, such as Java, and the flexibility and ease of use of JavaScript-like programming?

Additionally, are there any alternatives to TypeScript that still offer the benefits of strong typing without the limitations of JavaScript?

Sub-menu moving moving when using sticky

I create a submenu for a nav bar using HTML and CSS. I want the position of the submenu to be fixed since I want the sub-menu to open at the same spot despite which element of the nav bar is hovered on. Further, I’m using sticky to fix the position of the navbar. The problem is when I scroll down if the sub-menu is open, it’s moving down. I’m not sure what is causing this

/*for Sticky*/

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

.sticky+.sub-menu {
  padding-top: 0px;
}


/*style for nav bar*/

nav {
  display: inline-flex;
  width: 100%;
}

.nav-list {
  display: flex;
  width: 100%;
  margin-top: .7rem;
  padding-left: 1.1rem;
}

.nav-list li {
  position: relative;
}

.nav-list>li>a {
  color: black;
  display: block;
  font-size: 1rem;
  padding: 1.3rem 1rem;
  text-transform: uppercase;
}

.sub-menu {
  display: flex;
  position: fixed;
  box-sizing: border-box;
  background-color: black;
  visibility: hidden;
  top: 4.5rem;
  /*adjust postion */
  left: -3rem;
  width: 82.5rem;
  height: 35rem;
}

.sub-menu a {
  position: relative;
  top: 2rem;
  color: white;
  font-size: 1.1rem;
  font-weight: 200;
  padding: 3rem 40px 0 40px;
}

.sub-menu a:hover {
  color: #7e7978;
}

.nav-list li:hover>.sub-menu {
  visibility: visible;
}
<div class="main" id="navbar">
  <div class="logo">
    <a href="">XZY</br> NAME</a>
  </div>
  <nav>
    <ul class="nav-list">
      <li>
        <a href="">Category</a>
        <ul class="sub-menu">
          <li><a href="#">shirts</a> </li>
        </ul>
      </li>
      <ul>
  </nav>
</div>


<div class="content for scroll">
  <a>Enim sociosqu class viverra pellentesque consectetuer a hymenaeos lectus lacinia potenti suscipit sagittis velit. Primis habitant sociis. Mauris nonummy Donec, habitasse vitae ullamcorper aptent velit ligula. Natoque placerat class nunc, natoque iaculis non ac iaculis. Turpis nullam. Suscipit curae; nisl mi eleifend venenatis est phasellus luctus sociosqu facilisis egestas. Porta suspendisse inceptos sociis placerat adipiscing auctor aliquam vel libero aptent. Duis class, sollicitudin, massa sodales, netus volutpat nibh lobortis bibendum est torquent ipsum volutpat pharetra ac eleifend consequat magna vitae tincidunt euismod eleifend lobortis dapibus vitae. Cras sollicitudin nullam per inceptos elementum dolor varius rutrum sollicitudin augue vestibulum ullamcorper donec pharetra feugiat aliquet etiam est turpis velit eros, eu arcu. Elementum interdum tincidunt. Dolor semper consectetuer morbi vivamus aliquam. Id class platea pharetra nec varius tristique dis metus. Fusce nascetur sociosqu ultricies leo mauris maecenas vulputate. Metus vulputate purus cum habitant, erat semper bibendum. Nisi per aliquam nec tellus turpis Curae;. Praesent ornare curae; vehicula mattis potenti vitae torquent montes lorem nam gravida eget sapien natoque risus per nulla quisque ornare ultrices erat morbi dignissim scelerisque dictumst porttitor leo. Aptent facilisis pharetra cras curae; aenean.

Tellus cursus auctor. Volutpat commodo id. Tempor nec natoque integer leo senectus suscipit. Aliquam quisque nulla litora vivamus hymenaeos praesent dui primis. Mollis praesent lobortis tincidunt parturient venenatis. Mattis. Lectus fermentum ornare ornare senectus interdum hac rhoncus sociis litora. Non in lacus egestas sociis. Consequat justo posuere dapibus ornare nulla sollicitudin nascetur donec hymenaeos. Pharetra aliquet imperdiet molestie nullam libero habitant ipsum pharetra quisque ad class natoque hymenaeos justo quisque. Class. Risus duis lacinia eleifend magna penatibus urna, posuere cras Massa quam est mi sapien nisl placerat. Libero fermentum pharetra taciti, auctor metus eleifend mus fermentum luctus felis. Odio condimentum. Pellentesque senectus hymenaeos eget nostra ac vitae. Aenean fusce faucibus dictum. Ornare natoque. Sem. Lobortis malesuada. Lacus ante donec turpis venenatis volutpat, amet condimentum urna pulvinar arcu vitae maecenas libero iaculis elementum senectus dapibus vulputate feugiat viverra pulvinar mattis purus hac rhoncus ridiculus egestas a senectus. Sollicitudin.

Enim, dictumst nullam platea molestie nonummy. Non, donec montes. Erat id. Eu erat commodo ornare potenti curabitur pharetra et curae; velit nec ullamcorper morbi nonummy hymenaeos, montes montes parturient fermentum per. Quis auctor nascetur class eu Venenatis. Pellentesque euismod cras imperdiet malesuada neque scelerisque mollis. Nec molestie pulvinar quis eget erat. Sapien vestibulum nullam metus nec placerat nisl ridiculus sociis suscipit consequat sed facilisis arcu senectus molestie facilisi interdum at vehicula tempor penatibus malesuada. Consectetuer eu adipiscing non. Curae; integer varius pede mi mus. Metus malesuada congue elit molestie orci urna sed ornare vel curabitur vulputate congue convallis felis maecenas adipiscing ac fermentum. Mus fringilla lacus. Non tortor rutrum dis habitasse mattis elementum eleifend. Arcu. Nascetur. Porttitor per, non porttitor. Potenti mi mi sapien nibh. Malesuada praesent per orci eu pulvinar dui ante mollis. Elit luctus sagittis tempus augue cras nunc interdum scelerisque sapien nec dapibus conubia est euismod aliquam arcu ligula porta metus curabitur eleifend sed. Ad sagittis ad. Nullam blandit maecenas dolor orci Quam pharetra duis. </a>
</div>

<script>
  window.onscroll = function() {
    myFunction()
  };

  var navbar = document.getElementById("navbar");
  var sticky = navbar.offsetTop;

  function myFunction() {
    if (window.pageYOffset >= sticky) {
      navbar.classList.add("sticky")
    } else {
      navbar.classList.remove("sticky");
    }
  }
</script>

Click on next element in javascript

I have multiple same containers and each one contains same anchors like:

<div>
  <a href="#" class="button1">Button 1a</a>
  <a href="#" class="button2">Button 2a</a>
<div>
<div>
  <a href="#" class="button1">Button 1b</a>
  <a href="#" class="button2">Button 2b</a>
<div>
<div>
  <a href="#" class="button1">Button 1c</a>
  <a href="#" class="button2">Button 2c</a>
<div>

What I try to achieve is when I click on .button1 should start trigger and auto click on closest .button2

My js code now looks like:

const btn = document.querySelectorAll('.button1')

btn.forEach(function(btn) {
    btn.addEventListener("click", function() {
         console.log(this.innerText)
       this.closest('.button2').click()
    });
});

And here is fiddle: https://jsfiddle.net/4nhvtao1/4/

Passing props to route component through this.$router.push in VueJS

Configuration of router :

const routes = [
    { path: '/' , redirect: '/login'},
    { path: '/chat', component: MyChat,props: true},
    { path: '/login', component: MyLogin},
  ]

Chat component with props :

export default {
    name: "MyChat",
    props:{
      avatar_url : {
        type: String,
      }
    }

The router push to pass props :

 this.$router.push({path:'/chat',props: {avatar_url: 'rrrrrrr'}});

When I’m passing props directly in routes array it does work :

const routes = [
    { path: '/' , redirect: '/login'},
    { path: '/chat', component: MyChat,props: {avatar_url: 'myurl'}},
    { path: '/login', component: MyLogin},
  ]

But when I try to pass props in the this.$router.push it doesn’t , if anyone has an answer to that.

chart js can’t load when insert a second nested async function inside the first

I try to get name and date from dropdown and pass to the api point like parameters:

            <li class="nav-item dropdown" >
                <a class="nav-link dropdown-toggle" id="clicked"  href="#" role="button" data-bs-toggle="dropdown"
                    aria-expanded="false">
                    Име на станция:
                </a>
                <ul class="dropdown-menu" id="clickedNames">
                   
                </ul>
            </li>

            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" id="clicked2" href="#" role="button" data-bs-toggle="dropdown"
                    aria-expanded="false">
                    Дата за прогноза:
                </a>
                <ul class="dropdown-menu" id="clickedDates">
                   
                </ul>
            </li>
        </ul>

With this function I create a chart:

    async function mike11Chart() {
  await getMike11Data()
  //Create second chart
  const ctx2 = document.getElementById('mike11chart');

  new Chart(ctx2, {
    type: 'line',
    data: {
      labels: mike11LabelChart,
      datasets: [{
        type: 'line',
        label: 'Метра',
        data: mike11DataChart,
        borderWidth: 1,
        
      }]
    },
    options: {
      scales: {
        y: {
          type: 'linear',

        }
      }
    }
  })
};

I create this function to get clicked name and date and pass like a parameter:

    //Create a function who will give clicked values like a parameter on API
async function getMike11Data() {
  document.querySelector('#clickedNames').addEventListener('click', showNames)
  document.querySelector('#clickedDates').addEventListener('click', showNames)
  let currFlag = true
  let count = 0;
  async function showNames(e) {

    if (currFlag) {
      dataAPI.nameStation = e.target.innerHTML.replace(/.*+s?/, '');
      currFlag = false;
    } else {
      dataAPI.dateStation = e.target.innerHTML;
    }
    count++;
    if (count != 1) {
      const formatDate = "YYYY-MM-DD HH:mm:ss"
      const apiUrl = "http://194.141.118.43:3010/mike11?id="+dataAPI.nameStation+"&id2="+moment(dataAPI.dateStation).format(formatDate);
     
      const response = await fetch(apiUrl)
      const mike11data = await response.json()

      const mike11date = mike11data.floodguard_mike11.rows.map((x) => x.date)
      //console.log(mike11date)
      const mike11value = mike11data.floodguard_mike11.rows.map((x) => x.level)
      //console.log(mike11value)

      mike11LabelChart = mike11date;
      mike11DataChart = mike11value;
      //debugger;
    }
  }
}

const apiUrl come with correct url path and data coming, but chart cannot displaying.

apiUrl

image

Response come with full data with date and values:

image 2

When I remove showNames() function and paste static url addres on apiUrl which I have copied when debugging from the variable itself everythink is ok and chart is showing.

Like this:

 //Create a function who will give clicked values like a parameter on API
async function getMike11Data() {
  
      const formatDate = "YYYY-MM-DD HH:mm:ss"
      const apiUrl = "http://194.141.118.43:3010/mike11?id=Maritsa%20-%20132543%20-%20HPoint-Water%20level&id2=2023-01-23%2014:00:00"

      const response = await fetch(apiUrl)
      const mike11data = await response.json()

      const mike11date = mike11data.floodguard_mike11.rows.map((x) => x.date)
      //console.log(mike11date)
      const mike11value = mike11data.floodguard_mike11.rows.map((x) => x.level)
      //console.log(mike11value)

      mike11LabelChart = mike11date;
      mike11DataChart = mike11value;
      
    }

When I use hardcoded url address the chart is showing.

How can I otherwise get the clicked name and date and put them in the function getMike11Data();

Set text color based on color of another element in the same spot

I want my fixed text change its color depending on the exact background color that’s currently behind it, pixel-by-pixel. Is it possible?In the given example, part of the text on the blue background would be white
Is it possible to do if the shape on which the text is displayed has different edges than horizontal/vertical?

I tried using JQuery to target specific elements on the page, knowing that the scroll function will only let me target scroll position, so only horizontal elements, and the text will change color in its entirety, not pixel-by-pixel, which would be my goal, as I’m planning to add custom-shaped backgrounds, and it would make the text readable also in transitional positions, as per the example. However, even this didn’t work, possibly due to some CSS issues. Is here a way to do it in CSS?

$(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll <= $('.fp-container-1').offset().bottom) {
      $('nav-button').css('color', 'black');
    }
    if (scroll >= $('.fp-container-2').offset().top) {
      $('nav-button').css('color', 'white');
    }
  });
.fp-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    width: 100vw;
}

.fp-container-1 {
    background-color: rgb(255, 255, 255);
}

.fp-container-2 {
    display: block;
    background-color: rgb(70, 67, 226);
    height: 150vh;
}

Error initializing google maps API from backend node server to keep key secure

I built a webapp that follows the javascript tutorials for google maps api, and now I’m looking to secure the api key by moving whatever functionality is needed to a node server and passing the values of interest up to the front end. My server function is sending the api all the same arguments and is getting back what looks like a valid script string, which I’m passing to the front end and running eval(result) on. The issue is when I run eval() the Google maps API responds that I’m missing the arguments I’ve previously sent.

Am I going about this all wrong? Should I rebuild purely for nodejs? Thank you for any help.

JS function on the node server:

async function startmaps(){
  var payload = {
    key: process.env.GOOGLE_MAPS_API_KEY,
    libraries: ['places', 'geometry'],
    callback: 'initMap'
  };

  var data = new FormData();
  data.append("json", JSON.stringify(payload));

  var result = fetch('https://maps.googleapis.com/maps/api/js',
    {
      method: "POST",
      body: data
    }
  )
  .then((res) => res.text())
    .then((dat) => {
      return {
        data: dat,
        error: false,
        errMsg: ''
      };
    })
    .catch((err) => {
      return {
        data: '',
        error: true,
        errMsg: err.toString()
      };
    });

    return result;
}

Calling function on the front end:

async function StartMaps(){
    var result = await fetch('http://localhost:3000/mapinit')
    .then((res) => res.json())
      .then((data) => {
        return data;
      })
      .catch((error) => {
        return error;
      });

    if(result.data === "undefined" || result.error){
        console.log("got error");
    }else{
        eval(result.data);
    }
}

End result:API errors on eval of result.data

Tried sending Google the sensitive data to initialize the maps from the backend, and passing up to the front end JS the result, however what Google maps API returns seems to realize it’s in another context and complains that it’s missing the api key

“VM403:208 Loading the Google Maps JavaScript API without a callback is not supported: https://developers.google.com/maps/documentation/javascript/url-params#required_parameters
….
util.js:63 Google Maps JavaScript API warning: NoApiKeys https://develope…”

Vue3 – scrollIntoView in watch

I want to type in the input, and if the value of input matches “1” it will scroll to .here, but it isn’t working,

I tried creating a button and adding a handle-click function. It worked.

Please help me.

<template>
  <button @click="scrollToView">Click to Here</button>
  <input type="text" v-model="searchAddress" />
  <span v-if="matchAddress">OK</span>
  <span class="here" ref="el">Here</span>
</template>

<script setup>
import { ref, computed, watch, nextTick } from "vue";
const searchAddress = ref(null);
const el = ref(null);
const matchAddress = computed(() => {
  return searchAddress.value == 1;
});
function scrollToView() {
  el.value.scrollIntoView({ behavior: "smooth", block: "center" });
  el.value.focus({ preventScroll: true });
}
watch(matchAddress, async (val) => {
  console.log(val);
  if (val) {
    await nextTick();
    scrollToView();
  }
});
</script>

DEMO

how to substring in javascript but excluding symbols

I need to use (substring method) in my javascript web network project, but excluding (:) colon symbol, because it is hexa decimal ip address, and I don’t want to accept (:) colons as a string or lets say number in the substring, I want to ignore it, how to do that?

this is the example IPV6 in the input field:

2001:2eb8:0dc1:54ed:0000:0000:0000:0f31

after substring from 1 to 12:

001:2eb8:0d

as you can see it accepted colons also, but in fact, I need this result:

2001:2eb8:0dc1

so by excluding these two symbols, it would have gave me that result above, but I don’t know how.

please don’t close my question.

How can i use javascript variable when i mapping data [duplicate]

i m trying to put variable when i m trying to map my data

import dataimg from '../data/images.json';

const locationState = car

dataimg.(locationState).map((item, index) => (
    <div key={index} className={'container ' + locationState} onClick={() => handleClick(item, index)}>
        <img src={item.link} alt={item.text} className={item.class + ' albumImages'}
        style={{display: locationState == item.class ? 'block' : 'none'}}
        />
    </div>

//how can i use 'locationState' when i try to dataimg.car.map. i try dataimg.locationState*/(that equal car)/*.map((item,index) => (....

my json file is like this

 "car": [{
        "text": "dog",
        "link": "https://images.unsplash.com/photo-1517423440428-a5a00ad493e8?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ",
        "class": "studio"
    },
    {
        "text": "coffe",
        "link": "...link",
        "class": "studio"
    },
]

i try diffirent syntax but still couldnt handle it