Gatsby, problem with javascript not loading until refreshing page

I am running into an issue with getting SimpleLightbox not loading for me until I refresh the page on my Gatsby site. I have a demo up where if you go from the “inspirations” page (https://effulgent-liger-a1d01e.netlify.app/inspiration) then click on an individual inspiration you will see by clicking on the photo in the gallery that it just opens the photo url and not the lightbox. Then if you refresh the page and click an image in the gallery it then loads the lightbox fine. I assume this is part of my Gatsby learning process, but stumped on this. Thanks for any help.

Here is my individual “inspiration” post file code.

import React from 'react'
import styled from 'styled-components'
import { GatsbyImage } from 'gatsby-plugin-image'
import SimpleLightbox from 'simple-lightbox'

import 'simple-lightbox/dist/simpleLightbox.min.css'

import Seo from "../components/seo"
import CTAOne from '../components/ctaOne'

const HeroSection = styled.section`
  height: 650px;
  position: relative;

  @media(min-width: 768px) {
    height: 825px;
  }

  .hero-image .gatsby-image-wrapper {
    width: 100%;
    height: 650px;
    object-fit: cover;
    object-position: center;

    @media(min-width: 768px) {
      height: 825px;
    }
  }

  .hero-content {
    position: absolute;
    bottom: 40px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1;
    text-align: center;
    width: calc(100% - 20px);
    max-width: 1160px;
    padding: 15px 0;
    background-color: var(--white-trans);

    .hero-border-top,
    .hero-border-bottom {
      height: 18px;
      width: 100%;
      border: 6px solid var(--white-trans);
    }

    .hero-border-top {
      margin-top: -33px;
    }

    .hero-border-bottom {
      margin-bottom: -33px;
    }

    h1 {
      margin-bottom: 0;
    }

    p {
      font-size: 21px;
      line-height: 1.2;
      width: 100%;
      max-width: 900px;
      margin: 25px auto 21px auto;
      padding-left: 10px;
      padding-right: 10px;

      @media(min-width: 768px) {
        font-size: 23px;
      }
    }
  }
`

const InspirationPostContainer = styled.section`
  margin-bottom: 90px;

  .inspiration-desc {
    max-width: 850px;
    margin: 90px auto 85px auto;
    text-align: center;
  }

  .inspiration-grid {
    column-count: 1;
    column-gap: 55px;

    @media(min-width: 640px) {
      column-count: 2;
    }

    @media(min-width: 992px) {
      column-count: 3;
    }
  }

  .item {
    margin: 0 0 40px;
    display: grid;
    grid-template-rows: 1fr auto;
    break-inside: avoid;
  }

  .item > img {
    grid-row: 1 / -1;
    grid-column: 1;
  }
`

function InspirationPost({ pageContext }) {
  const { inspiration } = pageContext

  if (typeof window !== `undefined`) {
    new SimpleLightbox({elements: '.inspiration-grid a'})
  }

  return (
    <>
      <HeroSection>
          <div className='hero-image'>
            <GatsbyImage image={inspiration.inspiration.projectFeaturedPhoto.gatsbyImage} alt={inspiration.inspiration.projectFeaturedPhoto.altText} />
          </div>
          <div className="hero-content">
            <div className='hero-border-top'></div>
            <h1>{inspiration.inspiration.projectTitle}</h1>
            <div className='hero-border-bottom'></div>
          </div>
      </HeroSection>
      <InspirationPostContainer>
        <div className="container">
          <div className='inspiration-desc'>{inspiration.inspiration.projectDescription}</div>
          <h2>Project Gallery</h2>
          <div className='inspiration-grid'>
            {inspiration.inspiration.projectGallery.map((node) => (
              <a href={`${node.mediaItemUrl}`} className='item' key={node.id}>
                <GatsbyImage image={node.gatsbyImage} alt={node.altText} />
              </a>
            ))}
          </div>
        </div>
      </InspirationPostContainer>
      <CTAOne />
    </>
  )
}

export default InspirationPost

how can I modify this regular expression so that it distinguishes between latin and russian letters in links and emails

At the moment my program looks like this:

let final = text;
  const divElement = document.createElement('div');
  // eslint-disable-next-line max-len
  const linkRegExp = /b(((http(s)?://)([w-]{1,32}(.|:)[w-]{1,32}))|([w-]{1,32}(@)[w-]{1,32}(.)[w-]{1,32})|([w-]{1,32}(.)[A-Za-z]{1,32}))b/gi;

  function replacer(url) {
    if (url.match(/S+@S+.S+/ig)) {
      const email = document.createElement('a');
      email.innerHTML = url;
      email.href = `mailto:${url}`;
      email.setAttribute('class', 'email');

      return `${email.outerHTML}`;
    }
    const link = document.createElement('span');
    link.innerHTML = url;
    link.setAttribute('class', 'link');
    link.setAttribute('style', 'color: blue; cursor: pointer');

    return `${link.outerHTML}`;
  }

  final = final.replace(RegExp(linkRegExp), replacer);

Unfortunately, replacing [w-] with [wА-Яа-я-] did not give positive results

How can I select a newly added Datatable.js row using jQuery.js?

I have a button that adds a row to a datatable when clicked. Is there a way I can select that new row specifically once it’s created?

dataTable = $("#table").DataTable({
    ...
})

$('button#addRow').off();
$('button#addRow').on('click', function () {
    dataTable.row
        .add({
            example: string,
        })
        .draw();
    
    /*
        This button is found within a row so I can select its current row like 
        this:
        var row = $(this).parents('tr');

        How can I select the newly added row?
    */

    var newRowSelector = ???
});

Linking JS message loop to HTML header

I have been trying to make a loop of messages that change very hour (One is visible at a time) I’m decent at HTML, but I’m pretty bad at JS. (Message should go in h3)

I tried to link my JS loop into a HTML text element, but I failed.

h3 = document.createElement("h3");
var messages = "Message 1", "Message 2", "Message 3", "Message 4", "Message 5", "Message 6";
var counter = 0;

function myLoop() {
  setTimeout(myLoop, 3, 600, 000);
  document.getElementById("Message")
  document.body.appendChild(h3);
}
myLoop();
<h3>
  <h3 id="Message"></h3>
</h3>

File object to base64 results in converting to base64 the entered file

I have this function for converting File objects to base64.

const convertBase64 = (file: File) => {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onloadend = () => {
      resolve(fileReader.result);
    };
    fileReader.onerror = error => {
      reject(error);
    };
  });
};

The function indeed converts the provided file to base64 string, but the provided file is converted as well to base64. I tried cloning the file before passing it to the readAsDataUrl function, but no success. My environment is Chrome 110.0.5481.77 in Ubuntu 22.04.

Any workaround on this?

Why does passing props cause it to be embed inside an object?

Is there a way to pass a prop without embedding it inside the object?

For instance, consider the parent component passing the “partners” data

const partners = [
  {
    name: "Test1",
  },
  {
    name: "Test2",
  },
  {
    name: "Test3",
  },
  {
    name: "Test4",
  },
];

const Partners: NextPage = () => {
  return (
    <>
      <PartnerPanel props={partners} />
    </>
  );
};

The child component

// incorrect type 
type PropsType = [
  {
    name: string;
  }
];

//correct type
type PropsType =  { props: { name: string; }[]; }


export const PartnerPanel: FC<PropsType> = (props): JSX.Element => {
  return <div>{props.props[0].name}</div>;
};

Why is it that the props are embedded inside another props, for instance, I have to do props.props[0].name to get the value? Instead of props[0].name

Wheel style animation using html, css and JS

I’m looking into creating a wheel animation widget similar to the one on this page https://csh.umn.edu/ (Explore your wellbeing section)? I think I can use Image Maps to link different sections to different pages/content and Javascript to load the content dynamically. But, I’m not sure how to animate the transition. Any help to get me started will be greatly appreciated.

Thanks.

What would be the easiest way to make my meter represent the number in the centre?

270 degree meter with number in the centre to represent the bar

Hi, I would like to make my bar around the outside represent the number in the middle – so when it is 0, the bar is entirely white (the colour underneath) it, and when it is 100 it looks as shown above. I have the image as a photoshop file and I am trying to represent it in html/css.

I have tried using the radial-gradient attribute, but struggled to get any of it to work. Here is the code I was using:

html:
<img id="BlueBoostMeter" src="ModularPieces/BlueBoostMeter.png">

css:

#BlueBoostMeter{
    position: absolute;
    width: 141px;
    height: 141px;
    top: 882px;
    left: 1761px;
}

#BlueBoostMeter::before{
    content: "";
    position: absolute;
    top:0;
    left:0;
    width: 100%;
    height: 100%;
    background-image: radial-gradient(circle at center, #4CAF50 0%, #4CAF50 50%, transparent 50%, transparent 100%);
    transform: rotate(-90deg);
    border-radius: 50%;
}

#BlueBoostMeter::after{
    content: "";
    position: absolute;
    top:0;
    left:0;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background-color: #fff;
    transform: rotate(calc(120deg - 90deg));
    transform-origin: center;

}

all help is appreciated 🙂

Is there an easy way to drilldown into a “datetime” data grouped column in Highcharts?

I have a simple column chart that has one very large series that contains unix timestamps (x) and their values (y).

I am grouping the data by “year” in plotOptions which works fine. However, I would like to be able to click on one of the grouped “year” columns and have it drilldown and group all the data by “month” for that year.

Is this possible to do without having to spend ages re-working the format of my “payments” array to include hidden series like they do in the API demo?

API Demo: https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/column-drilldown

const payments = [
    {1547541553000, 56},
    {1547546525000, 32},
    {1548011538000, 10},
    {1548344454000, 91},
    etc... 
]

plotOptions: {
    series: {
        dataGrouping: {
            enabled: true,
            forced: true,
            units: [['year', null]]
        }
    }
},
series: [{
    type: 'column',
    data: payments
}]

Access to XMLHttpRequest at has been blocked my cors policy

Here’s the full error:

Access to XMLHttpRequest at 'http://localhost:3000/assets/get' from origin 'http://192.168.1.100:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

code:

const response = axios.get(`${apiUrl}/assets/get`)

What can I do to fix this?
this issue also exists
I m using react.js using npx create-react-app

Setting a property of Object.prototype with assignment versus with defineProperty in Javascript

I have written a function in Javascript that removes the values that are undefined.

export const removeUndefinedValues: (obj: Record<PropertyKey, any>) => Record<PropertyKey, any> = (obj: Record<PropertyKey, any>) => {
    if (obj) {
        Object.keys(obj).forEach((key: PropertyKey) => {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                if (obj[key] === undefined) {
                    console.log(`Removing property ${key.toString()} with value ${obj[key]}`)
                    delete obj[key]
                }

            }
        })
    }
    return obj
}

I added this to the object prototype with

Object.prototype.removeUndefinedValues = function () {
    return removeUndefinedValues(this)
}

This seems to work, but as soon as I use it in a large code base it breaks because some things in the package browserslist become undefined. I solved this by using the following code instead.

Object.defineProperty(Object.prototype, 'removeUndefinedValues', {
    value: function () {
        return removeUndefinedValues(this);
    },
    enumerable: false
});

However, I do not understand what is the difference. Why does the second code work and the first not?

Why would js function not trigger on button click?

I’m trying to follow this guide and I’m having a bit of an issue I can’t figure out how to fix.

Basically in PassKeys.html you have these 2 following bits of code:

<button class="btn btn-success" onclick='start()'>Add Key</button>
function start(){
        $("#modal-title").html("Enter a token name")
        $("#modal-body").html(`<p>Please enter a name for your new token</p>
                                <input type="text" placeholder="e.g Laptop, PC" id="key_name" class="form-control"/><br/>
                                <div id="res"></div>
                                `)
        $("#actionBtn").remove();
        $("#modal-footer").prepend(`<button id='actionBtn' class='btn btn-success' onclick="begin_reg()">Start</button>`)
        $("#popUpModal").modal('show')
    }

Now I’m no JavaScript expert but I would wager that when I click that button (which I can see in my webpage) a function should run that activates a modal.

In the example provided by the guide things do work exactly that way, but in my application it doesn’t seem to, and the code itself is exactly the same.

What could be the cause of that?

Nextjs environment variables seem to be undefined

After creating a new next.js project with npx create-next-app@latest and adding some environment variables on .env.local file I get this error when i run the server.

"Failed to load env from .env.local TypeError: Cannot read properties of undefined (reading 'split')"

I tried 3 times to create a nextjs project and it was always happening (OS Windows 11)

Stopping JavaScript from opening windows challenge

We are learning how to use JavaScript to open a new browser window. One of my students went above and beyond to open x number of windows of Rick Astley’s Never Gonna Give You Up on YouTube.
My challenge to the class after that was to develop a code in JS that would prevent these windows from opening. Rules are that they can’t alter the original code.

I wanted to see what suggestions stackoverflow had. Here are images of the html and JS.
HTML codeJS code

Some ideas the students had were using the .open or .close methods.

How to make Angular parent FormGroup invalid until all nested FormGroups are valid

I have a FormGroup containing nested FormGroups. I want to put a validator on the child FormGroup using the code below. However, I want to disable the submit button if the entire parent form group is invalid. If any of the children are invalid, it should be invalid until all children are valid. But this is not happening on initial load. It only happens if I touch any of the child input elements.

stackblitz link

user-registration.component.ts (parent component). First name should be required

 .....
  this.userForm = this.fb.group({
  basicInfo: this.fb.group({
    firstName: [],
    lastName: [],
    email: [],
    age: []
  }),
  .....

basic-info.component.ts

  ngAfterViewInit(){
    this.form.get('firstName').setValidators(Validators.required)
    this.form.updateValueAndValidity()
  }

basic-info.component.html
enter image description here

Parent form always returns true on initial load. The submit button should be disabled
Parent form always returns true on initial load