Uncaught TypeError: Cannot read properties of undefined (reading ‘classList’) while trying to get the images in a correct order

Hello!
first, I know the question title seems like a duplicate but, it’s not.

I’m a beginner at Javascript and I’m trying to build a portfolio section that shows a couple of projects, if you click on an icon it will show you the project’s picture in a bigger way. Anyway I wrote a couple of js lines but, I keep getting this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'classList')
    at changeImage (index.js:168:19)
    at HTMLSpanElement.<anonymous> (index.js:139:9)

The first image is showing and nothing wrong with it, but the other pictures, show it in a strange order and some of the pictures don’t even show!
I tried several solutions including getting the items using getElementByClassName and so on.
If you can help me I would appreciate it and tell me how it can be done!

HTML:

<section class="portfolio section" id="portfolio">
    <div class="modal">
        <div class="modal-overlay"></div>
        <div class="slider-wrap">
            <div class="prev-btn navigation">
                <i class="uil uil-angle-left-b"></i>
            </div>
            <div class="images">
                <img class="showImage" src="./assets/images/port1.jpg" alt="">
                <img src="./assets/images/port2.png" alt="">
                <img src="./assets/images/port3.jpg" alt="">
                <img src="./assets/images/port4.png" alt="">
                <img src="./assets/images/port5.png" alt="">
                <img src="./assets/images/port6.jpg" alt="">
            </div>
            <div class="next-btn navigation">
                <i class="uil uil-angle-right-b"></i>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="portfolio-header">
            <div class="portfolio-title">
                <h3 class="sub-heading">Portfolio</h3>
                <h1 class="heading">Latest projects</h1>
            </div>
            <div class="filter-btns">
                <button class="filter-btn" data-filter="all">All</button>
                <button class="filter-btn" data-filter=".product">Product</button>
                <button class="filter-btn" data-filter=".interaction">Interacting</button>
                <button class="filter-btn" data-filter=".webapps">Web apps</button>
            </div>
        </div>
        <div class="portfolio-gallery">
            <div class="mix prt-card interaction">
                <div class="prt-image">
                    <img src="./assets/images/port1.jpg">
                    <div class="prt-overlay">
                        <span class="prt-icon zoom-icon" style="--i: 0s">
                            <i class="uil uil-search-plus"></i>
                        </span>
                        <a href="#" class="prt-icon zoom-icon" style="--i: .15s">
                            <i class="uil uil-link"></i>
                        </a>
                    </div>
                </div>
                <div class="prt-desc">
                    <h3>Olido interaction</h3>
                    <a href="#" class="btn secondary-btn sm">Read more</a>
                </div>
            </div>
            <div class="mix prt-card webapps">
                <div class="prt-image">
                    <img src="./assets/images/port2.png">
                    <div class="prt-overlay">
                        <span class="prt-icon zoom-icon" style="--i: 0s">
                            <i class="uil uil-search-plus"></i>
                        </span>
                        <a href="#" class="prt-icon zoom-icon" style="--i: .15s">
                            <i class="uil uil-link"></i>
                        </a>
                    </div>
                </div>
                <div class="prt-desc">
                    <h3>Olido interaction</h3>
                    <a href="#" class="btn secondary-btn sm">Read more</a>
                </div>
            </div>
            <div class="mix prt-card webapps">
                <div class="prt-image">
                    <img src="./assets/images/port3.jpg">
                    <div class="prt-overlay">
                        <span class="prt-icon zoom-icon" style="--i: 0s">
                            <i class="uil uil-search-plus"></i>
                        </span>
                        <a href="#" class="prt-icon zoom-icon" style="--i: .15s">
                            <i class="uil uil-link"></i>
                        </a>
                    </div>
                </div>
                <div class="prt-desc">
                    <h3>Olido interaction</h3>
                    <a href="#" class="btn secondary-btn sm">Read more</a>
                </div>
            </div>
            <div class="mix prt-card product">
                <div class="prt-image">
                    <img src="./assets/images/port4.png">
                    <div class="prt-overlay">
                        <span class="prt-icon zoom-icon" style="--i: 0s">
                            <i class="uil uil-search-plus"></i>
                        </span>
                        <a href="#" class="prt-icon zoom-icon" style="--i: .15s">
                            <i class="uil uil-link"></i>
                        </a>
                    </div>
                </div>
                <div class="prt-desc">
                    <h3>Olido interaction</h3>
                    <a href="#" class="btn secondary-btn sm">Read more</a>
                </div>
            </div>
            <div class="mix prt-card interaction">
                <div class="prt-image">
                    <img src="./assets/images/port5.png">
                    <div class="prt-overlay">
                        <span class="prt-icon zoom-icon" style="--i: 0s">
                            <i class="uil uil-search-plus"></i>
                        </span>
                        <a href="#" class="prt-icon zoom-icon" style="--i: .15s">
                            <i class="uil uil-link"></i>
                        </a>
                    </div>
                </div>
                <div class="prt-desc">
                    <h3>Olido interaction</h3>
                    <a href="#" class="btn secondary-btn sm">Read more</a>
                </div>
            </div>
            <div class="mix prt-card webapps">
                <div class="prt-image">
                    <img src="./assets/images/port6.jpg">
                    <div class="prt-overlay">
                        <span class="prt-icon zoom-icon" style="--i: 0s">
                            <i class="uil uil-search-plus"></i>
                        </span>
                        <a href="#" class="prt-icon zoom-icon" style="--i: .15s">
                            <i class="uil uil-link"></i>
                        </a>
                    </div>
                </div>
                <div class="prt-desc">
                    <h3>Olido interaction</h3>
                    <a href="#" class="btn secondary-btn sm">Read more</a>
                </div>
            </div>
        </div>
    </div>
</section>

And here is the Javascript code:

const prt_section = document.querySelector(".portfolio");
const zoom_icon = document.querySelectorAll(".zoom-icon");
const modal_overlay = document.querySelector('.modal-overlay');
const images = document.querySelectorAll(".images img");

let currentIndex = 0;

zoom_icon.forEach((icn, i) =>
    icn.addEventListener("click", () => {
        prt_section.classList.add("open");
        document.body.classList.add("stopScrolling");
        currentIndex = i;
        changeImage(currentIndex);
    })
);

modal_overlay.addEventListener("click", () => {
    prt_section.classList.remove("open");
    document.body.classList.remove("stopScrolling");
});

function changeImage(index) {
    images.forEach((img) => img.classList.remove("showImage"));
    images[index].classList.add("showImage");
}

NOTE: When I navigate throughout the images with the mixer there is nothing wrong and it’s showing me all the images in the correct order.

Here is the mixer js code if you’re interested:

const prev_btn = document.querySelector(".prev-btn");
const next_btn = document.querySelector(".next-btn");

let mixer = mixitup(".portfolio-gallery", {
    selectors: {
        target: ".prt-card",
    },
    animation: {
        duration: 500,
    },
});

prev_btn.addEventListener("click", () => {
    if (currentIndex === 0) {
        currentIndex = 5; //NOTE: (5) is the number of the last image.
    } else {
        currentIndex--;
    }
    changeImage(currentIndex);
});

next_btn.addEventListener("click", () => {
    if (currentIndex === 5) {
        currentIndex = 0;
    } else {
        currentIndex++;
    }
    changeImage(currentIndex);
});

Nuxt js serve dev does not load when accessed remotely from another device

Nuxt js serve dev does not load when accessed remotely from another device.

Locally it works perfectly.

However, when I access the tablet, the nuxt address is running. An infinite load is shown.

server: {
    host: '0',
    port: '3030',
    https: {
      key: fs.readFileSync(path.resolve(__dirname, 'server.key')),
      cert: fs.readFileSync(path.resolve(__dirname, 'server.crt'))
    }
  }

Tried with and without https and the scenario is the same.

This error is shown after a long time of loading.

https://10.0.0.108:3030/_nuxt/commons/app.js
net::ERR_CONTENT_LENGTH_MISMATCH 200

Someone could help. I am very grateful for the attention of the community.
Strong hug

how to change the border-color of div onclick of a button

Okay! I want to change the border-color of the after the btn-success button is clicked.
SO if the button is clicked, the border of the .data-table will be red.

<div class="d-flex justify-content-center">
  <button class="btn-success px-2 py-1 action-success" onclick="document.getElementById('data-table').style.border-color = '#009b10'" style="border-radius:1rem"><i class="fa-solid fa-check"></i></button>
</div>

<table>
  <tr>
    <th>UPI</th>
    <th>DIAGNOSIS</th>
    <th>ITEMS</th>
    <th>ACTION</th>
    <th>ACTION BY</th>
    <th>CLINIC</th>
    <th>DATE</th>
  </tr>
  <tr class="data-table">
    <td>U6789876</td>
    <td>MALARIA</td>
    <td>Cathetar</td>
    <td>DELETE</td>
    <td>Nurse Duro</td>
    <td>Ibadan Clinic</td>
    <td>21-09-22</td>
  </tr>
</table>

PDFJS Viewer on page render event

I’m having an issue with FabricJS, i’m loading canvases per page on pagesloaded
, but when i scroll bottom or top the pages starts rendering again and the fabricJS canvases will disappear..

is there anyway to execute a function when the after the rendering is complete?

I’m using PFJS Viewer and FarbicJS here’s my code:

eventBus.on("pagesloaded", function () {
  //  this is here 2
  const tyter = ()=>{
    $(".spread .page").each(function () {
      $(this).append("<div class='canvasArea'><canvas></canvas></div>");
    })
    $(".canvasArea canvas").each(function () {
      let target = $(this).closest(".page").attr("data-page-number");
      $(this).attr("id", target);
      var canvas = this.__canvas = new fabric.Canvas(target);
      // create a rect object
      var deleteIcon = "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg version='1.1' id='Ebene_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='595.275px' height='595.275px' viewBox='200 215 230 470' xml:space='preserve'%3E%3Ccircle style='fill:%23F44336;' cx='299.76' cy='439.067' r='218.516'/%3E%3Cg%3E%3Crect x='267.162' y='307.978' transform='matrix(0.7071 -0.7071 0.7071 0.7071 -222.6202 340.6915)' style='fill:white;' width='65.545' height='262.18'/%3E%3Crect x='266.988' y='308.153' transform='matrix(0.7071 0.7071 -0.7071 0.7071 398.3889 -83.3116)' style='fill:white;' width='65.544' height='262.179'/%3E%3C/g%3E%3C/svg%3E";

      var img = document.createElement('img');
      img.src = deleteIcon;

      fabric.Object.prototype.transparentCorners = false;
      fabric.Object.prototype.cornerColor = 'blue';
      fabric.Object.prototype.cornerStyle = 'circle';

      function Add() {
        var rect = new fabric.Rect({
          left: 100,
          top: 50,
          fill: 'yellow',
          width: 200,
          height: 100,
          objectCaching: false,
          stroke: 'lightgreen',
          strokeWidth: 4,
        });

        canvas.add(rect);
        canvas.setActiveObject(rect);
      }

      fabric.Object.prototype.controls.deleteControl = new fabric.Control({
        x: 0.5,
        y: -0.5,
        offsetY: 16,
        cursorStyle: 'pointer',
        mouseUpHandler: deleteObject,
        render: renderIcon,
        cornerSize: 24
      });

      Add();

      function deleteObject(eventData, transform) {
        var target = transform.target;
        var canvas = target.canvas;
        canvas.remove(target);
        canvas.requestRenderAll();
      }

      function renderIcon(ctx, left, top, styleOverride, fabricObject) {
        var size = this.cornerSize;
        ctx.save();
        ctx.translate(left, top);
        ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle));
        ctx.drawImage(img, -size / 2, -size / 2, size, size);
        ctx.restore();
      }
      // canvas.setWidth(originalWidth * canvas.getZoom());
      // canvas.setHeight(originalHeight * canvas.getZoom());
    })
  }
  tyter()
});

Vue.js axios delete request is deleting but table won’t reset

I am having trouble with axios delete request. I get the following errors when I click the delete button

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'isExpanded')"

and

TypeError: Cannot read properties of undefined (reading 'isExpanded')

The data gets deleted but only after I refresh the browser.
Please let me know what I am missing in my deleteNetworkGroup method? I included the axios get request

async getNetworks(audId) 
  {
      try
      {
          const response = await this.axios.get("/s/audiences/network-groups?audId=" + audId);

          if (!this.networkGroups[audId])
          {
              this.$set(this.networkGroups, audId, {});
              this.$set(this.networkGroups[audId], 'isExpanded', false);
          }

          this.$set(this.networkGroups[audId], 'data', response.data ? response.data.data : []);
      }
      catch (error)
      {
          if (error.message && error.message.includes("404"))
          {
              if (!this.networkGroups[audId])
              {
                  this.$set(this.networkGroups, audId, {});
                  this.$set(this.networkGroups[audId], 'isExpanded', false);
              }

              this.$set(this.networkGroups[audId], 'data', []);
          }
          else
          {
              console.log(error.message);
          }
      }

  },


deleteNetworkGroup(id, index) 
  {

      axios.delete(projConfig.apiRoot + '/s/audiences/network-groups/' + id)
          .then(response => 
          {
              this.networkGroups.splice(index, 1)
                  .push(response.data.data);
          })
          .catch((error) => 
          {
              console.log(error);
          });
  },
<button type="button" class="delete_btn">
  <div class="trash_icon" @click="deleteNetworkGroup(networkGroup.id)">
   <font-awesome-icon icon="trash" />
  </div>
</button>

Error when trying to contact MangoDB server inside a vue 3 component

I’m doing a small hobby project for learning how to connect and read information from a database. Have done it with a local host JSON server, but want to take it a step further. I’m trying to connect to a MongoDB server inside of a Vue 3 component. The end goal is to read user login credentials from a database and compare it to input from a form. But first, I’m trying to get some simple information to work with to learn the basic concepts. This code list the databases I have in my cluster and works fine when I run it through an index.js file with the node terminal (Except the fake connection string).

  const {
        MongoClient
    } = require('mongodb');
    
    async function main() {
        const uriTest = "mongodb+srv://notRealUser:[email protected]/database?authSource=admin&retryWrites=true&w=majority"
        const client = new MongoClient(uriTest);
        try {
            await client.connect();
            await listDatabases(client);
            console.log("Connected correctly to server");
        } catch (e) {
            console.error(e);
        } finally {
            await client.close();
        }
    }
    
    main().catch(console.error);
    
    async function listDatabases(clients) {
        const databasesList = await clients.db().admin().listDatabases();
        databasesList.databases.forEach(db => console.log(`${db.name}`));
    }

But whenever I want to run it in my Vue 3 application I get a long error. I get about 27 errors mentioning something similar to this:

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
    - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "stream": false }

I searched the internet for an answer and someone mentioned that this could be because of “web pack 5”. I would really like to learn how to solve this for a Vue project. Is it a better way to approach this with MongoDB and Vue3? If I’m doing this all wrong please lecture me. Thank you for reading. 🙂

How can I declare a state and initialize it to 1 in App.js and then pull that state and increment/decrement it in another component?

I have App.js and epubreader.js. How can I initialize the state pageNum and set it to 1 in App.js and then pull it into the epubreader.js and set the state by incrementing or decrementing by 1? My problem right now is if I create the state pageNum in epubreader.js everytime the epubreader.js gets called, it resets the pageNum to 1. However, I want the pageNum only to be set to 1 when the application is ran.

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      fullscreen: true,
      location:
        storage && storage.getItem('epub-location')
          ? storage.getItem('epub-location')
          : 2,
      localFile: null,
      localName: null,
      largeText: false,
      pageNum: 1
    }
    this.rendition = null
  }
class EBookReader extends PureComponent {
  constructor(props) {
    super(props)
    this.readerRef = React.createRef()
    this.state = {
      expandedToc: false,
      toc: false,
    }

    
  }
  toggleToc = () => {
    this.setState({
      expandedToc: !this.state.expandedToc
    })
  }


  next = () => {
    //Sets page num + 1
    console.log(this.state.pageNum)
      this.setState({
      pageNum: this.state.pageNum + 1

    })
    const node = this.readerRef.current
    node.nextPage()
  }

  prev = () => {
    //Sets page num - 1
        this.setState({
      pageNum: this.state.pageNum - 1

    })
    console.log(this.state.pageNum)
    const node = this.readerRef.current
    node.prevPage()
  }

get max value from inside list of JSON objects

I have a list of JSON objects as below:

const data = [
  {
    "ID": 2131321,
    "firstName": "john",
    "lastName": "Doe",
    "lastLoginInSeconds": "324762"
  },
  {
    "ID": 2134321,
    "firstName": "john1",
    "lastName": "Doe1",
    "lastLoginInSeconds": "32232"
  },
  {
    "ID": 21314321,
    "firstName": "john2",
    "lastName": "Doe2",
    "lastLoginInSeconds": "328762"
  },
  {},
  {},
  {}
]

I need to get the max value of lastLoginInSeconds out of the given list of objects.

How to sort JSX elements from JSON values

What I Want to Do:

I want to render a list of elements using .map, then sort by most recent on top. I’ve tried adding .sort and .filter before rendering the element, but it doesn’t seem to be working. I’ve done some quick Google searches, but came across posts which don’t seem relevant to what i’m trying to do. (or it’s just me).

I want to sort by date, with the most recent on top.

Render Component:

import React from "react";
import TransactionEntry from "./TransactionEntry";

function Transactions({ transactionList }) {
  return (
    <div className="flex flex-col items-start justify-start w-full h-[520px] overflow-auto gap-3 no-scrollbar">
      {transactionList.map((transaction) => {
        return (
          <TransactionEntry
            id={transaction.id}
            retailer={transaction.retailer}
            category={transaction.category}
            price={transaction.price}
          />
        );
      })}
    </div>
  );
}

export default Transactions;

Data Structure:

[
    {
        "id": "ts001",
        "category": "Category",
        "retailer": "Retailer",
        "price": 1.99,
        "dateAdded": "04/02/01"
    },
    {
        "id": "ts002",
        "category": "Category",
        "retailer": "Retailer",
        "price": 13.99,
        "dateAdded": "04/02/04"
    },
    {
        "id": "ts003",
        "category": "Category",
        "retailer": "Retailer",
        "price": 119.99,
        "dateAdded": "04/02/09"
    }
]

How to make a framework API available globally on Node

I have a web development framework which I use on personal backend projects. All web apps revolve around my framework and the API is quite big so importing it in each file becomes tiring and repetitive.

The solution I came up with is using this code in my program main/entry point

Object.assign(global, require("@mycompany/myframework"));

Now I’m able to access all classes, constants and functions without importing them in each file.

The only problem is that my framework is written in TypeScript but my IDE is not reconinging the types globally, so after using any of my framework class, the editor/IDE will report that the API has not been imported.

Do you have a complete solution for this problem?

Turning an unordered list Table of Contents into a dropdown menu with JS/jQuery/CSS

I have an automatically generated table of contents that is an unordered list:

<ul class="elementor-toc__list-wrapper"><li class="elementor-toc__list-item"><div class="elementor-toc__list-item-text-wrapper"><i class=""></i><a href="#elementor-toc__heading-anchor-0" class="elementor-toc__list-item-text elementor-toc__top-level elementor-item-active">How AP Exams Are Scored</a></div></li><li class="elementor-toc__list-item"><div class="elementor-toc__list-item-text-wrapper"><i class=""></i><a href="#elementor-toc__heading-anchor-1" class="elementor-toc__list-item-text elementor-toc__top-level">What Are AP Scores Used for?</a></div></li><li class="elementor-toc__list-item"><div class="elementor-toc__list-item-text-wrapper"><i class=""></i><a href="#elementor-toc__heading-anchor-2" class="elementor-toc__list-item-text elementor-toc__top-level">What is Advanced Placement® and Credit?</a></div></li><li class="elementor-toc__list-item"><div class="elementor-toc__list-item-text-wrapper"><i class=""></i><a href="#elementor-toc__heading-anchor-3" class="elementor-toc__list-item-text elementor-toc__top-level">What AP Exam Scores Do Colleges And Universities Accept?</a></div></li><li class="elementor-toc__list-item"><div class="elementor-toc__list-item-text-wrapper"><i class=""></i><a href="#elementor-toc__heading-anchor-4" class="elementor-toc__list-item-text elementor-toc__top-level">AP Exam Score Distribution</a></div></li><li class="elementor-toc__list-item"><div class="elementor-toc__list-item-text-wrapper"><i class=""></i><a href="#elementor-toc__heading-anchor-5" class="elementor-toc__list-item-text elementor-toc__top-level">Frequently Answered Questions (FAQs)</a></div></li></ul>

I want this list to turn into a dropdown on mobile (below 768px). I want to either use jQuery on pageload to generate a dropdown menu (<option…) based off of this ul li, and then show/hide accordingly on mobile/desktop,

Or if possible I want to turn it into a dropdown menu with just CSS.

This is the page where you can see what I’m doing live, it’s currently a little buggy on mobile: https://collegeprep.uworld.com/ap/test-pillar-page-for-optimization/

the code I’m using that needs to be improved (keep in mind I’m using WP rocket that defers JS, and delays JS execution, which I’m trying to work around):

<script type="text/javascript">
// Table of Contents (ToC) code - new April 19 2022
document.addEventListener("DOMContentLoaded", function(event) { 
    // console.log("document ready");
    
    runWhenJqueryIsLoaded();

    function runWhenJqueryIsLoaded() {
        if( window.jQuery ) {
            jQuery(window).on("resize", function (e) {
                checkScreenSize();
            });

            // Table of Contents (ToC) code
            function convertTOCtoDropdown() {
                
                //first, store original non-mobile TOC so we can reverse back to it
                window.originalTOC = jQuery("#TOC .elementor-toc__list-wrapper");
                jQuery(function() {
                    jQuery("#TOC ul.elementor-toc__list-wrapper").each(function() {
                        var $select = jQuery("<select />");
                        
                        jQuery(this).find("a").each(function() {
                            var $option = jQuery("<option />");
                            $option.attr("value", jQuery(this).attr("href")).html(jQuery(this).html());
                            $select.append($option);
                        });
                        
                        jQuery(this).replaceWith($select);
                    });
                    // make mobile dropdown ToC function
                    jQuery("#TOC select").change(function() {
                        var cTarget = jQuery(this).val();
                        window.location.hash = cTarget;
                    });

                    jQuery("#TOC select").wrap("<div class='dropdown-container stickyDropdown' id='section-nav-mobile'></div>" );
                });
            }
            function checkScreenSize(){
                
                
                var newWindowWidth = jQuery(window).width();
            
                // if the screen is smaller than 768, and if mobile dropdown does not exist
                if ((newWindowWidth < 768) && (jQuery(".dropdown-container").length == 0)) {
                    
                    // show mobile dropdown, hide desktop ToC
                    
                    
                    
                    
                    convertTOCtoDropdown();
                    makeMobileDropdownSticky();
                    // console.log('convert to dropdown, and make sticky');
                }
                // if screen is larger than 768, and if mobile dropdown exists in DOM
                else if ((newWindowWidth > 768) && (jQuery(".dropdown-container").length !== 0) && (jQuery("#TOC .elementor-toc__list-wrapper").length == 0)) {



                    jQuery(".elementor-toc__header").show();
                    jQuery(".dropdown-container").replaceWith(window.originalTOC);
                    
                }
            }

            function makeMobileDropdownSticky() {
                jQuery(window).scroll(function() {
                    if (jQuery(document).scrollTop() > jQuery(".elementor-background-overlay").height() - jQuery(".stickyDropdown").height() ) {
                        jQuery('.stickyDropdown').css('position', 'fixed');
                        jQuery('.stickyDropdown').css('top', jQuery("#ast-mobile-header").height());
                        jQuery(".stickyDropdown").css("width", jQuery("#contentsColumn").width());
                    }
                    else {
                        jQuery('.stickyDropdown').css('position', 'relative');
                        jQuery('.stickyDropdown').css('top', '');
                        jQuery('.stickyDropdown').css('width', '');
                    }
                });
            }

            checkScreenSize();
            
        } else {
            // wait 50 milliseconds and try again.
            window.setTimeout( runWhenJqueryIsLoaded, 250 );
        }
    }

});

</script>

Please use providerUtils.standardizeOrThrow() – opensea Error

I’m having trouble using the openseas.js library. I’m trying to do a getAsset call on a random asset on openseas I found, but I keep getting

Error: DEPRECATED: Please use providerUtils.standardizeOrThrow() instead

I’m currently on node v16.14.2.

How can I resolve this issue? I appreciate the help!

const Web3 = require("web3");
import { OpenSeaPort, Network } from "opensea-js";
import { OpenSeaAsset } from "opensea-js/lib/types";

// This example provider won't let you make transactions, only read-only calls:
const provider = new Web3.providers.HttpProvider("https://mainnet.infura.io");

const seaport = new OpenSeaPort(provider, {
  networkName: Network.Main,
});

(async function main() {
  try {
    //random asset I found on OpenSea
    const asset: OpenSeaAsset = await seaport.api.getAsset({
      tokenAddress: "0x20ed6cdf9344b3a187063a3ff4d883b6b1947b81", // string
      tokenId: 220, // string | number | null
    });
    console.log("Asset", asset);
  } catch (e) {
    console.log("ERROR", e);
  }
});

Javascript – Simulate Keyboard Input into AngularJS Form

Hi I’m working on a Chrome Extension that executes a content script in pure Javascript where I could simulate keypresses into Inputs.

However the site I’m trying to simulate keypresses into is running AngularJS.

The Form

Here’s the HTML code of the form and the input. Note the ng-untouched, ng-pristine, ng-valid classes on the elements.

<form _ngcontent-ysv-c110="" novalidate="" class="ng-untouched ng-pristine ng-valid">
    <esw-address _ngcontent-ysv-c110="">
       <esw-address-my _nghost-ysv-c130="">
          <div _ngcontent-ysv-c130="" class="address-form ng-untouched ng-pristine ng-invalid">

             <esw-input _ngcontent-ysv-c130="" type="text" eswtrim="" class="address-form__firstName ng-untouched ng-pristine ng-invalid" _nghost-ysv-c109="" maxlength="60">
                
                <!-- THIS INPUT -->
                <input _ngcontent-ysv-c109="" triggers="manual" class="textInput ng-untouched ng-pristine ng-invalid" id="firstName" type="text" placeholder="First Name" required="" maxlength="60">
             
            </esw-input>

          </div>
       </esw-address-my>
    </esw-address>
    <button _ngcontent-ysv-c110="" type="button" translate="" class="button-continue">Save Continue</button>
 </form>

The Code I’m Using

Currently the way I try to simulate keypresses into this input is by running the following code:

var firstNameV = "Alex";
var firstName = document.getElementById('firstName');
firstName.focus();
var firstNameV = addressObj['firstName'];
for (let i = 0; i < firstNameV.length; i++) {
    var char = firstNameV[i];
    firstName.dispatchEvent(new KeyboardEvent('keydown', { 'key': char }));
    firstName.value += char;
    firstName.dispatchEvent(new KeyboardEvent('keyup', { 'key': char }));
    await sleep(10);
}

Problem

However when I go ahead and submit the form, the fields light up red as the elements did not change from ng-untouched to ng-touched or ng-pristine to ng-dirty.

So my question, is there a way to properly simulate typing into an AngularJS input in order to trigger the ‘touched’ event and pass form validation so I could submit the form?