How do you make a function in JavaScript that displays 10 elements at a time with a button?

I am displaying data from a JSON file to a website using HTML. I want it to display the first 10 actors in the list and the movie they are in. Then I want the user to be able to press a button and be able to display the next 10, and another button to go back 10. I have been able to display the first 10 onload, I have an index on line 17 that counts how many rows I have added to “newContent” and once it reaches 10 it breaks the loop on line 36. But when I press the button on the page the index no longer works. It just goes past 10 without breaking till the loop goes through the entire JSON file.

var actors = [];


const xhr = new XMLHttpRequest(); //Gets the http request

xhr.onload = function () {
    if (xhr.status == 200) {
        var responseObject = JSON.parse(xhr.responseText);
        var newContent = '';

        var parameter = 0;
        var counter = 0;
    
    function table(parameter) {
        
        var index = 0;

        for (var i = parameter; i < responseObject.movies.length; i++) {
            for(var j=0; j < responseObject.movies[i].cast.length; j++){
                //Checking for duplicates
                if((actors.indexOf(responseObject.movies[i].cast[j]) == -1)) {
                    var letter = responseObject.movies[i].cast[j].charAt(0);
                        if((/[a-zA-Z]/).test(letter)) {
                            newContent += '<tr class="event">';
                            newContent += '<td>' + responseObject.movies[i].cast[j] + '</td>';
                            newContent += '<td>' + responseObject.movies[i].title + '</td>';
                            newContent += '<td>' + index + '</td>';
                            newContent += '</tr>';
                            index++;
                        }
                    }
                }
                counter++;

                if (index == 10) {   
                    break;
                }
            }
            return newContent;
        }
        document.getElementById('castNames').innerHTML = table(0);

        var showMoreBtn = document.getElementById('showMoreBtn');
        showMoreBtn.addEventListener('click', showMore, false);

        
        function showMore() {
            parameter = counter;
            return document.getElementById('castNames').innerHTML = table(parameter);
        }
        
    }
    

}


xhr.open('GET', "static/data/movies.json", true);
xhr.send();
table {
    width: 100%;
}

tr {
    border-bottom: 1px solid black;
}

th {
    color: black;
}

td {
    padding-top: 5px;
    color: black;
}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  
    <link rel="stylesheet" href="static/css/style.css">

  </head>
  <body>

    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
      <div class="container">
        <img src = "static/images/movieLogo.png" alt = "reel of film" width = "50px" height = auto style = "margin-right: 25px;">
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav">
          <li><a href="{{ url_for('index') }}" class="nav-link px-2 link-secondary">Home</a></li>
          <li><a href="{{ url_for('movies') }}" class="nav-link px-2 link-dark">Movies</a></li>
          <li><a href="{{ url_for('actors') }}" class="nav-link px-2 link-dark">Actors</a></li>
          </ul>
        </div>
      </div>
    </nav>
    
<div id = "buttonClass">
    <button id="showMoreBtn" class = "button" type="button">More</button>
    <!--<button id="viewLessBtn" class = "button" type="button">More</button>-->
</div>
    <table>
        <thead>
            <tr>
                <th class = "tableHeader">Name</td>
                <th class = "tableHeader">Movie</td>
            </tr>
        </thead>

        <tbody id="castNames">

        </tbody>
    </table> 
    
    <!--<p id="castNames"></p>-->

    <script src="{{ url_for('static', filename='actorDisplay.js') }}"></script>
    
        <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
    -->
  </body>
</html>

TLDR index in my JavaScript in the function table() is working when I load the page but not when I call the function with the button to see the next 10.

Parent SPFx React hooks web part open and close children’s windows. the child close hangs the parent

I have 2 applications that need to work together.
the parent has a list of jobs and the user may open them in the second (child) application as many jobs as he wants.
The code to open a child is:

 window.open(finalUrl, 'W' + event.data.ProjJob, "alwaysRaised=yes,titlebar=no,left=0,top=0,width=800,height=800");
    if (!inboxPopUpJobs.some(j => j.job === event.data.ProjJob)) {
      setInboxPopUpJobs(PopUpJobs => [...PopUpJobs, event.data.ProjJob]);
    }

When the child windows needs to refresh the parent and close, it sends a message using the ‘broadcast-channel’ library

The message is received OK by the parent with the job number so the window is intercepted by using:

 const w = window.open("", 'W' + job);

then to close it I use:

await w.close();

but now the parent window hangs, there is nothing showing in the console as error and there is no way to even refresh the browser (EDGE and Chrome)
I tried: w.opener.focus(); and window.focus(); but it is still hanging.

Does any one have a suggestion how to prevent the parent from hanging?
Thank you

JavaScript: Why when storing an array of an array in a variable, and pushing to that array a value, the original array increases in value too? [duplicate]

I wish I could find an answer to this question or anything that points me to the right direction. Assume below scenario

let x = [[1,2,3],[2,3,4]]
let y = x[0]
y.push(66)
console.log(x[0]) 
// [1,2,3,66]

How can I store in the “y” variable the value of x[0], add an element to Y and maintain X to its original roots?

Also why exactly does x[0] gain the new value? I’m no where doing x[0].push(value)

getting weird result when trying to copy an array using slice() on VS Code

I’m doing the “Chunky Monkey” practice on freeCodeCamp and I’m trying to debug the program on VS Code. But I’m getting a different result than the one I get when I try to run it on the fCC console. fCC returns the expected result for the case, the original array,, but I get a different output on VS Code. Here’s the code I made:

function chunkArrayInGroups(arr, size) {
    let groupArr = arr.slice(0);   // VS Code returns [4, 5, 6, 7]
    //console.log(groupArr)
    const groupTarget = Math.ceil(arr.length / size);
    console.log(groupTarget)
    let group = 1;
    console.log(group)
    let finalArr = [];
    for (let i = 0; i < size; i++) {  // iterates though the array 'size' times 
      if (group == groupTarget) {     // if for when we are on the last array to fill
        for (let j = 0; j < size; j++)  // for to iterate size amount of times to see if there is no undefined
        {
          if (groupArr[j] == undefined) { //if there is a undifined value, we'll make a smaller array for the last group 
            finalArr.push(groupArr.splice(0, j))
            console.log(finalArr)
          }
        }
      }
      finalArr.push(groupArr.splice(0, size))  // if we are not on the last group, we just splice the original value and push it 
      console.log(finalArr)
    } 
    return finalArr; // once loops end, we return the finalArray
  }
  
  chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4); 

Hope someone is able to help. Did I mess up something on VS Code? I only copied the exact code that I had.

How to save image from html2canvas

I’m using html2canvas to convert the div into an image. To save the image I have to go right-click and save it. Is it possible to download the image without right-clicking?

I tried like :

<a href="<canvas style='width: 1903px; height: 886px;' width='1903' height='886'></canvas>">DOWNLOAD</a>

but it doesnt work.

<div id="output">
   <canvas style="width: 1903px; height: 886px;" width="1903" height="886"></canvas>
</div>

Any help is appreciated

Bot crashed when trying to DM || Discord.js

I have a little problem. My bot, sometimes sends a message directly to the user, but if user turned off the messages from strangers it crashes, so my question is: Is there some If function that will check if you can send a message to this user? Or maybe some command, that will try to send a message to the user, but if it won’t work, bot will ignore it and go on. Tried “try” but it doesn’t work “DiscordAPIError: Cannot send messages to this user”

try{
   await client.users.cache.get(`${id}`).send('hello',{
      embed:embed1,
      });
   let messageEmbed1 = await client.users.cache.get(`${id}`).send({embeds: [embed1]})
   } catch (error) {
   console.error(error);

How to change the html inside of an element based on which element the mouse is hovered over

I am creating a hip hop timeline that allows users to hover over elements on the timeline to display a popup window on the page. The content of the popup window changes, depending on which timeline element is hovered over. Below is my part of my html and full JS code. I think I am close and believe I can use the event object in order to identify the element. Can someone help me with this? The pop up container that pops up when the user hovers on a timeline element is info__container.

<div class="container">
      <div class="hidden info__container">
        <div class="info__container--content">
          <!-- <h1>The Sugarhill Gang</h1>
          <img src="/img/sugarhill.jpeg" alt="Sugarhill Gang" id="sugarhill" />
          <p>
            This trio kick started the rap movement. Wonder Mike, Master Gee,
            and Big Bank Hank made up the group. Their release of The Sugarhill
            Gang album created an avenue for African Americans to enter the
            music industry. Popular hits from the album include Passion Play and
            the famous Rapper's Delight.
          </p> -->

          <!--
          <h1>Run-D.M.C.</h1>
          <img src="/img/runDMC.jpeg" alt="Run-D.M.C." id="rundmc" />
          <p>
            This trio kick started the rap movement. Wonder Mike, Master Gee, and
            Big Bank Hank made up the group. Their release of The Sugarhill Gang
            album created an avenue for African Americans to enter the music
            industry. Popular hits from the album include Passion Play and the
            famous Rapper's Delight.
          </p>-->
        </div>
      </div>
      <div class="timeline">
        <ul>
          <li>
            <div class="timeline--content--even" i="sn">
              <h1>1979</h1>
              <p>
                Hip Hop begins gaining traction in society. This was the first
                time that a rap album entered the top 40 on the Billboard Hot
                100 chart. This was due to Sugarhill Gang's album "Rappers
                Delight", which reached number 37 on the chart.
              </p>
            </div>
          </li>

          <li>
            <div class="timeline--content--even" id="ee">
              <h1>1988</h1>
              <p>
                N.W.A. releases their album "Straight Outta Compton", putting
                the West Coast on the map. This album was a turning point for
                rap and was sparked a lot of uproar and controversy.
              </p>
            </div>
          </li>
</div>

const containerContent = document.querySelector('.info__container--content');
const timelineContainer = document.querySelectorAll('.timeline--content--even');
const sideContent = document.querySelector('.info__container');

timelineContainer.forEach(item => {
    item.addEventListener('mouseover', function (e) {
        sideContent.classList.remove('hidden');
        if(e.target === ) {
            containerContent.innerHTML =  `
                <h1>The Sugarhill Gang</h1>
                <img src="/img/sugarhill.jpeg" alt="Sugarhill Gang" id="sugarhill" />
                <p>
                    This trio kick started the rap movement. Wonder Mike, Master Gee,
                    and Big Bank Hank made up the group. Their release of The Sugarhill
                    Gang album created an avenue for African Americans to enter the
                    music industry. Popular hits from the album include Passion Play and
                    the famous Rapper's Delight.
                </p>        
            `;
        };

        if(e.target === ) {
            containerContent.innerHTML =  `

                <h1>Run-D.M.C.</h1>
                <img src="/img/runDMC.jpeg" alt="Run-D.M.C." id="rundmc" />
                <p>
                This trio kick started the rap movement. Wonder Mike, Master Gee, and
                Big Bank Hank made up the group. Their release of The Sugarhill Gang
                album created an avenue for African Americans to enter the music
                industry. Popular hits from the album include Passion Play and the
                famous Rapper's Delight.
                </p>        
            `;
        }
    });       
});

how do i delete child element in nested Json Array and rename Id of child element and merge it to parent element?

I’ve JSON array which is returned after an edit success in react-redux-saga. The record I updated before and after successfull update comes together as an element of JSON array. So, I need to replace the old resort element with the newly updated resort values and also delete the old resort.

Here, in this example, I have updated resortId(id)=15, but my redux-saga returns both-old resort and the updated new resort,clubbed together in a single element in JSON array cuz in the this.props(cuz place part in this id=15 belongs to another saga store).

    resortafterupdate=[{
                "id": 5,
                "name": "The Ananta Udaipur",
                "address": "Village Bujhda,Tehsil Girwa",
                "placeId": 2,
                "city": "Udaipur",
                "state": "Rajasthan",
                "country": "India",
                "details": "string",
                "phone": "567890055"
            }, {
                "id": 10,
                "name": "Test",
                "address": "Raj Garden road111",
                "placeId": 4,
                "city": "Shillong",
                "state": "Meghalaya",
                "country": "India",
                "details": "afafas asdfasfas",
                "phone": "986289"
            }, {
                "id": 11,
                "name": "bbbbb",
                "address": "ggjgjgjh",
                "placeId": 1,
                "city": "Panjim",
                "state": "Goa",
                "country": "India",
                "details": "jjkhkhkhk",
                "phone": "89789789"
            }, {
                "id": 12,
                "name": "The Classic",
                "address": "chandni chowk",
                "placeId": 4,
                "city": "Shillong",
                "state": "Meghalaya",
                "country": "India",
                "details": "beverages",
                "phone": "687686868"
            }, {
                "id": 9,
                "name": "xyzzzz 56788998877666",
                "address": "111111223345566Raj Garden road111",
                "placeId": 2,
                "city": "Udaipur",
                "state": "Rajasthan",
                "country": "India",
                "details": "afafas asdfasfas",
                "phone": "11111111111"
            }, {
                "id": 13,
                "name": "Byculla Navi ln",
                "address": "Byculla Navi ln",
                "placeId": 3,
                "city": "Puducherry",
                "state": "Puducherry",
                "country": "India",
                "details": "beverages",
                "phone": "04409"
            }, {
                "id": 8,
                "name": "test address",
                "address": "Raj Garden road111",
                "placeId": 1,
                "city": "Panjim",
                "state": "Goa",
                "country": "India",
                "details": "afafas asdfasfas",
                "phone": "3253453434"
            }, {
                "id": 7,
                "name": "test name",
                "address": "test address",
                "placeId": 4,
                "city": "Shillong",
                "state": "Meghalaya",
                "country": "India",
                "details": "afafas asdfasfas",
                "phone": "9862897999"
            },
             {
                "resort": {
                    "id": 15,
                    "name": "AAA",
                    "address": "hjhgkjk",
                    "placeId": 4,
                    "city": "Shillong",
                    "state": "Meghalaya",
                    "country": "India",
                    "details": "jhkhkjhkjhkjh",
                    "phone": "98789797"
                },
                "id": 15,
                "name": "BBB",
                "address": "NewTown",
                "details": "jhkhkjhkjhkjh",
                "phone": "98789797",
                "place": {
                    "id": 3,
                    "city": "Puducherry",
                    "country": "India",
                    "state": "Puducherry"
                }
            }
        ]

How do I delete the child element resort with id=15 as this is old record before the update? And how do I rename the id of “place” to “placeId” and merge the inner parts – placeId,city,state and country to the outer part of the element – name=BBB and Id=15 and address”: “NewTown”,”details”: “jhkhkjhkjhkjh”,”phone”: “98789797” to something like this

    resortafterupdate=[{
                "id": 5,
                "name": "The Ananta Udaipur",
                "address": "Village Bujhda,Tehsil Girwa",
                "placeId": 2,
                "city": "Udaipur",
                "state": "Rajasthan",
                "country": "India",
                "details": "string",
                "phone": "567890055"
            }, {
                "id": 10,
                "name": "Test",
                "address": "Raj Garden road111",
                "placeId": 4,
                "city": "Shillong",
                "state": "Meghalaya",
                "country": "India",
                "details": "afafas asdfasfas",
                "phone": "986289"
            }, {
                "id": 11,
                "name": "bbbbb",
                "address": "ggjgjgjh",
                "placeId": 1,
                "city": "Panjim",
                "state": "Goa",
                "country": "India",
                "details": "jjkhkhkhk",
                "phone": "89789789"
            }, {
                "id": 12,
                "name": "The Classic",
                "address": "chandni chowk",
                "placeId": 4,
                "city": "Shillong",
                "state": "Meghalaya",
                "country": "India",
                "details": "beverages",
                "phone": "687686868"
            }, {
                "id": 9,
                "name": "xyzzzz 56788998877666",
                "address": "111111223345566Raj Garden road111",
                "placeId": 2,
                "city": "Udaipur",
                "state": "Rajasthan",
                "country": "India",
                "details": "afafas asdfasfas",
                "phone": "11111111111"
            }, {
                "id": 13,
                "name": "Byculla Navi ln",
                "address": "Byculla Navi ln",
                "placeId": 3,
                "city": "Puducherry",
                "state": "Puducherry",
                "country": "India",
                "details": "beverages",
                "phone": "04409"
            }, {
                "id": 8,
                "name": "test address",
                "address": "Raj Garden road111",
                "placeId": 1,
                "city": "Panjim",
                "state": "Goa",
                "country": "India",
                "details": "afafas asdfasfas",
                "phone": "3253453434"
            }, {
                "id": 7,
                "name": "test name",
                "address": "test address",
                "placeId": 4,
                "city": "Shillong",
                "state": "Meghalaya",
                "country": "India",
                "details": "afafas asdfasfas",
                "phone": "9862897999"
            },
             {
                "id": 15,
                "name": "AAA",
                "address": "hjhgkjk",
                "details": "jhkhkjhkjhkjh",
                "phone": "98789797",
                    "placeId": 3,
                    "city": "Puducherry",
                    "country": "India",
                    "state": "Puducherry"
                
            }
        ]

Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

I’m trying to create a sign up form with an input for a users address. The address input uses the google autocomplete address api.

I’d like to be able to keep it as a Formik field, so I can use Yup validation on it.

The address input component looks like

// Google.jsx
import React from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
/* global google */


class SearchBar extends React.Component {
  constructor(props) {
    super(props);
    this.autocompleteInput = React.createRef();
    this.autocomplete = null;
    this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
  }

  componentDidMount() {
    this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current,
        {"types": ["address"]});
    this.autocomplete.addListener('place_changed', this.handlePlaceChanged);
  }


  handlePlaceChanged(){
    const place = this.autocomplete.getPlace();
    console.log(place);

  }

  render() {
    return (
        <Field ref={this.autocompleteInput}  id="autocomplete" type="text" name="address" placeholder="" />
    );
  }
}


export default SearchBar;

And my Form component looks like:

import React from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import SearchBar from "./Google";


const LoginSchema = Yup.object().shape({
  fName: Yup.string().required("Please enter your first name"),
  address: Yup.string().required("invalid address"),
});

class Basic extends React.Component {
  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-lg-12">
            <Formik
              initialValues={{
                fName: "",
                postal: "",
              }}
              validationSchema={LoginSchema}
              onSubmit={(values) => {
                console.log(values);
                console.log("form submitted");
              }}
            >
              {({ touched, errors, isSubmitting, values }) =>
                !isSubmitting ? (
                  <div>
                    <div className="row mb-5">
                      <div className="col-lg-12 text-center">
                        <h1 className="mt-5">LoKnow Form</h1>
                      </div>
                    </div>

                    <Form>

                      <div className="form-group">
                        <label htmlFor="fName">First Name</label>
                        <Field
                          type="text"
                          name="fName"
                          className={`mt-2 form-control
                    ${touched.fName && errors.fName ? "is-invalid" : ""}`}
                        />

                        <ErrorMessage
                          component="div"
                          name="fName"
                          className="invalid-feedback"
                        />
                      </div>

                      <div className="form-group">
                        <label htmlFor="address">Address</label>

                        <Field name="address" component={SearchBar} placeholder="" />

                        <ErrorMessage
                          component="div"
                          name="address"
                          className="invalid-feedback"
                        />

                      </div>



                      <button
                        type="submit"
                        className="btn btn-primary btn-block mt-4"
                      >
                        Submit
                      </button>
                    </Form>
                  </div>
                ) : (
                  <div>
                    <h1 className="p-3 mt-5">Form Submitted</h1>

                    <div className="alert alert-success mt-3">
                      Thank for your connecting with us.
                    </div>
                  </div>
                )
              }
            </Formik>
          </div>
        </div>
      </div>
    );
  }
}

export default Basic;

This returns an error of “Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?”.

Which is coming from my address input component at: <Field ref={this.autocompleteInput} id="autocomplete" type="text" name="address" placeholder="" />

Everything else is working, I just need to get past this last hurdle and I’ll be good from here.

I will begin looking into the docs, but I’m unfortunately in a rush to get this done so I figured I’d try my luck here!

Any help is greatly appreciated! Thank you!

How to manage components across different pages

so for some background, I currently have a pretty complex application, using PHP, jQuery, and some angular. I have a page (a dashboard) which presents the client with numerous components, as seen in the image below.
dashboard layout

I am trying to create another page with similar functionality, that both reuses and re-implements many of the components. The issue I am having is I need to reuse all the components that are the same, as I am constantly making changes to them.

How should I go about this in PHP?
Should I have a main file page which includes PHP functions, each corresponding to a component, so in the pages I just need to call those functions? This is a conceptual question.

Enable cors for Chrome browser

I have a problem with enable cors. Browset blocked request despite I install and turn on addon Allow CORS: Access-Control-Allow-Origin form Chrome. I tried set different options but all the times request is blocked. Cors I tested here: https://webbrowsertools.com/test-cors/.
I make script with axios but effect is this same:

const onSubmit = data => {
      const headers = {
    'Access-Control-Allow-Origin': '*'
};
    axios.post('[url]', {
        'username': 'Hello123',
        'emailaddress': '[email protected]',
        'password': 'Test123@',
        'confirmpassword': 'Test123@'
    }, headers)
    .then(() => console.log('this works'))
};

What is wrong?

expand nav in mobile and tablet

Why is the menu bar not visible in tablet mode. I have to click on the colored part to see it. It works well in mobile mode but has problems in tablet mode. I checked everything but did not understand how the collapsible__content class does not work in tablet mode.

Now in tablet mode, the navigation is not visible and I have to click on the gray bar to make the menus appear, while in tablet mode, you do not need to click on the menu to be seen.

index.html

    <header>
      <nav class="nav collapsible">
        <a class="nav__brand" href="#">Gustoso</a>
        <svg class="icon icon--white nav__toggler">
          <use href="images/sprite.svg#menu"></use>
        </svg>
        <ul class="list nav__list collapsible__content">
          <li class="nav__item">
            <a href="#">Welcome<span class="between__nav">~</span></a>
          </li>
          <li class="nav__item">
            <a href="#">Menu<span class="between__nav">~</span></a>
          </li>
          <li class="nav__item">
            <a href="#">reservations<span class="between__nav">~</span></a>
          </li>
          <li class="nav__item">
            <a href="#">News<span class="between__nav">~</span></a>
          </li>
          <li class="nav__item">
            <a href="#">Contact</a>
          </li>
        </ul>
      </nav>
    </header>

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

style.css

.list {
  list-style-type: none;
  padding-left: 0;
}

/* Navigation Bar */
header {
  background: rgba(86, 83, 76, 0.5294117647058824);
}

.nav {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  align-items: center;
  padding: 0.6rem 1rem;
}

.nav__list {
  width: 100%;
  margin: 0;
}

.nav__item {
  padding: 0.9rem 0.2rem;
  border-bottom: 1px solid #826c6c;
}

.nav__item > a:hover {
  font-weight: bolder;
}

.nav__item > a {
  color: var(--color-heading);
  text-transform: uppercase;
  font-size: 1.7rem;
}

.nav__item > a span {
  display: none;
}

.between__nav {
  margin: auto 0.9rem;
  font-size: 1.4rem;
  font-weight: 400;
}

.nav__brand {
  font-family: scriptina, Arial, Helvetica, sans-serif;
  font-size: 3rem;
  letter-spacing: 9px;
  line-height: 24px;
  color: #ffffff;
  transform: translateY(-11px);
}

.nav__toggler {
  opacity: 0.5;
  cursor: pointer;
  transition: all 0.15s;
}

.nav.collapsible--expanded .nav__toggler {
  opacity: 1;
  box-shadow: 0 0 0 3px #666;
  border-radius: 5px;
  transform: rotate(-90deg);
}

@media screen and (min-width: 768px) {
  .nav__toggler {
    display: none;
  }

  .nav__list {
     max-height: 100%;
    opacity: 1;
    width: auto;
    display: flex;
    font-size: 1.6rem;
  }

  .nav__item {
    border: 0;
  }

  .nav__item > a span {
    display: inline-flex;
  }
}

/* Collapsibles */
.collapsible__content {
  max-height: 0;
  opacity: 0;
  overflow: hidden;
  transition: all 0.3s;
}

.collapsible--expanded .collapsible__content {
  max-height: 100vh;
  opacity: 1;
}

main.js

const collapsibles = document.querySelectorAll(".collapsible");
collapsibles.forEach((item) =>
  item.addEventListener("click", function () {
    this.classList.toggle("collapsible--expanded");
  })
);

Problem While animating an svg point using tranform translate X

I’m trying to make a simple animation using translate X on a segment of my svg (while hover on the element). This is my code:

<html>
<style>
  .big-dot:hover {
    transform: translateX(20px);
    animation-duration: 1s;
    transition: all 1.5s linear;
    display: inline-block;
  }
</style>

<body>
  <svg id="Component_31_4" data-name="Component 31 – 4" xmlns="http://www.w3.org/2000/svg" width="42.534"
    height="49.111" viewBox="0 0 42.534 49.111">

    <g id="icon_navigation_chevron_right_24px" data-name="icon/navigation/chevron_right_24px"
      transform="translate(0 8.696)">
      <rect id="Boundary" width="24" height="24" transform="translate(13.423 11.72)" fill="none" />
      <path id="_Color" data-name=" ↳Color" d="M3.957,0,2.371,1.81,17.634,16.86,2.733,31.7,3.957,33.72,20.794,16.86Z"
        transform="translate(-2.371)" fill="#181e41" />
    </g>
    <g id="Group_3463" data-name="Group 3463" transform="translate(-780.577 -5591.11)">
      <g class='big-dot' id="Component_3_29" data-name="Component 3 – 29"
        transform="translate(801.374 5626.535) rotate(-90)">
        <path id="Path_277" data-name="Path 277"
          d="M0,0A7.686,7.686,0,0,0,7.685-7.687,7.685,7.685,0,0,0,0-15.371,7.685,7.685,0,0,0-7.685-7.687,7.686,7.686,0,0,0,0,0"
          transform="translate(16.303 16.303) rotate(-45)" fill="#e05037" />
      </g>
      <g id="Component_3_30" data-name="Component 3 – 30" transform="translate(803.226 5640.222) rotate(180)">
        <path id="Path_277-2" data-name="Path 277"
          d="M-4.382-8.765a3.3,3.3,0,0,0,3.3-3.3,3.3,3.3,0,0,0-3.3-3.3,3.3,3.3,0,0,0-3.3,3.3,3.3,3.3,0,0,0,3.3,3.3"
          transform="translate(16.303 49.875) rotate(-45)" fill="#e05037" />
        <g id="Group_296" data-name="Group 296" transform="translate(9.908 6.811) rotate(-45)">
          <path id="Path_275" data-name="Path 275"
            d="M-1.325-2.649A2.769,2.769,0,0,0,1.445-5.419,2.77,2.77,0,0,0-1.325-8.188,2.77,2.77,0,0,0-4.094-5.419,2.769,2.769,0,0,0-1.325-2.649"
            fill="#377caa" />
        </g>
      </g>
    </g>
  </svg>
</body>

</html>

While hovering, the dot is doing a move on the Y axis instead and disappear. How Shall i tackle this? Also, is there a way I could use gsap to animate this considering this svg is inside a css class on a backround image ? Thanks

How do I make a typing animation?

I’ve been attempting to create a typing animation program that creates an animation of typing a word. Every period of time (1 second), it adds a letter to the output, seemingly “typing” the word out. Here is my code:

let input = document.querySelector("#input");
let text = document.querySelector("#text");
let run = document.querySelector("#run");
let str = input.value;

run.onclick = function() {
  text.innerText = "";
  str = input.value;
  let chars = [];
  for (let i = 0; i < str.length; i++) {
    chars[i] = str.charAt(i);
  }
  
  for (let i = 0; i < chars.length; i++) {
    setTimeout(function() {
      text.innerText += chars[i];
    }, 1000)
  }
}

How to get timezone abbreviation from given timestamp?

I’m running into an issue while testing two functions that convert ISO and Epoch timestamp to the client timezone. The tests are passing but I’m trying to modify them so we don’t have to keep changing them based on Daylight time.

I added a bit of code to obtain the timezone abbreviation using Date() and toLocaleTimeString() and it works, except it fails in the CI/CD pipeline as the server returns UTC time. Even though, I’m adding options to specifically set the zone to America/Chicago, the server doesn’t seem to recognize them.

describe('convertISO8601ToClientTimezone', () => {
  const timestamp = '2021-04-08T19:15:42.410506Z';
  const zoneAbbr = new Date(timestamp)
    .toLocaleTimeString('en-us', { timeZone: "America/Chicago", timeZoneName: 'short' })
    .split(' ')[2];

  it('should take ISO-8601 return date formatted string of local timezone offset accordingly', () => {
    expect(convertISO8601ToClientTimezone(timestamp)).toEqual(
      `April 8th 2021, 2:15:42 PM ${zoneAbbr}`
    );
  });
});

describe('convertEpochTimestampToClientTimezone', () => {
  const timestamp = 1617909517024179200; // epoch in nanoseconds
  const zoneAbbr = new Date(timestamp / 100000)
    .toLocaleTimeString('en-us', { timeZoneName: 'short' })
    .split(' ')[2];

  it('should take epoch timestamp and return date formatted string of local timezone offset accordingly', () => {
    expect(convertEpochTimestampToClientTimezone(timestamp)).toEqual(
      `April 8th 2021, 2:18:37 PM ${zoneAbbr}`
    );
  });
});

Is there a better way to get the timezone abbreviation for America/Chicago based on a given timestamp?

I’m also using the Moment library but I’m struggling to figure out how get the value needed from the mock fn. And actually, I’m not sure that would be the recommended approach here but I’m pretty new to Jest.