How do i put a variable on my web page in JavaScript [closed]

My program has a button that moves when you click it and adds one to your score however the score doesn’t display correctly. Here is my HTML:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <p id="demo">Score: 0</p>
    <button id="move-button" onclick="moveButton()"></button>
    <script src="js.js"></script>
</body>
</html>

And here is the JavaScript:

let score = 0;
function moveButton()
{
    score= score + 1
    document.getElementById("demo").innerText = "Score:", score;
    const btn = document.getElementById('move-button');
    const maxX = window.innerWidth - btn.offsetWidth;
    const maxY = window.innerHeight - btn.offsetHeight;

    const randomX = Math.floor(Math.random() * maxX);
    const randomY = Math.floor(Math.random() * maxY);

    btn.style.left = `${randomX}px`
    btn.style.top = `${randomY}px`
    
}

This is the css code in case it helps:

body{
    display: flex;
    overflow: hidden;
}
button{
    position: absolute;
    align-self: center;
    height: 15px;
}

What can i do to make the score display correctly?

let score = 0;
function moveButton()
{
    score= score + 1
    document.getElementById("demo").innerText = "Score:", score;
    const btn = document.getElementById('move-button');
    const maxX = window.innerWidth - btn.offsetWidth;
    const maxY = window.innerHeight - btn.offsetHeight;

    const randomX = Math.floor(Math.random() * maxX);
    const randomY = Math.floor(Math.random() * maxY);

    btn.style.left = `${randomX}px`
    btn.style.top = `${randomY}px`
    
}
body{
    display: flex;
    overflow: hidden;
}
button{
    position: absolute;
    align-self: center;
    height: 15px;
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <p id="demo">Score: 0</p>
    <button id="move-button" onclick="moveButton()"></button>
    <script src="js.js"></script>
</body>
</html>

log the title of a html page with zombie in node.js

I’m trying to log the title of the index.html page with zombie.js, but I don’t seem to be able to make it work.

const Browser = require('zombie')
const browser = new Browser()

browser.visit('http://0.0.0.0:3000/', () => {
    console.log(browser.text("title"))
})

Below is the terminal output.

$ node --watch zombie_tests

Completed running 'zombie_tests'

Since “welcome” is the title of the index page, I anticipate “welcome” as the result.

Alpha Mask on image using Chakra UI to create an opacity gradient

I want to create a simple opacity gradient on an image. I’m using Next.JS with Chakra UI and Tailwind CSS for the front-end design, and I cannot find a way to do it.

This is a result that I did on figma using an image and a box with an alpha mask and a linear gradient:
See this image example

This is what I currently have: Image of my current web-app

This is my current code:

loginPage.js

import { Box, Flex, Image, Card } from "@chakra-ui/react";
export default function LoginPage() {
  return (
    <Flex
      paddingX={0}
      marginX={0}
      width={"100%"}
      justifyContent={"space-between"}
    >
      <Box>
        <Image src="./img/bordeaux.png"></Image>
      </Box>

      <Flex direction={"column"} justifyContent={"space-evenly"}>
        <Card.Root>
          <Card.Header />
        </Card.Root>
        <Card.Root>
          <Card.Header />
        </Card.Root>
      </Flex>
    </Flex>
  );
}

page.js

import Header from "./pages/header";
import LoginPage from "./pages/loginPage";

export default function Home() {
  return (
    <>
      <Header />
      <LoginPage />
    </>
  );
}

layout.js

import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { ColorModeProvider } from "@/components/ui/color-mode";
import { Provider } from "@/components/ui/provider";

const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
});

export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({ children }) {
  return (
    <html suppressHydrationWarning>
      <body>
        <Provider>
          <ColorModeProvider
            className={`${geistSans.variable} ${geistMono.variable} antialiased`}
          >
            {children}
          </ColorModeProvider>
        </Provider>
      </body>
    </html>
  );
}

I tried to:

  • Have an image with a linear gradient background
  • Have a box with linear gradient and an image inside it with blend mode multiply
  • Have a box on top of an image with a linear gradient.

But nothing works…

Thanks!

Next.js not rendering clean HTML source: a problem for SEO and accessibility?

Next.js (V15, App router, SSR) does not render HTML as initially structured.

It renders <template> tags inside the structure, and further in the source, the content in a hidden <div>.

Thus, there is no structure in the source HTML, all attempts to be semantically correct are quite vain: all you see before JS is an empty structure and then a bunch of unstructured data.

**Isn’t that a problem for SEO and/or accessibility?

Is it taken for granted that JS will be ran by search engines and a11y tools? Then why even bother doing SSR?

Here are two examples of what Next.js (V15, App router) renders as the initial HTML for server components.

Main content:

JSX

<body>
                <main id="main">
                    {children}
                </main>
</body>

Renders:

<body>

<main id="main">
        <template id="P:1"></template><!--$--><!--/$--><!--$--><!--/$-->
</main>

<!-- ... -->
<!-- This is supposed to be #main content -->
<div hidden id="S:1">
    <div>
        <div class="cards-scroller-titles"></div>
        <div class="cards-scroller">
            <div class="card"><h1 class="card-title">À propos</h1>
                <div class="about-grid">
                    <section class="presentation">
                        <div class="">
                            <div><span><p>Je suis développeur freelance, basé sur Nantes et spécialisé en <strong>Symfony</strong>, <strong>architecture back-end</strong>, <strong>React/Next.js</strong> et <strong>intégration soignée</strong>.</p>

<!-- ... -->
</body>

Some components:

JSX:

<ul className="section-content">
                        {data.parcours.map((job: string) =>
                            <TimedItem item={job}/>
                       )}
                    </ul>

Renders:

<ul class="section-content">
                    <li class="timed-item">
                        <time class="date">
                            <template id="P:14"></template>
                        </time>
                        <h4 class="title">
                            <template id="P:15"></template>
                        </h4>
                    </li>
                    <li class="timed-item">
                        <time class="date">
                            <template id="P:16"></template>
                        </time>
                        <h4 class="title">
                            <template id="P:17"></template>
                        </h4>
                    </li>
</ul>
<!-- ... -->
<div hidden id="S:14">2010+</div>
<script>$RS("S:14", "P:14")</script>
<div hidden id="S:15">Développeur / architecte web freelance</div>
<script>$RS("S:15", "P:15")</script>
<div hidden id="S:16">2010+</div>
<script>$RS("S:16", "P:16")</script>
<div hidden id="S:17">Contributions à des projets open-source (modules Symfony, plugins PhpStorm, Mastodon...)</div>
<script>$RS("S:17", "P:17")</script>
<div hidden id="S:18">2006 — 2012</div>

دریافت داده از API محصولات انجام می‌شود ولی چیزی در کامپوننت React رندر نمی‌شود [closed]

چه مشکلی پیش اومده؟
داده‌ها از API به‌درستی دریافت می‌شن (توی console.log(data) نشون داده می‌شن)، اما وقتی می‌خوام اون‌ها رو داخل JSX رندر کنم، چیزی روی صفحه نشون داده نمی‌شه.

چه کاری می‌خواستی انجام بدی؟
می‌خواستم یک لیست از محصولات رو از API که با Express ساختم دریافت کنم و داخل یک کامپوننت React نمایش بدم.

چه چیزهایی رو تست کردم؟
fetch به /api/products انجام می‌شه و جواب می‌گیرم.

از useEffect برای گرفتن دیتا استفاده کردم.

داده‌ها به‌درستی در useState ذخیره می‌شن.

ولی توی map که برای رندر کردن محصولات استفاده کردم، چیزی نشون داده نمی‌شه.

Angular 18 computed not a function

I’m using Angular 18 with signals.
My CalculationService basically calculates a price based on some parameters.
Building with ng serve doesn’t throw any errors neither does VSCode, however my browser throws the following:

 ERROR TypeError: this.doorAmount is not a function at Object.calculatePricePerDoor [as computation] (calculation.service.ts:52:48)

And my component doesn’t load.

calculation.service.ts

import { computed, Injectable, signal } from '@angular/core';
import {
  basePrice,
  basePricePerDay,
  basePricePerDoor,
  minutesPerDoor,
  stepPrice,
} from '../consts';

@Injectable({
  providedIn: 'root',
})
export class CalculationService {
  #price = signal(0);
  #basicDoorAmount = signal(0);
  #electroDoorAmount = signal(0);
  #automaticDoorAmount = signal(0);

  doorAmount = computed(this.countDoorAmount);
  price = computed(this.#price);
  pricePerDoor = computed(this.calculatePricePerDoor);
  priceStep = computed(this.calculatePriceStep);
  hours = computed(this.countHours);
  days = computed(this.countDays);

  constructor() {
    this.calculatePrice();
  }

  calculatePrice() {
    this.#price.set(
      basePrice +
        this.pricePerDoor() +
        basePricePerDay * this.days() +
        this.priceStep()
    );
  }

  setBasic(amount: number) {
    this.#basicDoorAmount.set(amount);
  }

  setElectro(amount: number) {
    this.#electroDoorAmount.set(amount);
  }

  setAutomatic(amount: number) {
    this.#automaticDoorAmount.set(amount);
  }

  private calculatePricePerDoor() {
    const { basic, electro, automatic } = this.doorAmount();
    return (
      basic * basePricePerDoor.basic +
      electro * basePricePerDoor.electro +
      automatic * basePricePerDoor.automatic
    );
  }

  private calculatePriceStep() {
    const { basic } = this.doorAmount();
    if (basic < 21) return 0;
    if (basic < 101) return stepPrice[100];
    if (basic < 251) return stepPrice[250];
    if (basic < 1001) return stepPrice[1000];
    return stepPrice[1001];
  }

  private countDoorAmount() {
    return {
      basic: this.#basicDoorAmount(),
      electro: this.#electroDoorAmount(),
      automatic: this.#automaticDoorAmount(),
    };
  }

  private countHours() {
    const { basic, electro, automatic } = this.doorAmount();
    return (
      (basic * minutesPerDoor.basic +
        electro * minutesPerDoor.electro +
        automatic * minutesPerDoor.automatic) /
      60
    );
  }

  private countDays() {
    return Math.ceil(this.countHours() / 7.5);
  }
}

showDirectoryPicker FileSystemDirectoryHandle’s getFile() doesn’t work when file path in > 231 chars

Here is my code

async function getFilesHandles(dirHandle) {
    const handles = [];
    for await (const entry of dirHandle.values()) {
      if (entry.kind === 'directory') {
        handles.push(...(await this.listAllFilesAndDirs(entry)));
      } else {
        handles.push(entry);
      }
    }
    return handles;
  }

const directoryHandle= await window.showDirectoryPicker({ mode: 'read' });
const handles = await getFilesHandles(directoryHandle);

await handles[0].getFile(); // <-- doesn't work when path+filename length > 231 chars

Throws the followinf Error

Uncaught NotFoundError: A requested file or directory could not be found at the time an operation was processed.

Is there a way to work around this ?

OS: Windows
Browser: Chrome (Version 134.0.6998.178 – 64 bits)

App Store/TestFlight upload error: Missing dSYM files for Razorpay and Hermes, and Invalid Executable due to bitcode

I’m facing issues while uploading an iOS build for a React Native app (using Hermes and Razorpay) to App Center and TestFlight. Even after cleaning and rebuilding multiple times, I encounter the following validation and symbol upload errors.
The archive did not include a dSYM for the Razorpay.framework with the UUIDs [UUIDs].
Ensure that the archive’s dSYM folder includes a DWARF file for Razorpay.framework with the expected UUIDs.

The archive did not include a dSYM for the hermes.framework with the UUIDs [UUIs].
Ensure that the archive’s dSYM folder includes a DWARF file for hermes.framework with the expected UUIDs.

What I’ve tried:
Cleaned the project and derived data.

Re-archived using Xcode (Product > Archive).

Verified debug_information_format is set to dwarf-with-dsym.

Attempted to manually find and include missing dSYM files.

Checked for bitcode settings in Xcode and in Podfile.

Searched for the UUIDs in dwarfdump output – not found.
React Native with Hermes enabled

Razorpay iOS SDK integration

Xcode 16.x

Archive being uploaded via App Center or manually to TestFlight

How to add current page URL to the voiceFlow AI agent Transcripts

How can i add the URL of the page (where the user opened the chatbot) to the Transcript of VoiceFlow AI agent? This will help us to understand which website pages users are asking their Questions! I tried the following but did not work:

(function(d, t) {
  var v = d.createElement(t), s = d.getElementsByTagName(t)[0];
  v.onload = function() {
    window.voiceflow.chat.load({
      verify: { projectID: 'XXXXCURRENT_IDXXXX' },
      url: 'https://general-runtime.voiceflow.com',
      versionID: 'production',
      launch: {
        event: {
            type: "launch",
            payload: {
            current_url: window.location.href
            }
        }
        },
        autostart: false
    });
  }
  v.src = "https://cdn.voiceflow.com/widget/bundle.mjs"; v.type = "text/javascript"; s.parentNode.insertBefore(v, s);})(document, 'script');

and

if (last_event) {
  current_url = last_event.payload.current_url
} else {
  current_url = "i dunno"
}

It seems last_event is not found and also not sure how this could add the url to the Transcript.

Javascript cropped and resized image to input field

Ik use a jquery/javascript for cropping and resizing image and that works fine. The problem is that I want to upload the cropped image via a normal input (file) so that my server sided laminas script can process the adjusted image. How to get the adjusted image into the input field of my form? I can receive a base64 encoded image, but I want to receive it in the “normal” way.
In the script the dataUrl is composed like below:

var dataUrl     = (options.canvasImageOnly == true) ? $(canvasImageOnly)[0].toDataURL(image.data('mime')) : $(canvas)[0].toDataURL(image.data('mime'))

It (seems) that the image is put in the input over here (but that is encoded I suppose)

 var json       = JSON.stringify($.extend({data: dataUrl},obj));
                        $(input).after($('<input type="text" name="' + $(input).attr('name') + '_values" class="final" />').val(json));
                        
                        $(input).data('required',$(input).prop('required'));
                        $(input).prop('required',false);
                        $(input).wrap('<form>').parent('form').trigger('reset');
                        $(input).unwrap();
                        
                        $(element).find('.tools .saving').remove();
                        $(element).find('.tools').children().toggle();
                        
                        _self.imageFinal();

SEO freindly URLs [closed]

I have a PHP site that using the folllowing URL structure

example.com/search/category.php?=general

example.com/search/location.php?=london

I’d like to make them more SEO and aesthetically freindly by changing them to

example.com/search/general

example.com/search/bikes-for-sale-in-london

What’s the easiest way of doing this?

Thanks

Save order of custom entities in selection field

Let’s say I have two custom entities:

  • Dish
  • Ingredient

The entities have a many-to-many relation with extra field: ingredient_position:

#[ORMEntity]
class Dish
{
    #[ORMOneToMany(
        mappedBy: 'dish',
        targetEntity: DishIngredient::class,
        cascade: ['all'],
    )]
    private Collection $dishIngredients;
}

#[ORMEntity]
class Ingredient
{
    #[ORMOneToMany(
        mappedBy: 'ingredient',
        targetEntity: DishIngredient::class,
        cascade: ['all'],
    )]
    private Collection $dishIngredients;
}

#[ORMEntity]
class DishIngredient
{
    public function __construct(
        #[
            ORMManyToOne(
                targetEntity: Dish::class,
            ),
            ORMJoinColumn(nullable: false),
        ]
        private Dish $dish,
        #[
            ORMManyToOne(
                targetEntity: Ingredient::class,
            ),
            ORMJoinColumn(nullable: false),
        ]
        private Ingredient $ingredient,
        
        #[ORMColumn(type: Types::INTEGER)]
        private int $ingredientPosition = 0,
    ) {}
}

I’d like to be able to add existing Ingredients when adding/editing Dish but the ingredients have to be stored in the order I set in the admin form.

I tried to set up a ingredient_selection field in sulu_admin and it works, when I select ingredients and store them in the database, but when I load the Dish in the admin form, the ingredients don’t show up – Sulu tries to load ingredients from the ingredients’ endpoint: /admin/api/ingredients?locale=en&ids=9,10&page=1&flat=true: in that case the ids are the IDs of the DishIngredient entity, but I’m not able to load the ingredients.

Laravel N+1 when accessing a pivot relationship and the related model (unit)

I got n+1 query while working with my models and pivot

Recipe.php:

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function ingredients(): BelongsToMany
    {
        return $this->belongsToMany(Ingredient::class)
            ->using(IngredientRecipe::class)
            ->withTimestamps()
            ->withPivot(['quantity', 'unit_id']);
    }

IngredientRecipe.php (Pivot):

    public function unit(): BelongsTo
    {
        return $this->belongsTo(Unit::class);
    }

Ingredient.php:

    public function recipes(): BelongsToMany
    {
        return $this->belongsToMany(Recipe::class);
    }

Unit.php:

    public function ingredient_recipes(): HasMany
    {
        return $this->hasMany(IngredientRecipe::class);
    }

What am I trying to do:

In my user-profile page I want to show a list of recipes for owner (user). Every recipe has ingredients() which are in pivot table with additionall columns quantity and unit_id

Code:

In my ProfileController.php I am using this code:

    public function show_profile(User $user)
    {
        $userRecipes = $user->recipes()->with('ingredients', 'guideSteps')->get();

        return view('user.user-profile', compact('user', 'userRecipes'));
    }

Problem:

Laravel doesn’t know that pivot->unit_id is related to the Unit model, so every I am accessing pivot->unit, it makes a separate query to the units table.

In debugbar I am getting 15 duplicated queries:

select * from users where users.id = 1 limit 1

select * from units where units.id = 3 limit 1

select * from units where units.id = 3 limit 1

… 12 more

And a problem is in this place:


   @foreach($userRecipes as $recipe)
       <x-recipe-card :recipe="$recipe"/>
   @endforeach

---------------inside component recipe-card:------------------------

        @foreach($recipe->ingredients as $ingredient)
            <div>
                <span>{{ $ingredient->name }}</span>
                <div></div>
                <span>{{ $ingredient->pivot->quantity . ' '. $ingredient->pivot->unit->name}}</span>
            </div>
        @endforeach

(errno: 150 “Foreign key constraint is incorrectly formed “)”)

I am trying to create scheduleUser migration but this error is popping out although I am using the same standards I’ve been taught. I created another schema it gave me the same error. I made sure the relationships is written in a correct way still having the same error. I am using Laravel v.12.

This is the scheduleUser migration:

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('scheduelusers', function (Blueprint $table) {
            
            $table->id();
            // $table->unsignedBigInteger('studentId')-> primary()->nullable() -> from(100000);
            $table -> string('firstName');
            $table -> string ('middleName');
            $table -> string ('lastName');
            $table -> string ('email')-> unique();
            $table -> string ('password');
            $table -> string ('phone')-> unique();
            $table -> foreignId('role_id')->constrained();
            
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('scheduelusers');
    }
};

This is the function I am using in scheduleusers migration for the relationship:

    public function role()
    {
        return $this->belongsTo(Role::class);
    }
    
}

This is the role migration:

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table -> string('role');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('roles');
    }
};

This is the function in role model for the relationship:

    public function scheduleusers()
    {
        return $this->hasMany(ScheduleUser::class);
    }
}

Troubleshooting Laravel Website Issues After Hosting on Shared Server

I have developed a Laravel website and uploaded it to the live server. Since a Laravel website cannot be hosted directly on shared hosting, I created an ASSET_URL in the .env file and moved the index.php file, which was inside the public folder, to the main directory of the website. I also changed the default session time of 120 in the .env file to SESSION_LIFETIME=600 and also have the setting SESSION_SECURE_COOKIE =true. Now, the website is working fine. However, when I keep the website open in a browser for a couple of days, I face issues like some buttons not working, some links not working, and the page reloading when I click a button. However, when I change the browser or open it in incognito mode, the website works perfectly. I don’t want to clear the cache all the time because the end user may not be aware of browser cache, etc. How to resolve this