Javascript Only ESLint ‘HTMLElement’ is not defined no-undef error?

Not a Typescript Question

I’ve asked this question once already at it was closed saying that it is already answered here:

ReferenceError: HTMLElement is not defined in TypeScript

Please note that this is not a typescript project, so the typescript answer does not fit.

Here’s the question again.

For the source files in this project this ESLint configuration creates these errors.


/Users/oleersoy/Temp/Remove/fs-javascript-starter/src/hello-world.component.js
   7:42  error  'HTMLElement' is not defined     no-undef
  52:3   error  'customElements' is not defined  no-undef

/Users/oleersoy/Temp/Remove/fs-javascript-starter/src/hello-world.component.spec.js
  3:1  error  'suite' is not defined  no-undef
  4:3  error  'test' is not defined   no-undef

✖ 4 problems (4 errors, 0 warnings)

How do we switch these off so that ESLint allows suite, test, HTMLElement, and customElements?

Here are the source files for reference:

eslint.config.js

import eslint from "@eslint/js";

export default [
    // apply recommended rules to JS files
    {
        files: ["**/*.js", "**/*.cjs", "**/*.mjs"],
        rules: eslint.configs.recommended.rules
    },
    {
        ignores: ["rollup.config.js", "web-test-runner.config.js"]
    }
]

src/hello-world.component.js

/**
 *  @category WebComponent
 *
 * Hello World Web Component
 * that renders a greeting.
 */
export class HelloWorldComponent extends HTMLElement {
    static get observedAttributes() {
      return ['name'];
    }
  
    /**
     * The name to greet
     * @defaultValue World
     */
    name = 'World';
    something
    /**
     * Initializes the name property to `World`.
     */
    constructor() {
      super();
      //    this.name = 'World';
    }
  
    /**
     * Sets the component inner
     * html to the greeting.
     */
    connectedCallback() {
      this.textContent = `Hello ${this.name}!`;
    }
  
    //========================================
    // attribute change callback
    //========================================
    attributeChangedCallback(
      property,
      oldValue,
      newValue
    ) {
      if (oldValue === newValue) return;
      switch (property) {
        case 'name':
          this.name = newValue;
          break;
        default:
          throw new Error(`Unhandled attribute: ${property}`);
      }
    }
  }
  customElements.define('hello-world', HelloWorldComponent);

src/hello-world.component.spec.js

import {expect, fixture, html} from '@open-wc/testing';

suite('hello-world.component tests', () => {
  test('fixture instantiation', async () => {
    const el = (await fixture(
      html`<hello-world></hello-world> `
    ));
    expect(el).not.to.equal(null);
    //    expect(true).to.equal(false);
  });
});

wordpress woocommerse quick view and hover button

I’ve been working on this for about three hours, and I’m honestly stuck. Here’s the situation: we have two types of products—some are for rent, and others are for purchase. We’ve already changed the buttons as shown in the screenshot above, but we’re trying to change the “Buy Now” button to “Rent Now” on certain products. The rule we’re going with is that the button should say “Rent Now” unless the product is on a page with “general-retail” in the URL (though there may be a better way to differentiate between rental and purchasable products, that’s the best I’ve come up with so far).

We need the button text to change in three situations:

When someone clicks “Quick View” on a product photo.
When the button is hovered over.
When the button is clicked.
Right now, we’ve managed to change the button text to “Rent Now” when you’re on the product page itself, but it’s applying to all products regardless of whether they should be rented or bought. What we’re aiming for is to have it show “Buy Now” on the products that can be purchased and “Rent Now” on the rental products.

Praying someone can help me!!

Our theme: woodcart
We are using wordpress and woocommerse

what we want to be changed depending on the type of product: enter image description here

what it looks like now for all product pages: enter image description here

ive tried all the online resouces i could find on the topic

How to user KV in cloudflare workers?

I am using wrangler v3.78. I am trying to make a test worker, just to figure out how KV database works. This is my code:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const { pathname } = new URL(request.url)

  if (request.method === 'GET' && pathname === '/retrieve') {
    const key = 'data'
    const data = await env.BINDING_NAME.get(key, 'text')
    return new Response(data || 'Key not found', { status: 200 })
  } else if (request.method === 'POST' && pathname === '/store') {
    const data = await request.text()
    await env.BINDING_NAME.put('data', data)
    return new Response('Data stored successfully', { status: 200 })
  } else {
    return new Response(JSON.stringify({ error: 404, message: 'Not found' }), {
      status: 404,
      headers: { 'Content-Type': 'application/json' },
    })
  }
}

when I run wrangler dev or npm run dev I get these errors:

X [ERROR] service core:user:api: Uncaught Error: Dynamic require of "node:stream" is not supported

    at null.<anonymous> (core:user:api:9:11)
    at null.<anonymous> (core:user:api:107:28)
    at null.<anonymous> (core:user:api:1222:3)


X [ERROR] MiniflareCoreError [ERR_RUNTIME_FAILURE]: The Workers runtime failed to start. There is likely additional logging output above.

Any assistance in what I am doing wrong to get these errors and how to fix them would be very appreciated, thanks.
I am very new to any backend developing, and tbh I don’t really understand what some of the code even does, so there is a good chance I am getting it all wrong.
Thanks anyway

ESLint ‘HTMLElement’ is not defined no-undef error?

For the source files in this project this ESLint configuration creates these errors.


/Users/oleersoy/Temp/Remove/fs-javascript-starter/src/hello-world.component.js
   7:42  error  'HTMLElement' is not defined     no-undef
  52:3   error  'customElements' is not defined  no-undef

/Users/oleersoy/Temp/Remove/fs-javascript-starter/src/hello-world.component.spec.js
  3:1  error  'suite' is not defined  no-undef
  4:3  error  'test' is not defined   no-undef

✖ 4 problems (4 errors, 0 warnings)

How do we switch these off so that ESLint allows suite, test, HTMLElement, and customElements?

Here are the source files for reference:

eslint.config.js

import eslint from "@eslint/js";

export default [
    // apply recommended rules to JS files
    {
        files: ["**/*.js", "**/*.cjs", "**/*.mjs"],
        rules: eslint.configs.recommended.rules
    },
    {
        ignores: ["rollup.config.js", "web-test-runner.config.js"]
    }
]

src/hello-world.component.js

/**
 *  @category WebComponent
 *
 * Hello World Web Component
 * that renders a greeting.
 */
export class HelloWorldComponent extends HTMLElement {
    static get observedAttributes() {
      return ['name'];
    }
  
    /**
     * The name to greet
     * @defaultValue World
     */
    name = 'World';
    something
    /**
     * Initializes the name property to `World`.
     */
    constructor() {
      super();
      //    this.name = 'World';
    }
  
    /**
     * Sets the component inner
     * html to the greeting.
     */
    connectedCallback() {
      this.textContent = `Hello ${this.name}!`;
    }
  
    //========================================
    // attribute change callback
    //========================================
    attributeChangedCallback(
      property,
      oldValue,
      newValue
    ) {
      if (oldValue === newValue) return;
      switch (property) {
        case 'name':
          this.name = newValue;
          break;
        default:
          throw new Error(`Unhandled attribute: ${property}`);
      }
    }
  }
  customElements.define('hello-world', HelloWorldComponent);

src/hello-world.component.spec.js

import {expect, fixture, html} from '@open-wc/testing';

suite('hello-world.component tests', () => {
  test('fixture instantiation', async () => {
    const el = (await fixture(
      html`<hello-world></hello-world> `
    ));
    expect(el).not.to.equal(null);
    //    expect(true).to.equal(false);
  });
});

why is my default ionic app not getting default styling?

I am learning Ionic, and I am creating a test project and playing around. I have noticed a few things being different from the examples they show in their docs. For example:

enter image description here

This is a small screenshot of how some elements are displayed. For example the Card component has a very strange shadow. Whereas in the ionic docs, the example shows a much softer shadow:
enter image description here

why is it that i am not getting the same styling?

React Native CarPlay app not loading JavaScript when phone app is closed

I’m developing a React Native app with CarPlay support using the react-native-carplay library. The CarPlay interface works correctly when the phone app is open, but it fails to load the JavaScript when the phone app is closed. Currently, the CarPlay does not load the JS when the app is open either, although that is something easier to fix.

I already tried adhering to this README, although to little avail.

// AppDelegate.mm (redacted and consolidated)
@implementation AppDelegate

- (BOOL)initAppFromScene:(UISceneConnectionOptions *)connectionOptions {
    if (self.rootView == nil) {
        self.rootViewFactory = [self createRCTRootViewFactory];
        NSDictionary *initProps = [self prepareInitialProps];
        self.rootView = [self.rootViewFactory viewWithModuleName:self.moduleName 
                                              initialProperties:initProps 
                                                  launchOptions:[self connectionOptionsToLaunchOptions:connectionOptions]];
        return YES;
    }
    return NO;
}

// Other necessary methods...

@end


// CarSceneDelegate.mm (redacted and consolidated)
@implementation CarSceneDelegate

- (void)templateApplicationScene:(CPTemplateApplicationScene *)templateApplicationScene
    didConnectInterfaceController:(CPInterfaceController *)interfaceController {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    [appDelegate initAppFromScene:nil];
    UIView *carPlayRootView = [appDelegate.rootViewFactory viewWithModuleName:@"CarPlayApp"
                                                            initialProperties:nil
                                                                launchOptions:nil];
    
    UIViewController *rootViewController = appDelegate.createRootViewController;
    [appDelegate setRootView:appDelegate.rootView toRootViewController:rootViewController];
    
    CPWindow *carWindow = templateApplicationScene.carWindow;
    carWindow.rootViewController = rootViewController;
    
    [carPlayRootView setFrame:carWindow.bounds];
    [carWindow addSubview:carPlayRootView];
  
    [RNCarPlay connectWithInterfaceController:interfaceController window:carWindow];
}

// Other necessary methods...

@end

// SceneDelegate.mm (redacted and consolidated)
@implementation SceneDelegate

- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions
{
    if ([scene isKindOfClass:[UIWindowScene class]])
    {
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        BOOL hasCreatedBridge = [appDelegate initAppFromScene:connectionOptions];
        
        UIViewController *rootViewController = appDelegate.createRootViewController;
        [appDelegate setRootView:appDelegate.rootView toRootViewController:rootViewController];

        UIWindow *window = [[UIWindow alloc] initWithWindowScene:scene];
        window.rootViewController = rootViewController;
        self.window = window;
        appDelegate.window = window;
        [self.window makeKeyAndVisible];

        // Handle splash screen...
    }
}

// Other necessary methods...

@end

// JavaScript
import { AppRegistry } from "react-native";
import CarCode from "./carplay/CarCode";

AppRegistry.registerComponent("CarPlayApp", () => CarCode);

I’ve tried various approaches, including:

  • Initializing the React Native bridge in the CarPlay scene delegate.
  • Creating a separate root view for CarPlay.
  • Ensuring that the JavaScript bundle is loaded and executed.

Despite these attempts, the CarPlay interface remains blank when the phone app is not running. The native iOS code seems to be working, but the JavaScript is not being loaded or executed.
What am I missing to ensure that the React Native JavaScript code runs in CarPlay even when the phone app is closed?
Additional information:

React Native version: 75.0
react-native-carplay version: 2.4.1-beta.0
iOS version: 16.6

Any help or insights would be greatly appreciated!

how to add items to the cart without refresh in reactjs

I am working on implementing shopping cart functionality in a React application, and while I have made some progress, I encountered challenges in managing the application’s state effectively. The application consists of two main components: BookList and Navbar. The BookList component displays a list of books, each with an “Add to Cart” button, while the Navbar component contains a cart icon that shows the total number of items in the cart.

Currently, I store the cart items in localStorage. My goal is to ensure that items are added to the cart seamlessly, without the need to refresh the page, and that the cart count in the Navbar is updated dynamically as items are added.

BookList.jsx:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { 
  Card, CardBody, Image, Text, Stack, Heading, Input, Center, InputGroup, InputLeftElement, Box, IconButton 
} from '@chakra-ui/react';
import { SearchIcon } from '@chakra-ui/icons';
import { BsCartPlusFill } from "react-icons/bs";

export const BookList = () => {
  const navigate = useNavigate();
  const [data, setData] = useState([]); 
  const [searchTerm, setSearchTerm] = useState('');   
  const [cartData, setCartData] = useState(() => {
    const savedCart = localStorage.getItem('cartData');
    return savedCart ? JSON.parse(savedCart) : [];
  });

  useEffect(() => {
    const fetchBooks = async () => {
      try {
        const response = await axios.get('http://localhost:5000/api/books');
        setData(response.data.data);
      } catch (err) {
        console.log(err);
      }
    };
    fetchBooks();
  }, []);

  
  const filteredBooks = data.filter(book => 
    book.title.toLowerCase().includes(searchTerm.toLowerCase())
  );

  
  const handleAddToCart = (book) => {
    const existingCartItem = cartData.find(cartItem => cartItem.id === book._id);

    if (existingCartItem) {
      const updatedCartData = cartData.map(cartItem => 
        cartItem.id === book._id ? { ...cartItem, quantity: cartItem.quantity + 1 } : cartItem
      );
      setCartData(updatedCartData);
      localStorage.setItem('cartData', JSON.stringify(updatedCartData));
      window.location.reload();
    } else {
      
      const newCartItem = {
        id: book._id,
        title: book.title,
        image: book.cover,
        quantity: 1, 
      };

      const updatedCartData = [...cartData, newCartItem];
      setCartData(updatedCartData);
      localStorage.setItem('cartData', JSON.stringify(updatedCartData));
      window.location.reload();
    }
   
  };

  

  return (
    <div>
      
      <Center>
        <Text fontSize={'3xl'} fontWeight={'bold'} marginTop={'50px'}>
          What Are you looking For ..?
        </Text>
      </Center>

      <Center>
        <InputGroup width="30%" margin={'30px'}>
          <InputLeftElement pointerEvents='none'>
            <SearchIcon color='black' />
          </InputLeftElement>
          <Input
            placeholder="Search by book name"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            mb="10px"
            size='md'
          />
        </InputGroup>
      </Center>

      <div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-around', marginTop: '20px' }}>
        {filteredBooks.length > 0 ? (
          filteredBooks.map((book) => (
            <Box
              position="relative"
              key={book._id}
              style={{ margin: '20px' }}
              cursor="pointer"
              role="group"
              _hover={{
                transform: 'scale(1.05)',
                transition: 'all 0.4s ease-in-out',
                boxShadow: 'xl',
              }}
            >
              <Card
                maxW="sm"
                _groupHover={{
                  transform: 'scale(1.05)', 
                  transition: 'all 0.4s ease-in-out',
                  boxShadow: 'xl',
                }}
                onClick={() => {
                  navigate(`/book/bookdetails/${book._id}`);
                }}
              >
                <CardBody>
                  <Image
                    src={book.cover}
                    alt="Book cover"
                    borderRadius="xl"
                    boxSize="500px"
                  />
                  <Stack mt="6" spacing="3">
                    <Heading size="md">
                      {book.title} <span style={{ color: 'green', fontSize: '15px' }}>${book.price}</span>
                    </Heading>
                    <Text>{book.author}</Text>
                  </Stack>
                </CardBody>
              </Card>

              
              <IconButton
                aria-label="Add to cart"
                icon={<BsCartPlusFill />}
                position="absolute"
                bottom="5%"
                right="5%"
                colorScheme="green"
                borderRadius="full"
                size="lg"
                _groupHover={{
                  transform: 'scale(1.4)',  
                  transition: 'all 0.4s ease-in-out',
                  bottom: '3%',  
                  right: '3%',
                }}
                onClick={(e) => {
                  e.stopPropagation(); 
                  handleAddToCart(book);
                }}
              />
            </Box>
          ))
        ) : (
          <p>No books available :(</p>
        )}
      </div>
    </div>
  );
};

Navbar.jsx:

import React, { useState } from 'react';
import { Flex, Box, Heading, UnorderedList, ListItem, Link, Button, IconButton, Text, Image, Badge } from '@chakra-ui/react';
import { Link as RouterLink } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import { FaCartShopping } from "react-icons/fa6";
import { MdDelete } from "react-icons/md";
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverBody,
} from '@chakra-ui/react';

export const Navbar = () => {
  const navigate = useNavigate();
  const isUserSignIn = !!localStorage.getItem('token');
  const getCartDataArr = JSON.parse(localStorage.getItem('cartData'));
  const [cartItemCount, SetCartItemCount] = useState(getCartDataArr ? getCartDataArr.length : 0);

  const handleSignOut = () => {
    localStorage.removeItem('token');
    navigate('/login');
  };

  const handleRemoveFromCart = (itemId) => {
    const cartData = JSON.parse(localStorage.getItem('cartData'));
    const itemIndex = cartData.findIndex(cartItem => cartItem.id === itemId);
    if (itemIndex > -1) {
      if (cartData[itemIndex].quantity > 1) {
        cartData[itemIndex].quantity -= 1;
      } else {
        cartData.splice(itemIndex, 1);
      }
      localStorage.setItem('cartData', JSON.stringify(cartData));
      SetCartItemCount(cartData.length);
      window.location.reload(); 
    }
  };

  return (
    <Box bg='#ffffff' color='white'>
      <Flex
        justify='space-between'
        align='center'
        px={8}
        py={4}
        height='80px'
        maxW='1200px'
        mx='auto'
      >
        <Box>
          <Heading as={RouterLink} to="/" fontSize='2xl' color={'#2D3748'} _hover={{ color: '#005bc8' }}>
           Logo
          </Heading>
        </Box>

        <UnorderedList display='flex' listStyleType='none' m={0} gap='20px' alignItems='center'>
          {isUserSignIn ? (
            <>
              <ListItem display="flex" alignItems="center">
                <Popover>
                  <PopoverTrigger>
                    <Box position="relative">
                      <Button variant={'ghost'} p={0}>
                        <FaCartShopping size="20px" />
                      </Button>
                      <Badge
                        position="absolute"
                        top="-8px"
                        right="-8px"
                        bg="red.500"
                        borderRadius="full"
                        px={2}
                        fontSize="0.8em"
                        color="white"
                      >
                        {cartItemCount}
                      </Badge>
                    </Box>
                  </PopoverTrigger>
                  <PopoverContent>
                    <PopoverBody>
                      {getCartDataArr && getCartDataArr.length > 0 ? (
                        getCartDataArr.map((item) => (
                          <Box key={item.id} marginTop={'10%'}>
                            <Flex alignItems="center" justifyContent="space-between" mb={2} backgroundColor={'#f6f6f6'} padding={'10px'}>
                              <Image 
                                src={item.image} // Ensure this matches your object property
                                alt="Cart Item Image"
                                boxSize="50px"  
                                objectFit="contain" 
                                maxH="50px"       
                                maxW="50px"       
                                borderRadius="md" 
                              />
                              <Text color={'black'} ml={2}>{item.title} x{item.quantity}</Text> 
                              <IconButton aria-label="Delete item" icon={<MdDelete color='red' />} onClick={() => handleRemoveFromCart(item.id)} variant="ghost" />
                            </Flex>
                          </Box>  
                        ))
                      ) : (
                        <Text>No items in the cart.</Text>
                      )}
                      <Button backgroundColor={'#85ff8d'} _hover={{ backgroundColor: "#41ff4e" }} width="100%" mt={4}>
                        Proceeding
                      </Button>
                    </PopoverBody>
                  </PopoverContent>
                </Popover>
              </ListItem>
              <ListItem>
                <Link as={RouterLink} to="/account" color={'#2D3748'} _hover={{ backgroundColor: "#000", color: '#fff' }}>
                  Account
                </Link>
              </ListItem>
              <ListItem>
                <Link as={RouterLink} to="/login" color={'#2D3748'} _hover={{ backgroundColor: "#000", color: '#fff' }} onClick={handleSignOut}>
                  Signout
                </Link>
              </ListItem>
            </>
          ) : (
            <>
              <ListItem display="flex" alignItems="center">
                <Popover>
                  <PopoverTrigger>
                    <Box position="relative">
                      <Button variant={'ghost'} p={0}>
                        <FaCartShopping size="20px" />
                      </Button>
                      <Badge
                        position="absolute"
                        top="-8px"
                        right="-8px"
                        bg="red.500"
                        borderRadius="full"
                        px={2}
                        fontSize="0.8em"
                        color="white"
                      >
                        {cartItemCount}
                      </Badge>
                    </Box>
                  </PopoverTrigger>
                  <PopoverContent>
                    <PopoverBody>
                      {getCartDataArr && getCartDataArr.length > 0 ? (
                        getCartDataArr.map((item) => (
                          <Box key={item.id} marginTop={'10%'}>
                            <Flex alignItems="center" justifyContent="space-between" mb={2} backgroundColor={'#f6f6f6'} padding={'10px'}>
                              <Image 
                                src={item.image} // Ensure this matches your object property
                                alt="Cart Item Image"
                                boxSize="50px"  
                                objectFit="contain" 
                                maxH="50px"       
                                maxW="50px"       
                                borderRadius="md" 
                              />
                              <Text color={'black'} ml={1}>{item.title} x{item.quantity} </Text> 
                              <IconButton aria-label="Delete item" icon={<MdDelete color='red' />} onClick={() => handleRemoveFromCart(item.id)} variant="ghost" />
                            </Flex>
                          </Box>  
                        ))
                      ) : (
                        <Text>No items in the cart.</Text>
                      )}
                      <Button backgroundColor={'#85ff8d'} _hover={{ backgroundColor: "#41ff4e" }} width="100%" mt={4}>
                        Proceeding
                      </Button>
                    </PopoverBody>
                  </PopoverContent>
                </Popover>
              </ListItem>
              <ListItem>
                <Link as={RouterLink} to="/login" color={'#2D3748'} _hover={{ backgroundColor: "#000", color: '#fff' }}>
                  Login
                </Link>
              </ListItem>
              <ListItem>
                <Link as={RouterLink} to="/signup" color={'#2D3748'} _hover={{ backgroundColor: "#000", color: '#fff' }}>
                  Signup
                </Link>
              </ListItem>
            </>
          )}
        </UnorderedList>
      </Flex>
    </Box>
  );
};

if you need from me to provide more informations just let me know.

I have started webdevelopment and reached at backend. I was doing some express&ejs code but I’m getting some errors PleaseHelp

I am writing a code like basic instagram where i have some my own data –

{
  "cats": {
    "name": "cats",
    "followers": 25000,
    "following": 5,
    "posts": [
      {
        "image": "https://plus.unsplash.com/premium_photo-1677545182067-26ac518ef64f?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MXx8Y2F0c3xlbnwwfHwwfHx8MA%3D%3D&auto=format&fit=crop&w=800&q=60",
        "likes": 200,
        "comments": 17
      },
      {
        "image": "https://images.unsplash.com/photo-1592194996308-7b43878e84a6?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Mnx8Y2F0c3xlbnwwfHwwfHx8MA%3D%3D&auto=format&fit=crop&w=800&q=60",
        "likes": 312,
        "comments": 19
      },
      {
        "image": "https://images.unsplash.com/photo-1577023311546-cdc07a8454d9?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Nnx8Y2F0c3xlbnwwfHwwfHx8MA%3D%3D&auto=format&fit=crop&w=800&q=60",
        "likes": 1065,
        "comments": 200
      }
    ]
  },
  "dogs": {
    "name": "dogs",
    "followers": 75000,
    "following": 150,
    "posts": [
      {
        "image": "https://images.unsplash.com/photo-1598133894008-61f7fdb8cc3a?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Nnx8ZG9nc3xlbnwwfHwwfHx8MA%3D%3D&auto=format&fit=crop&w=800&q=60",
        "likes": 3000,
        "comments": 41
      },
      {
        "image": "https://images.unsplash.com/photo-1552053831-71594a27632d?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MTd8fGRvZ3N8ZW58MHx8MHx8fDA%3D&auto=format&fit=crop&w=800&q=60",
        "likes": 2500,
        "comments": 32
      },
      {
        "image": "https://images.unsplash.com/photo-1537151608828-ea2b11777ee8?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MjB8fGRvZ3N8ZW58MHx8MHx8fDA%3D&auto=format&fit=crop&w=800&q=60",
        "likes": 500,
        "comments": 6
      }
    ]
  }
}

This was my data.json file and i was writing code for it
this is my index.js file –

const express=require("express");
const app=express();
const path=require("path");
const port=8080;

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views"));

app.listen(port, ()=>{
    console.log(`Listening on port ${port}`);
});

let instaData= require("./data.json");

app.get("/ig/:username", (req, res)=>{
    console.log(instaData);
    let { username }= req.params;
    console.log(instaData.username);
    let data=instaData[username];
    console.log(data);
    if(data){
        res.render("instagram.ejs", data);}
     }else{
         res.render("error.ejs");
     }
});

my instagram.ejs file –

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile</title>
</head>
<body>
    <h2>This page belongs to @<%= data.name%></h2>
    <button>Follow</button>
    <button>Message</button>

    <p>Followers : <%= data.followers%> &nbsp; &nbsp;&nbsp;&nbsp; Following : <%= data.following%> </p>

    <hr/>

    <% for(post of data.posts){ %>
        <img src=" <%= post.image %>" alt="some img">
        <p>
            comments : <%= post.comments %> &nbsp; &nbsp;&nbsp;&nbsp;  likes : <%=post.likes%>
        </p>
    <% } %>
</body>
</html>

this is what i am getting as output at my terminal

at the browser its keep laoding and at the terminal it is showing me instaData[username] is undefined

what is this happening please help

Scale canvas/matrix and all transformations applied, to obtain better quality image in the canvas

A member from stackoferflow helped fix my script and he obtained a good result, but I still need some help.

I have a DIV that contains some other divs and in the end, an image.
This image is bigger in size, but has a smaller width/height set directly from CSS (3x times smaller, the number is irrelevant).
The image has CSS transformations applied to it (rotate/scale, translate).

enter image description here

The script creates a canvas, of the same size as the div, and draws the image in the canvas, CROPPING the outside part of it (filling it with white). Finally it draws the image in it’s normal position (with no rotation applied to it), but with the outside part, in white (so cropped).
It works perfect. The problem is that I would like to scale this canvas 3 times (or 5 times) to make it better quality, since my image is bigger (natural size), but it’s displayed smaller due to the CSS exact width/height set.

I tried rescaling (resizing) the canvas but it simply produces bad results, as it’s rescales a small image (losing a lot of quality).

I would like to modify the script, so it applied scaling on all steps based on a scale factor (let’s say SCALE_FACTOR=3).
In my example, the div size is 400×400 pixels, so the final canvas would be 1200×1200 pixels and the image would be drawn 3 times bigger, but in EXACTLY the same position (so the crop result is identical, just in higher quality).

I tried applying .scale on the matrix and inverse matrix, but it does not give the result I am looking for. Of course I increased containerWidth with *SCALE_FACTOR etc…

I would like to obtain this (but high quality draw, not rescale like I did now) .
enter image description here

Here is the code I am using:

<!DOCTYPE html>
<html>
<head>
<style>
body {
  font-family: Arial, sans-serif;
  margin: 20px;
}

.object-render--canvas {
  width: 400px;
  /* You can change this to any size */
  height: 400px;
  /* You can change this to any size */
  border: 2px solid #000;
  position: relative;
  overflow: hidden;
  margin-bottom: 20px;
}

 #dd6f9f50-780e-11ef-b763-11ebd40cd3a6 {
      width: 326px; /* Scaled-down width */
      height: 290.3px; /* Scaled-down height */
      transform: translate(230px, -130px) rotate(145deg) scale(1);
      transform-origin: center center;
      position: absolute;
      top: 0;
      left: 0;
    }

#buttons {
  margin-bottom: 20px;
}

#tempCanvases {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

#tempCanvases canvas {
  border: 1px solid #ccc;
}
</style>

</head>
<body>
<h1>Dynamic Image Transformation and Cropping</h1>
<div class="object-render--canvas">
  <img id="dd6f9f50-780e-11ef-b763-11ebd40cd3a6" src="https://i.sstatic.net/oJs20ysA.png" alt="Source Image">
</div>
<div id="buttons">
  <button id="processButton">Process</button>
  <button id="downloadButton" disabled>Download</button>
</div>
<h2>Temporary Canvases (For Debugging)</h2>

<script type='text/javascript'>
// Wait for the DOM to load
document.addEventListener('DOMContentLoaded', () => {
  const processButton = document.getElementById('processButton');
  const downloadButton = document.getElementById('downloadButton');
  
  let finalCanvas = null;
  let finalImageCanvas=null;

  processButton.addEventListener('click', () => {
    // Clear previous temporary canvases
    downloadButton.disabled = true;

    processCanvas();

    // Enable the download button
    downloadButton.disabled = false;
  });

  downloadButton.addEventListener('click', () => {
    if (!finalCanvas) return;

    // Convert the final canvas to a data URL
    const dataURL = finalCanvas.toDataURL('image/png');

    // Create a temporary link to trigger download
    const link = document.createElement('a');
    link.href = dataURL;
    link.download = 'processed_image.png';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });

  /**
   * Utility function to append a canvas with a label for debugging
   * @param {HTMLCanvasElement} canvas 
   * @param {string} label 
   */
   
  function processCanvas(){

    const sourceImage = document.getElementById('dd6f9f50-780e-11ef-b763-11ebd40cd3a6');
  // Step 1: Get container and image dimensions
    const container = document.getElementsByClassName("object-render--canvas")[0];
    const containerWidth = container.clientWidth;
    const containerHeight = container.clientHeight;

    const imageRenderedWidth = sourceImage.width;
    const imageRenderedHeight = sourceImage.height;
    

    // Step 2: Get computed styles of the image
    const style = window.getComputedStyle(sourceImage);
    const transform = style.transform;

    // Calculate the center of the image
    const centerX = imageRenderedWidth / 2;
    const centerY = imageRenderedHeight / 2;

    // If no transform is applied, set it to identity matrix
    const matrix = transform === 'none' ?
      new DOMMatrix() :
      new DOMMatrix(transform)
    
      // Apply the transform-origin
        .preMultiplySelf({ e: centerX, f: centerY })
        .multiply({ e: -centerX, f: -centerY })
    

    
    //this is the canvas where we revert transformations and crop image
    finalCanvas = document.createElement('canvas');
    finalCanvas.width = containerWidth;
    finalCanvas.height = containerHeight;
    finalCanvas.style.border="1px solid red";
    const ctx1 = finalCanvas.getContext('2d');


    ctx1.setTransform(matrix);
    // Draw the image transformed
    ctx1.drawImage(sourceImage, 0, 0, imageRenderedWidth, imageRenderedHeight);


    //above code draws the image, identical as in the div, after this line, we reset transformations and crop everything that is outside the canvas with white, and display the image in normal (non rotated, not css scaled) position.
    // Draw again, using the inverse transform
    ctx1.setTransform(matrix.inverse());
    // Replace the previous content by the new content
    ctx1.globalCompositeOperation = "copy";
    ctx1.drawImage(ctx1.canvas, 0, 0);

    // Fill with white below the current drawing
    ctx1.fillStyle = '#FFFFFF';
    ctx1.globalCompositeOperation = "destination-over"; // Draw below
    ctx1.resetTransform(); // No transform
    ctx1.fillRect(0, 0, finalCanvas.width, finalCanvas.height);
    
    
    
    

    // Append the canvas for debugging
    appendCanvas(finalCanvas, 'Result');
  }
  function appendCanvas(canvas, label) {
    const wrapper = document.createElement('div');
    const caption = document.createElement('p');
    caption.textContent = label;
    wrapper.appendChild(caption);
    wrapper.appendChild(canvas);
    document.body.appendChild(wrapper);
  }
});
</script>
</body>
</html>

How do I put a p5play script inside of my HTML webpage?

I have made a webpage for school and our teacher wants us to go out and learn how to do something new to add to it. I had this idea to take one of my p5play games and put it in to the website somehow, but I have zero clue where to start.

Im using codeHS to do this and I have tried making a file for the javaScript but it just prints out all of the code instead of the code actually doing anything

texture from a dynamically generated SVG in pixiJS v8

How can I create a texture from a dynamically generated SVG in pixiJS v8?

This worked in v7:

const testSVG = '<svg viewBox="0 0 100 100" width="7" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="50" /></svg>'
, texture = PIXI.Texture.from(testSVG)

but texture logs out as undefined in v8.

And this approach:

  const textureSource = PIXI.TextureSource.from(testsvg )
  const texture = PIXI.Texture.from(textureSource)

Throws this error:

Error: Could not find a source type for resource: <svg viewBox="0 0 100 100" width="7" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="50" /></svg>

Thanks!

Angular Infinite Scroll with sorted list results in endless loop

I’m working on an Angular project. I implemented an “infinite scroll” list utilizing IntersectionObvserver. Generally it works quite well and satisfying.

But there is one issue I couldn’t find a solution for so far.

The results to build the list are being sorted ascending.

In Angular this causes the problem that the HTML list is built upwards while the scrollbar remains at the same position that triggered the infinite scroll event, which causes the event to fire over and over and over again until the user scrolls away manually.

That the event is being fired as long as the infinite scroll trigger is in the viewport is desired behavior, because depending on the viewport height and user preferences it can’t be guaranteed that there will always be enough items to fill the whole page initially. New items must be loaded continously until the page is filled.

StackBlitz example

https://stackblitz.com/edit/angular-infinite-scroll-intersectionobserver

Scroll to the very end of the list to trigger the infinite scroll event. It will keep the scrollbar at the same position and firing the event while building the list upwards.

List is built upwards and the scrollbar remains at the same position

In the generateItems() function there is a call to sortItems(). When you disable this call the scrolling behavior of the infinite scroll list works properly. New items added to the list cause the list to grow and push the infinite scroll trigger out of the viewport.

CodePen example

When I implement the same infinite scroll logic using native JavaScript with jQuery it works as expected, even when the results are sorted.

https://codepen.io/mw-108/pen/ExqPKmG

Here the infinite scroll trigger is always pushed out of the viewport when the list is updated. This is what I expect.

Questions

Am I doing something wrong in Angular?

What can I do to reproduce the same result I see in the JavaScript / jQuery example in Angular?

JavaScript Date.now undefined [closed]

function save(save) {
    let timestamp = new Date();
    cookie.setCookie("test" + timestamp.now, save, 360);
}

I’m trying to make this code create a cookie named “test [timestamp here]” but its not working for some reason.. any ideas?

console difference. log in C# and javascript [closed]

What is the difference between “Console.log” with an uppercase letter in C#, for example, and “console.log” with a lowercase letter in Javascript, why do some methods begin with uppercase letters and others with lowercase letters?

documentation for the languages ​​and I still couldn’t find it

Pass data from node.js to .ejs js script variable

I must be overlooking something but I don’t manage to get a variable from node.js to pass on into a js script object/variable in .ejs.

I have a route:

app.get('/simulation', (req, res) => {
  console.log("simulation results route requested");
  hotels = [
    {
      hotel: 'Hotel Tevini ****superior'
    }
  ];
  console.dir(priceTravelers, {depth:null});
  res.render('simulation/simulation', {jsonData: hotels});
});

And I want that data to be parsed in to a variable in the .ejs file.
I have tried

const data = <%= jsonData %>;

in the .ejs but that does not seem to work.

Any thoughts?

I tried several things like data = JSON.parse(<%= jsonData %>);.
Stringify the data on render to send first and then parse on the .ejs side but that gives [object][object] back etc.