Not sure why this isnt returning anything

function roster(url) {
    var url = "https://keeptradecut.com/dynasty/power-rankings/team-breakdown?leagueId=1052466327954309120&platform=2&team=697884463404740600";
    var response = UrlFetchApp.fetch(url);
    var content = response.getContentText();
    var parsed = getRoster(content);
    return parsed;
}
function getRoster(content) {
    var $ = Cheerio.load(content);
    var data = [];
    $('.tb-roster').each(function(i, playerData) {
        var playerDataArray = [];
        var playerNameWithTeam = $(playerData).find('.team-player-name');
        playerDataArray.push(playerNameWithTeam);
        data.push(playerDataArray);
    });
    console.log(data);
    return data;
}

I’m looking to mass import roster data but this is a hold up.

Blazor Server can’t click select element from javascript

On a blazor page, I have a html select element.

<select class="form-select" @bind="Model.ItemId">          
   @foreach (var item in Items)
   {
     <option value="@item.Id">@item.Name</option>
   }
</select>

Using IJSInterop, I am calling a javascript function to focus on the select element, and then try to click it.

    ...
    select.focus();

    var activeElement = document.activeElement;
    activeElement.click();

Everything seems to work fine, except when the select element is “clicked” the options don’t show on the screen.

I don’t know if blazor makes any difference from standard html in this scenario. Any ideas?

object oriented programing function call js

I have a problem because calling the function works in DevTools, but not in Tampermonkey

In DevTools this works, it returns a string

g.worldConfig.getWorldName()

but in Tampermonkey I get an error:

TypeError: Cannot read properties of null (reading 'worldname')
const worldName = g.worldConfig.getWorldName()
console.log(worldName);

I checked and when I add proto, the function is displayed but I can’t call it anyway

const worldName = g.worldConfig.__proto__.getWorldName
getWorldName() {
  return _classPrivateFieldGet(this, _config).worldname;
}

Frontend development [closed]

I don’t know how to start learning frontend development. I want to start learning frontend development. What’s the first step for me? HTML,CSS and JavaScript?

Hi. I want to start learning frontend development. What’s the first step for me? HTML,CSS and JavaScript?

How do I use to perform an action similar to ” window.location = “/GameOverDied”; ” in JS React?

Currently I am trying to do some animation transitions with a game I’m building in React and I don’t want the re-render/refresh function of href or window.location. How would I use <Link> from react-router-dom handled in this regard?

const handleGameOver = () => {
  if (health < 1) {
    window.location = "/GameOverDied";
  } else if (fuel < 1) {
    window.location = "/GameOverFuel";
  } else {
  }
};

I haven’t tried anything yet because I’m not getting the answers I was looking for anywhere else.

Jimp.decoders is undefined with webpack in browser with typescript. How do I fix?

Jimp works fine for me when not in a browser, but when using webpack and running in a browser. Jimp.decoders (and other fields from jimp) are undefined.

To reproduce this problem, copy the following files, run “npm run debug”, and open “http://localhost:4000” in your browser. You will see that the console.log in “src/index.ts” prints an undefined value for Jimp.decoders.

Thanks in advance for your help.

package.json:

{
“name”: “jimp”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“debug”: “npm i && webpack-dev-server –mode development”,
“build”: “npm i && webpack –mode production”
},
“keywords”: [],
“devDependencies”: {
“css-loader”: “^6.10.0”,
“html-webpack-plugin”: “^5.6.0”,
“mini-css-extract-plugin”: “^2.8.0”,
“ts-loader”: “^9.5.1”,
“typescript”: “^5.3.3”,
“webpack”: “^5.90.1”,
“webpack-cli”: “^5.1.4”,
“webpack-dev-server”: “^4.15.1”
},
“dependencies”: {
“jimp”: “^0.22.10”
}
}

webpack.config.js:

const webpack = require(“webpack”);
const HtmlWebpackPlugin = require(“html-webpack-plugin”);
const path = require(‘path’);

module.exports = {
const webpack = require(“webpack”);
const HtmlWebpackPlugin = require(“html-webpack-plugin”);
const path = require(‘path’);

module.exports = {
entry: ‘./src/index.ts’,
module: {
rules: [
{
test: /.ts?$/,
use: ‘ts-loader’,
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [‘.tsx’, ‘.ts’, ‘.js’],
fallback: {
“fs”: false,
“path”: false,
“crypto”: false,
“process”: false,
},
},
output: {
filename: ‘bundle.js’,
path: path.resolve(__dirname, ‘dist’),
},
plugins: [
new HtmlWebpackPlugin({
title: ‘Jimp problem’,
template: ‘src/custom.html’ }),
new webpack.DefinePlugin({
‘process.browser’: ‘true’
})
],
devServer: {
static: path.join(__dirname, “dist”),
compress: true,
port: 4000,
},
};

tsconfig.json:

{
“compilerOptions”: {
“target”: “ES5”,
“module”: “ES2015”,
“moduleResolution”:”node”,
“noImplicitAny”: true,
“allowSyntheticDefaultImports”: true,
}
}

src/index.ts:

import Jimp from “jimp”;
console.log(“Jimp.decoders”: Jimp.decoders);`

src/custom.html:

Jimp Test Case

See the console output. Why is Jimp.decoders undefined?

I tried various permutations of settings for webpack, typescript, etc but can’t find one that works.

Issue setting StackNavigation background color to transparent (shows white)

I have a react native applicaiton that I am currently building. One part of my react native application is that if the user is not logged in, I want to show a background image with the content from the LoginScreen displaying on the screen with a red background. I am noticing that the AuthenticationStackNavigation cards all have a white background for som reason and I can not remove it by setting cardStyle: { backgroundColor: 'rgba(0,0,0,0)' }, I dont know how to remove the background. I also tried setting backgroundColor: 'transparent'. Does anyone know how to remove the background.

import React from 'react';
import {createStackNavigator} from '@react-navigation/stack';
import LoginScreen from '../Screens/Authentication/LoginScreen';
import SignupScreen from '../Screens/Authentication/SignupScreen';
import ProfileScreen from '../Screens/Authentication/ProfileScreen';
import ForgotPasswordScreen from '../Screens/Authentication/ForgotPasswordScreen';
import ConfirmEmailScreen from '../Screens/Authentication/ConfirmEmailScreen';
import { NavigationContainer } from '@react-navigation/native';
const StackNav = createStackNavigator();

const AuthenticationStackNavigation = () => {
  return (
    <NavigationContainer>
      <StackNav.Navigator
        initialRouteName="LoginScreen"
        screenOptions={{
          headerShown: false,
          cardStyle: { backgroundColor: 'rgba(0,0,0,0)' },
        }}>
        <StackNav.Screen name="LoginScreen" component={LoginScreen} />
        <StackNav.Screen name="SignupScreen" component={SignupScreen} />
        <StackNav.Screen name="ProfileScreen" component={ProfileScreen} />
        <StackNav.Screen name="ForgotPasswordScreen" component={ForgotPasswordScreen} />
        <StackNav.Screen name="ConfirmEmailScreen" component={ConfirmEmailScreen} />
      </StackNav.Navigator>
    </NavigationContainer>
  );
};

export default AuthenticationStackNavigation;

You can see the background image I have. The red login for is from the LoginScreen.tsx.

My issue is with the navigation.

screen image from react native applicaiotn

how do i rearrange elements vertically and horizontally in the center of the page?

hi — i am working on a project that involves a backdrop of floating words, along with a centered button. once this button is tapped, 3 words are randomly selected, while the others, along with the button, fade away.

here is the javascript:

// Interval and words for placing words randomly
var interval = 100; // Interval between word placements (in milliseconds)
var buttonClicked = false; // Flag to control word population
var words = [
  "U let me bum two cigarettes",
  "i have thought about you since",
  "your right index finger was wrapped in a bandage",
  "You had a heart tattoo on your left arm",
  "I just wanted to make sure you were okay",
  "we bumped into each other in the produce section looking at bananas",
  "You noticed me but avoided my gaze",
  "I'll never be able to explain",
  "I cannot sleep",
  "You wear high heels and more when no one sees you",
  "snow flakes fall upon tender flesh",
  "watch me bleed",
  "you smiled but still left",
  "We exchanged glances",
  "Has anyone seen you recently?",
  "You told me you were sober and that I was pretty",
  "Let's have breakfast",
  "I liked ur necklace on saturday",
  "You said kiss me",
  "You used to read missed connections in our bed",
  "What are the chances?",
  "If you loved me I wouldn't have to guess",
  "Just another self inflicted tragedy",
  "I wanted to take you home",
  "To have someone to talk with about anything",
  "Cupid may be real",
  "Blue's my Favorite Color",
  "A shimmering full moon silhouetting",
  "not in my mind. I didn't think",
  "you disappeared",
  "Get back to me",
  "did you change your number?",
  "Spring is coming",
  "you saw me seeing you",
  "Gorbachev says it's ok",
  "You talk about your dad",
  "I walked up and you left",
  "many moons ago",
  "a genuine woman posting",
  "It's been a while",
  "I hope you are safe",
  "you were driving a blue Toyota corolla right before noon",
  "Everyone already knows",
  "We never got a chance to talk",
  "The valley is beautiful",
  "maybe you could come over",
  "If you know who I am",
  "i know it's you",
  "You've moved and I want to see you again",
  "You don’t critically think",
  "telling you how I wish my gf had your lust for adventure",
  "I have no way of contacting you",
  "Never forget",
  "But it’s just the way of the world",
  "You are really coming apart at the seams",
  "I’m sorry you had to move",
  "Who knew?",
  "It's Safer to Have a Gun in the House",
  "if you’re looking for a home",
  "I get butterflies",
  "How will you defend yourself?",
  "change will control everything in your life",
  "Thank you",
  "I have several young zebra finches that are looking for forever homes",
  "I hope we can talk",
  "I hope you got home safely",
  "in her body",
  "I know you're real",
  "I broke my foot last night",
  "Strawberry Fields",
  "Let's hang out at my place",
  "Remember me?",
  "you were flirting with me",
  "Will you be serious right now?",
  "You know who you are",
  "Let’s have a conversation",
  "We should have stayed in touch",
  "Cant help but think there's more to it",
  "Do you like the way it’s turning out?",
  "we couldn’t stop looking at each other",
  "I'd like to see u again",
  "I wish I had talked to you",
  "I am Anti-Drama",
  "not sure what it was about you",
  "yes I am aware",
  "I should have said more",
  "Just curious",
  "i held the door open for you this morning",
  "We grew close and then both of our lives fell apart",
  "I know it sounds made up",
  "Was there more of a connection?",
  "I hate to see you",
  "I know it's you",
  "Wish I had ran in the other direction when I had the chance",
  "You plasma cut a hole into my heart",
  "There's almost no chance",
  "This is so ridiculous",
  "you were searching for something that wasn't",
  "it's spring, the season of renewal",
];


// Set the overflow property of the body to hidden
document.body.style.overflow = 'hidden';

// Array to store positions of placed words
var usedPositions = [];

// Flag to track if the button has been clicked
var buttonClicked = false;

// Function to check if a position is already used
function isPositionUsed(x, y) {
  for (var i = 0; i < usedPositions.length; i++) {
    var pos = usedPositions[i];
    if (Math.abs(pos.x - x) < 200 && Math.abs(pos.y - y) < 50) {
      return true;
    }
  }
  return false;
}

// Function to apply typewriter effect to a word with different speeds
function applyTypewriterEffect(wordElement, word, speeds) {
  var i = 0;
  var interval = setInterval(function() {
    if (i < word.length) {
      wordElement.innerHTML += word.charAt(i);
      i++;
    } else {
      clearInterval(interval);
    }
  }, speeds.shift()); // Use different speed for each character
}

// Function to generate a random font size
function getRandomFontSize() {
  return Math.floor(Math.random() * 20) + 10 + 'px'; // Adjust the range of font sizes as needed
}

// Function to place words at random positions
var wordPlacementInterval = setInterval(function() {
  if (!buttonClicked) {
    var currentWord = words.shift();
    if (currentWord) {
      var word = document.createElement('span');
      word.style.position = 'absolute'; // Make sure the position is absolute

      var x, y;
      // Generate non-overlapping random positions
      do {
        x = Math.random() * (window.innerWidth - 200);
        y = Math.random() * (window.innerHeight - 50);
      } while (isPositionUsed(x, y));

      word.style.top = y + 'px'; // Set the top position
      word.style.left = x + 'px'; // Set the left position
      word.style.fontSize = getRandomFontSize(); // Set a random font size
      word.style.animation = 'floating 5s ease-in-out infinite'; // Adjust duration and timing function as needed
      document.body.appendChild(word);

      // Generate different speeds for each character (adjust as needed)
      var speeds = Array.from({
        length: currentWord.length
      }, () => Math.floor(Math.random() * 50) + 10);

      // Apply typewriter effect to the word with different speeds for each character
      applyTypewriterEffect(word, currentWord, speeds);

      // Store the position of the placed word
      usedPositions.push({
        x: x,
        y: y
      });
    } else {
      clearInterval(wordPlacementInterval);
    }
  }
}, 1000); // Change interval as needed

// Function to select three random words from the displayed words
function selectRandomWords() {
  // Get all word elements
  var wordElements = document.querySelectorAll('span');

  // Convert NodeList to an array
  var wordElementsArray = Array.from(wordElements);

  // Shuffle the array of word elements
  wordElementsArray.sort(() => Math.random() - 0.5);

  // Select the first three word elements to remain on the screen
  var remainingWords = wordElementsArray.slice(0, 3);

  // Fade out the non-selected words
  wordElementsArray.forEach(function(wordElement) {
    if (!remainingWords.includes(wordElement)) {
      $(wordElement).fadeOut();
    }
  });

  // Fade out the button
  $("button").fadeOut();

  // Set buttonClicked to true to stop word population
  buttonClicked = true;
}

// Attach an event listener to the button
$("button").on('click', function() {
  selectRandomWords();
});


$("button").hover(function() {
  var self = this;
  var pos = -(Math.floor(Math.random() * 5) + 1) * 55
  setTimeout(function() {
    $(self).find("ul").css("margin-top", pos + "px");
  }, 500);
}, function() {
  $(this).find("ul").css("margin-top", "0px");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

I am trying to get these 3 final randomly selected words to float into the center of the screen, each on its own line, to read like a poem. but there’s something wrong with my code, can someone please help? right now they are staying place where they were before the button was clicked.

My function has an array in it that seems to be working but the thing responding to it keeps going to 0

The thing responding to my random array keeps going back to 0

<script>
var holes = document.getElementsByClassName("holes");
var container = document.getElementById("container");

function chooseHole() {
    var randomNum = Math.floor(Math.random() * 6);
    container.children[randomNum].id = "moleHole";
    var moleHole = document.getElementById("moleHole");
    moleHole.innerHTML = '<img src = "https://i.postimg.cc/30BdQDNP/pngtree-cartoon-mole-come-out-of-the-hole-picture-image-8497055.png">';
    var randomTime = Math.floor(Math.random() * 2500);

    function functionC() {
        deleteMole();
    }
    setInterval(functionC, randomTime);
}

function deleteMole() {
    var moleHole = document.getElementById("moleHole");
    moleHole.innerHTML = "<img src = 'https://i.ibb.co/VDXK9Hw/Pngtree-cartoon-mole-come-out-of-the-hole-picture-image-8497055-2.png'>";
    chooseHole();
}
chooseHole();
</script>

So far I’ve console.logged the random array number and that’s working correctly

Google sheets: How to update script to count colored cells with specific text

I found a script that allows you to count colored cells in google sheets. I would like to update this code to be similar to the CountIf function where you can also specify a criteria (specifically a partial text) but am unsure on how to add it

The original code that only counts colored cells is as follows

function countColoredCells(countRange,colorRef) {

var activeRange = SpreadsheetApp.getActiveRange();

var activeSheet = SpreadsheetApp.getActiveSheet();

var activeformula = activeRange.getFormula();

var countRangeAddress = activeformula.match(/((.*),/).pop().trim();

var backGrounds = activeSheet.getRange(countRangeAddress).getBackgrounds();

var colorRefAddress = activeformula.match(/,(.*))/).pop().trim();

var BackGround = activeSheet.getRange(colorRefAddress).getBackground();

var countColorCells = 0;

for (var i = 0; i < backGrounds.length; i++)

for (var k = 0; k < backGrounds[i].length; k++)

  if ( backGrounds[i][k] == BackGround )

    countColorCells = countColorCells + 1;

return countColorCells;

};

I attempted to update it myself as shown below but it does not work

function countColoredCells(countRange,colorRef,_criteria) {

var activeRange = SpreadsheetApp.getActiveRange();

var activeSheet = SpreadsheetApp.getActiveSheet();

var activeformula = activeRange.getFormula();

var countRangeAddress = activeformula.match(/((.*),/).pop().trim();

var backGrounds = activeSheet.getRange(countRangeAddress).getBackgrounds();

var colorRefAddress = activeformula.match(/,(.*))/).pop().trim();

var BackGround = activeSheet.getRange(colorRefAddress).getBackground();

var _criteriaAddress = activeformula.match(/,(.*))/).pop().trim();

var _criteriatxt = activeSheet.getRange(_criteriaAddress).getBackground();

var countColorCells = 0;

for (var i = 0; i < backGrounds.length; i++)

for (var k = 0; k < backGrounds[i].length; k++)

  if ( backGrounds[i][k] == BackGround && backGrounds[i][k] == _criteriatxt )

    countColorCells = countColorCells + 1;

return countColorCells;

};

Add an event listener to an element once it has loaded (vanilla JS)

My website has eventlisteners for various actions. I currently add these eventlisteners to my elements once the whole DOM has loaded, like this:

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("someid").addEventListener("click", somefunction(); });
})

I’ve gotten feedback from some users with poor internet connexion that they have to wait sometimes up to a full minute for the whole page to load before the website to work properly..

Is there a way to add an eventlistener to an element the instant it loads on the page instead of waiting for the whole DOM to load? I’d rather not go back to using onclick=”” within the HTML like in the olden days.

By choice, I only use vanilla javascript.

Thanks in advance.

Unhandled Runtime Error. Lazy element type must resolve to a class or function

I’m using next.js 14 and I’m trying to merge 2 pdf files based on their contents. However, when I try to read the content of the pdf file using const pdf = await pdfjsLib.getDocument(content).promise;, I got the error Unhandled Runtime Error
Error: Element type is invalid. Received a promise that resolves to: [object Promise]. Lazy element type must resolve to a class or function.
Can anyone help me solve this? I dont even use lasy elemnt. Thanks in advance!

page.tsx:

import PDFFileMerger from "@/components/PDFFileMerger";
import Image from "next/image";
import React, { useState } from 'react';

export default function Home() {

  return (
    <main className="overflow-hidden">
      <PDFFileMerger />
    </main>
  );
}

PDFFileMerger.tsx:

"use client";

import React, { useState, ChangeEvent, useEffect } from 'react';
import { PDFDocument, rgb } from 'pdf-lib';
import * as pdfjsLib from 'pdfjs-dist';

function PDFFileMerger() {

  const [file1, setFile1] = useState<File | null>(null);
  const [file2, setFile2] = useState<File | null>(null);
  const [mergedPdf, setMergedPdf] = useState<Uint8Array | null>(null);
  const [textOutput, setTextOutput] = useState<string>('');

  useEffect(() => {
    if (!file1) return;


    const fileReader = new FileReader();
    fileReader.onload = async function() {
      const content = this.result;
      if (content) {
        try {
          const pdf = await pdfjsLib.getDocument(content).promise;
          console.log(pdf);
        } catch (error) {
          console.error('Error loading PDF:', error);
        }
      }
    };

    fileReader.readAsArrayBuffer(file1);

  }, [file1] );

  const handleFile1Change = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = event.target.files?.[0];
    setFile1(selectedFile || null);
  };

 return (
    <div>
      <input id="pdf1" type="file" accept=".pdf" onChange={handleFile1Change} />
      <input type="file" accept=".pdf" onChange={handleFile2Change} />
      <button onClick={handleMerge}>Merge PDFs</button>
      {mergedPdf && (
      <a
        href={URL.createObjectURL(new Blob([mergedPdf], { type: 'application/pdf' }))}
        target="_blank"
        rel="noopener noreferrer"
        download="merged.pdf"
      >
        Open Merged PDF
      </a>
    )}
    <div id="textOutput">{textOutput}</div>
    </div>
  );
};

export default PDFFileMerger;

I tried to use with and without useEffect(), and adding async, await, etc… . But the error still occurs whenever I have the line const pdf = await pdfjsLib.getDocument(content).promise;

Button background color darkens in safari when video autoplaying in Svelte

So I noticed when I added playsinline into the video attributes to enable autoplay, the button below gets darkened and dimmed. This only happens when it’s running on safari in on my iphone. I’ve tried adding a z-index to the button and also a background color in the to the video in styles. Any suggestions.

<video autoplay muted loop playsinline preload="auto" class="videos">
                <source src={vid} type="video/webm" />
                <track kind="captions" /></video
            >

Thanks

Headers for WebSocket client?

I need to connect Deno (as a client) to a WebSocket server that requires custom headers on connection. I can’t seem to find any currently supported method to accomplish this since the WebSocket API only allows for the url and protocols parameters.

Is there any known best practice to accomplish this?