Javascript Images Cycle on Hover

I’m new to coding and would like to adapt a code I got from CodePen for my website.
It is to hover over an image and the images below will automatically cycle.
However this code works for only one set of images and doesn’t work if I have two sets of images.
I would really like to learn why please??? Thank you.

<html>
<style>
.js-animated figure.active {
  opacity: 1;
}

.image-deck {
  position: relative;
  height: 12rem;
  width: 18rem;
}

.image-deck figure {
  opacity: 0;
  height: 100%;
  width: 100%;
  position: absolute;
}

.image-deck figure img {
  height: 100%;
  width: 100%;
}
</style>

<body>
    <!--Working-->
    <div class="image-deck js-animated">
        <figure>
            <img src="https://picsum.photos/300/300">
        </figure>
        <figure>
            <img src="https://picsum.photos/301/301">
        </figure>
        <figure>
            <img src="https://picsum.photos/302/302">
        </figure>
        <figure>
            <img src="https://picsum.photos/303/303">
        </figure>
    </div>
    
    <!--Not Working-->
    <div class="image-deck js-animated">
        <figure>
            <img src="https://picsum.photos/304/304">
        </figure>
        <figure>
            <img src="https://picsum.photos/305/305">
        </figure>
        <figure>
            <img src="https://picsum.photos/306/306">
        </figure>
        <figure>
            <img src="https://picsum.photos/307/307">
        </figure>
    </div>
</body>

<script>
    // get the image wrapper
    const imageDeck = document.querySelector(".image-deck.js-animated");

    // get the set of images within the wrapper
    const images = imageDeck.children;

    // reveal the first image
    images[0].classList.add("active");

    // set up the iterator
    let i = 0;

    // set up the function that we will call from our repeater
    function cyclePhotos() {

        // remove the active class from the current image
        images[i].classList.remove("active");

        // if the iterator is less than the total number of images
        // go to the next number, otherwise reset to 0
        i = i + 1 < images.length ? i + 1 : 0;

        // add the active class to the next image
        images[i].classList.add("active");
        
    }

    // instantiate the repeater
    let repeater;

    // when you hover over the image wrapper, start the reapeater
    // repeat every 500ms
    imageDeck.addEventListener("mouseover", (e) => {
        repeater = setInterval(cyclePhotos, 500);
    });

    // when you are no longer hovering, clear the repeater
    imageDeck.addEventListener("mouseout", (e) => {
        clearInterval(repeater);
    });
</script>

</html>

why warpping your code in resolved prop makes your sync code act like async code?

loop in side of the promise works like sync code for example


console.log('im working')
function proLoop(){
    return new Promise((resolve ,rejects)=>{
        for (let i = 0; i < 1000000000000; i++) {}
        console.log('loop is done')
    })
}

proLoop();

console.log('im working')

So even if we write is like promise it will get more time and freezes our code In other words it will works synchronically.

i find a solution but why it works?

so the solution is just warp your code as like resolved promise

like this

return Promise.resolve().then( ()=>{
    for (let i = 0; i < 1000000000000; i++) {}
    console.log('loop is done')
})

but why and how???

prevent default not working on form submission

trying to prevent default on form submission though it goes ahead and submits user input–
if I have the form onsubmit value to empty then the form prevents default.. is there solution to this?

Below is my form; on submit is empty as it prevents default when empty. though it should be going to generate as shown below…

              <form className='grid' onSubmit={}>
                <div className='flex'>
                  {/* <InputField
                    isRequired={true}
                    id='productNameField'
                    required={true}
                    className='border-solid border-2 border-gray-200 pl-3 w-full rounded-lg h-full'
                    type='text'
                    placeholder='Spotify'
                    label='Product Name'
                    onChange={onSetProductName}
                  /> */}

                  <div className=' relative '>
                    <label className='text-gray-700'>
                      Product Name
                      <span className='text-red-500 required-dot'>*</span>
                    </label>
                    <input
                      type='text'
                      required
                      className=' rounded-lg border-transparent flex-1 appearance-none border border-gray-400 w-full py-2 px-4 bg-white text-gray-700 placeholder-gray-400 shadow-sm text-base focus:outline-none focus:ring-2 focus:ring-accent1 focus:border-transparent'
                      placeholder='Spotify'
                      onChange={onSetProductName}
                    />
                  </div>
                </div>
                {/* <div className='flex pt-6'>
                  <InputField
                    id='productDescriptionField'
                    required={true}
                    className='border-solid border-2 border-gray-200 pl-3 w-full rounded-lg resize-none h-full p-1'
                    type='text'
                    placeholder='Spotify is a music service that lets you listen to music and share it with friends.'
                    label='Product Description'
                    maxRows={5}
                    onChange={onSetProductDescription}
                    multiline
                  />
                </div>
                <div className='flex pt-6'>
                  <InputField
                    id='platformField'
                    required={true}
                    className='border-solid border-2 border-gray-200 pl-3 w-full rounded-lg h-full'
                    type='text'
                    placeholder='Instagram'
                    label='Platform'
                    onChange={onSetPlatform}
                  />
                </div>
                <div className='flex pt-6'>
                  <InputField
                    id='audienceField'
                    required={true}
                    className='border-solid border-2 border-gray-200 pl-3 w-full rounded-lg h-full'
                    type='text'
                    placeholder='Teens'
                    label='Audience'
                    onChange={onSetAudience}
                  />
                </div> */}
                <div className='grid'>
                  <div className='grid grid-cols-2 pt-6'>
                    {pendingCreativeAd === true ? (
                      <div className='grid justify-start'>
                        <button
                          type='button'
                          disabled={true}
                          className='py-2 px-4 flex justify-center items-center bg-gray-600 text-white w-full transition ease-in duration-200 text-center text-base font-semibold rounded-lg '
                        >
                          1 sec.
                          <LoadingIcon height={21} width={21} />
                        </button>
                      </div>
                    ) : (
                      <div className='grid justify-start'>
                        <button
                          type='submit'
                          // onClick={generate}
                          className='py-2 px-4 flex justify-center items-center  bg-accent1 hover:bg-blue-800 focus:bg-accent1 text-white w-full transition ease-in duration-200 text-center text-base font-semibold shadow-md focus:outline-none rounded-lg  '
                        >
                          Generate
                        </button>
                      </div>
                    )}
                    <div className='grid justify-end'>
                      <button
                        type='button'
                        onClick={clearForm}
                        className='py-2 px-4 flex justify-center items-center  bg-orange-700 hover:bg-orange-800 text-white w-full transition ease-in duration-200 text-center text-base font-semibold shadow-md focus:outline-none focus:bg-orange-700  rounded-lg  '
                      >
                        Clear Form
                      </button>
                    </div>
                  </div>
                </div>
              </form>
 const generate = async (e) => {
    e.preventDefault();
    startGenAd(productName, productDescription, platform, audience);
    console.log('submitting generate');
  };

JavaScript Scroll Animation (ScrollMagic)

Have been watching some tutorials and testing out the ScrollMagic feature with GASP, yet this animation won’t work on my page (object is sticky). Pretty new to coding, so likely a simple solution to this. Thanks

const flightPath = {
    curviness: 1,
    autoRotate: true,
    values: [
        { x: 100, y: -30},
        { x: 300, y: 90},
    ]
}
const tweet = new TimelineLite();

tweet.add(
    TweenLite.to(".item", 1, {
        bezier: flightPath,
        ease: Power1.easeInOut
    })
);

HTML

<section> 
  <img class="item" src="images/paper.png" alt="img">
</section>


<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/ScrollMagic.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/plugins/animation.gsap.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/plugins/debug.addIndicators.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenLite.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TimelineLite.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/CSSPlugin.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/BezierPlugin.min.js" ></script>

<script> src="app.js"</script>   



CSS


.item {
    height: 60px;
    position: relative;
    top: 50%;
    left: 0;
}

Javascript Multiple Timelines visualizer and selector

Currently I have build this website which I would like to extend. The component I am trying to build takes as input a list of date arrays and visualizes them above an accurate timeline. The user should be able to select from the time steps on the master timeline so I can use the new date array for another component. I would love for the component to allow the user to use a double range slider which would capture all time steps in the range that all the layers have in common. I have other ideas but I want to find out if there is a library which would help me with such a component as I am using Vuetify at the moment and the options like Timemap.js or Timeline.js are not evidently applicable to my case it seems. Any suggestions are welcome, I am just trying to learn and build this. rough diagram of what I am trying to build

how to map through multiple images, after connecting to a third party api

I’ve managed to connect to an api, which returns images of dogs. However, I’m stuck on how to map more than one image, without repeating code. I essentially want to display a grid with(lets say 9) images, all with different dog images from this api.

At the moment, it displays one image with a json object mapped out underneath it.

App.js

import './App.css';
import './Dog.js';
import FetchAPI from './FetchAPI';



function DogApp() {

  return (
    <div className="DogApp">
     <FetchAPI />
    </div>
  );
}

export default DogApp;

FetchAPI.js

import React, { useState, useEffect } from 'react'

const FetchAPI = () => {

    const [data, setData] = useState([]);

    const apiGet = () => {
        const API_KEY = "";
        fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`)
            .then((response) => response.json())
            .then((json) => {
                console.log(json);
                setData(json);
            });
    };

    useEffect(() => {           //call data when pagee refreshes/initially loads 
        apiGet();
    }, []);


    return (

        <div>
            {data.map((item) => (
                <img src={item.url}></img>
            ))}

            My API
            <button onClick={apiGet}>Fetch API</button>
            <pre>{JSON.stringify(data, null, 2)}</pre>
            <br />


        </div>



    )
}

export default FetchAPI;

Mongodb: How to pass another stage inside $group?


Sample Data


Expected Output:

[
  {
    "_id": "healty",
    "doc_count": 2,
    "ingredients": {
      "Leaves": {
        "1.2g": 1,
        "1.5g": 1
      },
      "Spinach": {
        "12g": 1,
        "18g": 1
      }
    }
  },
  {
    "_id": "junk",
    "doc_count": 3,
    "ingredients": {
      "cheese": {
        "100g": 1,
        "120g": 2
      },
      "meat": {
        "50g": 1,
        "60g": 1,
        "70g": 1
      }
    }
  }
]

Aggregation Below: Playground1

db.collection.aggregate([
  {
    $group: {       
      "_id": "$type",  // grouping the document by "type" field
      "ingredients": {
        $push: "$$ROOT"  //want to run Playground2 aggrgtion in each of it
      },
      "doc_count": {
        $sum: 1        // total count
      }
    }
  }
])


After that,

I’ve also figured out an Another Step to convert the ingredients array after it: Playground2

But, this aggregation is for All the documents. I want to make Playground2 aggregation work for the ingredients field only in each group Object.

It’s similar to combining Playground1 & Playground2. How do I do this?

Border box around marker with Leaflet & OpenStreetMap

I customized the marker in Leaflet in order to change it’s color. I am using an SVG image for the marker. Unfortunately there is a border box around the marker. I would like to remove the border box. I am not sure what is causing the boarder box. Is it something I need to modify the SVG itself? Or a setting in Leaflet?

I am using the latest version of Mozilla Firefox to view the map.

Marker

ComponentDidUpdate is not called onclick of browser Back button

I’m developing a React application where the user should be logged off when he clicks on the browser back button from the dashboard.
I’m calling window.onpopstate event inside componentDidUpdate() method like below. But the code seems to work only one time. When I click on Browser’s Back button for the first time, it is working fine. And when I login again for the second time and try to click on the Browser back button, this time ComponentDidUpdate() is not even called.
This happens until I clear my browser cache. After clearing browser cache, again, only for the first time ComponentDidUpdate() is called on click of Browser Back button. Please help me with this. This is my first time with window event handlers. What am I doing wrong?
Do I need to write this functionality in any other lifecycle methods? Please suggest.

ComponentDidUpdate(prevState) {
  console.log("DID UPDATE CALLED");  // this works only for the first time.
  const location = window.location.href;
  if(location.includes('dashboard') { // I want this code to work only when the user is in dashboard
    window.onpopstate = (e) => {
      if (e.state) { 
        this.onSignOffClick();  // a function to display a popup asking for the user if he wants to logoff
      }
    };
    window.history.pushState({name: "BackButton"}, "back button clicked", location );
    window.history.pushState({name: "BackButton"}, "back button clicked", location );
  }
}

Basically, I want to display a popup asking for the user if he wants to logoff (i.e., trigger this.onSignOffClick) every time he clicks on the Browser back button.
Someone please help me. I’m struggling for a long time to achieve this.
Any idea or any advise would help.

Thanks in advance!

How can I call a function defined in an Angular component in a JavaScript file?

In a .ts file, I have the following code

export class SomeClass {
    .
    .
    .
    public someMethod() {
        ...
    }
}

I want to call this someMethod method in a .js file.

I tried

import { SomeClass } from '../../../../SomeClass';
.
.
.
SomeClass.someMethod();

but got the following error:

someMethod is not a function

Do I have to make the method static?

I prefer not because it calls other methods and I will have to make all of them static.

Can I create an instance of this class in the .js file?

Thanks!

i wanna get the max depth of a not-certain tree. the tree looks like below,how can i finish it

given a tree-structured data, get the max height of the tree. i wanna get the max depth of a not-certain tree. the tree looks like below:

{
      id: 1,
      label: 'label1',
      children: [{
        id: 3,
        label: 'label2',
        children: [{
          id: 4,
          label: 'label3'
        }, {
          id: 5,
          label: 'label4',
          disabled: true,
          children: [{
              id: 4,
              label: 'label3'
            }, {
              id: 5,
              label: 'label4',
              disabled: true
            }]
        }]
      }

Why do I have to specify this.___ for every variable in my class?

Currently with the code below I am getting the error Uncaught ReferenceError: a is not defined
The only way I have found to fix this is by putting this before the a in the print function. I was wondering if there was a way to avoid this because I think it makes the code messier and is probably unecessary. I know I have to use this in the constructor by the way although I thought that was only necessary when you had a parameter of the same name.

Class Example{
    a;
    constructor(a){
        //I know I have to put this here to specify which "a" variable
        a.this = a;
    }
    print(){
        return a;
    }
}
b = new Example("hi);
console.log(b.print());
    

HackerRank is not passing the code, on some test cases …need help here [closed]

my code is passing 20 out of 35 test cases, and I am not sure what fails it.
Would really appreciate assistance here, as the input is very large

function passwordCracker(pswrds, attempt) {
  let buildPswrd = [];
  let parsedAttempt = attempt;
  while (parsedAttempt.length > 0) {
    let parsedLength = parsedAttempt.length;
    for (let i = 0; i < pswrds.length; i++) {
      let pswrd = pswrds[i];
      let l = pswrd.length;
      if (parsedAttempt.slice(0, l) === pswrd) {
        buildPswrd.push(pswrd);
        parsedAttempt = parsedAttempt.slice(l);
        break;
      }
    }
    if (parsedLength === parsedAttempt.length) return 'WRONG PASSWORD';
  }
  let answer = buildPswrd.join(' ')
  console.log(answer);
  return answer;
}
//link to challenge 
//   https://www.hackerrank.com/challenges/password-cracker/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign

New to js, trying to make a simple To-Do list site [duplicate]

cannot for the life of me figure out why newTask is returning undefined instead of the input value from my form.

Heres my HTML code:

<!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>Document</title>
</head>
<body>
    <h1>Todo List!</h1>
    <form action="" id="addTask">
        <label for="newTask"></label>
        <input type="text" placeholder="Task" id = "newTask">
        <input type="submit" >
    </form>
    <ul id = "tdList">
        
    </ul>
    <script src="myTodo.js"></script>
</body>
</html>

and heres my Js:

const form = document.querySelector('#addTask');
const input = document.querySelector('#newTask');
const tdList = document.querySelector('#tdList');

form.addEventListener('submit', function(e) {
    e.preventDefault();
    const newTask = document.createElement('li');
    console.log(input.value);
    newTask.innerText = input.Value;
    input.value = '';
    tdList.appendChild(newTask);
});

Returning response in validation Express indicates error and continues the flow

I am validating through a middleware that the quantity of product required by the client is not greater than the quantity of product in stock.

The validation is correct, the message is displayed indicating that there is less stock than the user requires, but even if the message is displayed, the execution does not stop, it reaches the controller and saves the information.

This is my middleware:

let productHasStock =  async ( req, res, next ) => {
    try { 
        const details = req.body.detail;

        const product = await details.map( async detail => {
            let product = await Product.findById( detail._id );
 
            if (product.stock < detail.quantity) {
                console.log('stock error');
                return res.status(401).json({
                    msg: 'Stock error'
                })
            }
        })

        next();
    
    } catch (error) {
        res.status(401).json({
            msg: 'La peticiĆ³n es incorrecta'
        })
    }

}

const checkStock = async (id, quantity) => {

    let product = await Product.findById( id );
    return (quantity > product.stock) ? false : true;
};

module.exports = {
    productHasStock
}

In addition to this I get an error stating: Cannot set headers after they are sent to the client

error on console

I tried passing this logic to the controller but I get exactly the same errors so much so that it doesn’t stop executing like the error in the console.

Thanks for your help.