How to add and remove border on an element when an event occurs?

I want a border to be added and removed for an element when a certain event occurs.

In the example below, how do I make so that when I click on the p element a border is added to div which stays for a second and goes away.

The reason I am doing this is to draw the users attention to the element when an event takes place.

document.querySelector(".clickedelement").addEventListener("click", function (e) {
  // add and remove border on div
});
div {
  width: 100px;
  height: 100px;
  background-color: yellow;
  border-radius: 50%;
}
<p class="clickedelement">when this is clicked i want border added and removed (after 1s) on div below</p>
<div class=""></div>

When using window.fetch is there a way to actually “submit()” the form?

Say I have a web page and I want it to automatically “go to” some form. This sort of thing works fine:

script(type = 'text/javascript').
    var ff = document.createElement("form")
    document.body.appendChild(ff)

    var ii = document.createElement("input")
    ii.setAttribute("type","hidden")
    ii.setAttribute("height", 69)
    ff.appendChild(ii)

    ff.method = "POST"
    ff.action = window.location + "/someform"
    ff.submit()

However, it’s much easier to use fetch to send a form:

script(type = 'text/javascript').
    fetch("/someform", {
    method: "POST",
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({height: 69})
    })

However that does not actually “go to” the new page, /someform.

Is there actually a way to make fetch “go to” the form in question, rather than just fetch the results behind the scene?

P5JS camera 3 part turning

The code allows the user/camera to rotate along the y-axis. When either the left or right arrow key(s) are pressed, the camera rotates a specific number of degrees before it stops. If the down arrow key is pressed, it rotates in the opposite direction, looking forward again.

I want to make a 3-part turning system, where if I’m pointing in a direction, if I press the opposite key, the camera turns back forward, and if pressed again, it rotates the certain amount of degrees and stops.

(I would like to remove the down arrow function and implement it in the left and right arrow keys.)

Also, I’m calling all of this inside of the draw() function.
cam1 is in the setup() function

// camera operating code

cam1.lookAt(x, y, 0);

if(keyCode === LEFT_ARROW){
    x = x - 50;
  if( x < -200){
    x = -198
  }
}

if(keyCode === RIGHT_ARROW){
    x = x + 50;
  if(x > 200){
    x = 198;
  }
}

if(keyCode === DOWN_ARROW){
  if(x > 20){
    x = x - 50;
    if(x < 20){
      x = 0;
    }
  }
  if(x < 20){
    x = x + 50;
    if(x > 20){
      x = 0;
    }
  }
}
  
// camera operating code

I tried to split the down arrow function and use a lot of “if’s” and “else’s”, which didn’t really work..

and then I tried changing my variables into different functions and loops.. it was just really confusing..

what usually ended up happening, is when you pressed a key, it would constantly turn that certain amount of degrees, return to 0, and then turn the certain amount of degrees and so on.

How to handle with UUID scope variables to evaluate using Math.js?

Im using Math.js to evaluate string math expressions, each ‘variable’ represent an Input, wich have its own id (UUID).
so im setting this id’s to a ‘scope’ variable to receive key-value pair.

expressionScope: Record<string, number> = {
"ind_e101611e-33e0-426d-9cf8-e922d74b8a54": 998,
"ind_b7e5c845-0e83-4ca4-a90b-25d5f9cb06c5": 255

but if i evaluate something like

Math.evaluate("ind_e101611e-33e0-426d-9cf8-e922d74b8a54 + ind_b7e5c845-0e83-4ca4-a90b-25d5f9cb06c5" , expressionScope)

it will trigger an Error, because “e101611e” and “33e0e101611e” isnt a valid token from scope array.

the thing is: evaluate is ‘confusing’ the “-” from UUID with the real subtraction operator.What is a best way to deal with it instead of replacing “-” into “_” ?

How to monitor the changes of the dom elements in the parent and child components at the same time in React?

My current code like this:

const ComponentA = () => {
  const [elementA, setElementA] = useState(null)

  const setRefA = useCallback(node) => {
    setElementA(node)
  },[])

  return (
    <>
      <div ref={setRefA}>content a</div>
      <ComponentB elementA={elementA} />
    </>
  )
}

const ComponentB = ({ elementA }) => {
  const [elementB, setElementB] = useState(null)

  const setRefB = useCallback(node) => {
    setElementB(node)
  },[])

  useEffect(() => {
    if (elementA && elementB) {
      console.log('do something with both DOM nodes')
    }
  }, [elementA, elementB])

  return <div ref={setRefB}>content b</div>
}

Is this a reasonable implementation method, and will it violate the React pattern?

ComponentB is a public component that needs to be exposed to ComponentA and other components. Is using useEffect to listen to the element state change the only way in ComponentB? Are there methods that do not use useEffect?

Google Maps Javascript API Autocomplete vs. Browser Autofill

I am using Google Maps Javascript API Autocomplete in a form to make a user select an address. Great. However the browser’s autofill will fill the autocomplete field with an address. This would be fine if it triggered the drop down to open, or filled the entire street city state zip, but it only puts in the street number and name. This makes it so the user has to clear out the autofilled address and start typing it again to see the drop down of autocomplete options.

I thought of a few ideas to fix it using javascript, but there are no events triggered when the browser’s autofill is used, so any idea I can think of is out the window.

There HAS to be someone who thought up a clever way to resolve this issue. Please help!

Netlify Redirects Not Working for Forcing .html URLs

I’m running into an issue with my static site, and I could really use some help. Here’s the situation:

Project Structure:

My project is a simple HTML, CSS, and JS site with the following structure:

/my-site/
├── dist1/
│ └── about-us.html
├── dist2/
│ └── contact.html
├── dist3/
│ └── services.html
├── _redirects
├── netlify.toml
└── index.html

Goal:

I want to force all non-.html URLs to redirect to their .html counterparts, like this:

/dist1/about-us ➔ /dist1/about-us.html (301 Redirect)
What I Tried:

Disabled Pretty URLs:
I have unchecked the Pretty URLs setting in my Netlify dashboard.
Added _redirects File:
My _redirects file (located in the project root) contains:
/* /:splat.html 301

Added netlify.toml:

I also tried using a netlify.toml file with this configuration:

[[redirects]]
from = “/*”
to = “/:splat.html”
status = 301
force = true

Cleared Cache:

Cleared the build cache in Netlify.

Cleared my Cloudflare cache (I’m using Cloudflare as my DNS provider).
The Problem:

Despite all this, my non-.html URLs are still not redirecting. Both of these URLs are returning a 200 OK:

https://example.com/dist1/about-us
https://example.com/dist1/about-us.html
**What I Checked:

The _redirects and netlify.toml files are in the project root.
The build logs don’t show any errors related to the redirects.
I’ve cleared both Netlify and Cloudflare caches multiple times.
There are no conflicting page rules in Cloudflare.
What I Need Help With:

Why is Netlify ignoring my _redirects file and netlify.toml configuration?
How can I force the .html redirects to work consistently across my site?
Any guidance would be greatly appreciated!

Thanks in advance for your help!

How to replace plus/minus symbol in variable [closed]

I have a form field that can potentially contain the ± symbol.
I need to be able to parse that to determine upper and lower values.
I had originally been using the indexOf() function to attempt to check for the presence of the symbol but it was not working so I changed to use the jQuery.contains() and that does work.

However, I also need to be able to do a replace on that symbol and the javascript replace function does not find the symbol.
What options to I have that will work here?

Image edge transparency when using `drawImage` in combination with `setTransform`

I’d like to draw a red rectangle and an image on a HTML canvas. My goal is to completely cover the rectangle with the image, in combination with scaling all content using setTransform so the image fits the canvas. The issue I’m having is that the rectangle is still visible on the edges of the image.

I tried experimenting with the scale and it seems this is caused by rounding, as I’m scaling all content using a single setTransform call.

I can fix the issue by applying adjusted dimensions to both the rectangle and the image, so the resulting dimensions the rectangle and image are integer values. That works in Safari and Chrome, but it doesn’t in Firefox.

Here’s the reproduction code:

<div id="container" style="width: 838px; height: 446px;">
  <canvas id="canvas" style="width: 100%; height: 100%; background: white; display: block;"></canvas>
</div>
  const DPR = window.devicePixelRatio || 1;
  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');

  // Logical canvas size (matches physical pixels)
  const container = document.getElementById('container');
  const width = container.clientWidth * DPR;
  const height = container.clientHeight * DPR;
  canvas.width = width;
  canvas.height = height;

  // Desired content size
  const contentWidth = 3508;
  const contentHeight = 2480;

  // Compute scale to fit content inside canvas
  const scale = Math.min(width / contentWidth, height / contentHeight);
  console.log(scale);

  // Compute adjusted input size so output aligns to integers
  const targetOutputWidth = Math.round(contentWidth * scale);
  const targetOutputHeight = Math.round(contentHeight * scale);
  const adjustedWidth = targetOutputWidth / scale;
  const adjustedHeight = targetOutputHeight / scale;

  // Set transform and draw
  ctx.setTransform(scale, 0, 0, scale, 0, 0);

  // Determine to fix issue
  const fixIssue = false;

  // Draw background rect
  ctx.fillStyle = 'red';
  if (!fixIssue) {
    ctx.fillRect(0, 0, contentWidth, contentHeight);
  } else {
    ctx.fillRect(0, 0, adjustedWidth, adjustedHeight);
  }

  // Load and draw image
  const img = new Image();
  img.onload = () => {
    // ctx.imageSmoothingEnabled = false; // Uncommenting this doesn't help

    if (!fixIssue) {
      ctx.drawImage(img, 0, 0, contentWidth, contentHeight);

    } else {
      ctx.drawImage(img, 0, 0, adjustedWidth, adjustedHeight);
    }
  };
  img.src = `https://placehold.co/${contentWidth}x${contentHeight}`;

When fixIssue is set to false, this is what browsers display (make sure to view these screenshots at 100% to see the red rectangle at the edge of the image):

Chrome Safari Firefox
Chrome without fixIssue Safari without fixIssue Firefox without fixIssue

When setting fixIssue to true, the issue is fixed in Chrome and Safari but not in Firefox:

Chrome Safari Firefox
Chrome fixed Safari fixed Firefox fixed

You can see that the rectangle is still visible at the top of the image in Firefox.

How can I prevent this from happening? I tried disabling image smoothing which doesn’t help. I’d like to keep the single setTransform call as it’s convenient for scaling all content.

JavaScript error when change an HTML element with a tag in it [closed]

I;m trying to change an HTML element from “style” to “script” but when I have a tag in it, then I always get a browser console error and found no solution for this.

Browser Console Error:

Uncaught SyntaxError: Failed to execute ‘replaceChild’ on ‘Node’:
Unexpected token ‘<‘

HTML Demo code:

<div class="test-unit-1">
  <style>
    <video>
      <p>Some Stuff.</p>
    </video>
  </style>
</div>

JavaScript code:

var adUnits = document.querySelectorAll('[class^="test-unit"]');
adUnits.forEach(function(unit) {
    var styleElem = unit.querySelector("style");
    if (styleElem) {
        try {
            // Get the style content
            var styleContent = styleElem.textContent || styleElem.innerText;
                // Handle regular style content
                var script = document.createElement("script");
                var scriptContent = document.createTextNode(styleContent);
                script.appendChild(scriptContent);
                styleElem.parentNode.replaceChild(script, styleElem);
        } catch (error) {
            console.error('Error replacing style with script:', error);
        }
    }
});

External java script isn’t loading on my vue3 layout

So I am trying to move wordpress webpage (szczecinska.com.pl) to Laravel 12.x. I am using for that vue3 + inertia starting kit. But since I have very little experience with vue, and completely non in inertia, I bumped at some, I think, basic problem. I want to use front made with bootstrap 5 (already made for previous version of site), and backend with AdminLTE (which is using bootstrap 4). Because of that I need to use different javascripts for front layout, and different for backend layout. I succesed in creating front layout, but for some reason my admin panel layout don’t work how it supposed to (clicking on menu parent item don’t open list with child elements). I were able to check that it is something related to javascript (99% jquery) that isn’t loading like I expect him to. I downloaded AdminLTE by npm package, that contains necessary plugins too. My AdminLayout.vue looks like that:

<script setup lang="ts">
  import 'admin-lte/plugins/jquery/jquery.min.js';
  import 'admin-lte/plugins/bootstrap/js/bootstrap.bundle.min.js';
  import 'admin-lte/dist/js/adminlte.js';

  import Navbar from '../../components/Szczecinska/Backend/LayoutElements/Navbar.vue';
  import Sidebar from '../../components/Szczecinska/Backend/LayoutElements/Sidebar.vue';

  defineProps([
    'breadcrumbs',
    'activeBreadcrump',
    'pageTitle'
  ]);
</script>
<template>
    <div class="wrapper">
      <Navbar />
      <Sidebar />
      <!-- Content Wrapper. Contains page content -->
      <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
          <div class="container-fluid">
            <div class="row mb-2">
              <div class="col-sm-6">
                <h1 class="m-0">{{pageTitle}}</h1>
              </div><!-- /.col -->
              <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                  <li v-for="breadcrumb in breadcrumbs" class="breadcrumb-item" :key="breadcrumb.title">
                    <a href="{{ breadcrumb.link }}">
                      {{ breadcrumb.title }}
                    </a>
                  </li>
                  <li class="breadcrumb-item active">{{ pageTitle }}</li>
                </ol>
              </div><!-- /.col -->
            </div><!-- /.row -->
          </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->
        <!-- Main content -->
        <div class="content">
          <div class="container-fluid">
            <slot></slot>
          </div><!-- /.container-fluid -->
        </div>
        <!-- /.content -->
      </div>
      <!-- /.content-wrapper -->

<!-- Main Footer -->
<footer class="main-footer">
  <!-- To the right -->
  <div class="float-right d-none d-sm-inline">
  </div>
  <!-- Default to the left -->
  <strong>Copyright &copy; Tomasz Burzyński.</strong> All rights reserved.
</footer>
</div>
<!-- ./wrapper -->
</template>

The Sidebar.vue:

<script setup lang="ts">
    import Brand from './SidebarParts/Brand.vue';
    // import User from './SidebarParts/User.vue';
    import Menu from './SidebarParts/Menu.vue';
    import { computed } from 'vue'
    import { usePage } from '@inertiajs/vue3'

    const page = usePage()

    const user = computed(() => page.props.auth.user)
</script>
<template>
    <!-- Main Sidebar Container -->
    <aside class="main-sidebar sidebar-dark-primary elevation-4">
        <Brand />
        <div class="sidebar">
            <!-- <User /> -->
            <Menu />
        </div>
    </aside>
</template>

And finally, Menu.vue that contains element which doesn’t work for me:

<script setup lang="ts">
    import MenuSection from './MenuSection.vue';
    import MenuItem from './MenuItem.vue';
</script>
<template>
    <!-- Sidebar Menu -->
        <nav class="mt-2">
        <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="true">
            <li class="nav-item">
                <a href="#" class="nav-link active">
                    <i class="nav-icon fas fa-tachometer-alt"></i>
                    <p>
                    Starter Pages
                    <i class="right fas fa-angle-left"></i>
                    </p>
                </a>
                <ul class="nav nav-treeview">
                    <li class="nav-item">
                    <a href="#" class="nav-link active">
                        <i class="far fa-circle nav-icon"></i>
                        <p>Active Page</p>
                    </a>
                    </li>
                    <li class="nav-item">
                    <a href="#" class="nav-link">
                        <i class="far fa-circle nav-icon"></i>
                        <p>Inactive Page</p>
                    </a>
                    </li>
                </ul>
            </li>
            <li class="nav-item">
            <a href="#" class="nav-link">
                <i class="nav-icon fas fa-th"></i>
                <p>
                Simple Link
                <span class="right badge badge-danger">New</span>
                </p>
            </a>
            </li>
        </ul>
    </nav>
    <!-- /.sidebar-menu -->
</template>

I tried to move imports to app.ts (altought that isn’t what I want, but I tried to check what will help me), without results. I checked if paths are without mistakes, and compared my html to AdminLTE life demo and example files. I still can’t see what I am doing wrong.

I belive I misunderstood somehow how I should add javascripts to layout if I want it to work only on admin pages, but I just can’t find the proper way to do that.

I will be gratefull for any tips that can help me understand my mistake.

Sequelize magic method not adding foreign key

Sequelize’s createXXXXX method doesn’t seem to be adding the necessary foreign key.

This running the following code for these two models gives me a “notNull Violation: Seat.office_id cannot be null” error. The docs seem to indicate that that column should be automatically populated, no?

class Seat extends Model {
    static init(sequelize) {
        super.init(
            {
                id: {
                    autoIncrement: true,
                    type: DataTypes.INTEGER,
                    allowNull: false,
                    primaryKey: true,
                },
                office_id: {
                    type: DataTypes.INTEGER,
                    allowNull: false,
                },
                name: {
                    type: DataTypes.STRING,
                    allowNull: true,
                },
            },
            {
                sequelize,
                tableName: "seat",
                schema: "public",
                timestamps: false,
                indexes: [
                    {
                        name: "seat_pkey",
                        unique: true,
                        fields: [{ name: "id" }],
                    },
                ],
            },
        );
    }

    static associate(models) {
        this.belongsTo(models.Office, {
            foreignKey: "office_id",
            as: "office",
        });
    }
}

class Office extends Model {
    static init(sequelize) {
        super.init(
            {
                id: {
                    autoIncrement: true,
                    type: DataTypes.INTEGER,
                    allowNull: false,
                    primaryKey: true,
                },
                title: {
                    type: DataTypes.STRING,
                    allowNull: true,
                },
                description: {
                    type: DataTypes.STRING,
                    allowNull: true,
                },
            },
            {
                sequelize,
                tableName: "office",
                schema: "public",
                timestamps: false,
                indexes: [
                    {
                        name: "office_pkey",
                        unique: true,
                        fields: [{ name: "id" }],
                    },
                ],
            },
        );
    }

    static associate(models) {
        this.hasMany(models.Seat, {
            foreignKey: "office_id",
            as: "seats",
        });
    }
}

let office = await Office.findByPk(1);
let seat = await Seat.build({
  name: "Test",
});

office.createSeat(seat);

Drupal 10 CKEditor 5 Custom Plugin: “plugins.map is not a function” Error

I’m developing a custom CKEditor 5 plugin for Drupal 10.4.5. The JavaScript for the plugin seems to be loading correctly, and I’ve defined it in my module’s .ckeditor5.yml file. The plugin aims to add a “Small Text” button to the toolbar, wrapping selected text in tags.

However, I’m encountering the following JavaScript error in the browser console when trying to load the CKEditor 5 instance (both on node edit pages and where a CKEditor 5 instance might be present elsewhere):

Uncaught TypeError: plugins.map is not a function
    at selectPlugins (ckeditor5.js?swXXXX:XXX)
    at Object.attach (ckeditor5.js?swXXXX:XXX)
    ... (rest of the stack trace)

Here are the relevant parts of my module’s files:

Module folder is here: /web/modules/custom/small_text_ckeditor

/web/modules/custom/small_text_ckeditor/small_text_ckeditor.info.yml:

name: Small Text CKEditor
type: module
description: Provides a 'Small Text' plugin for CKEditor 5.
core_version_requirement: ^10
dependencies:
 - drupal:ckeditor5

/web/modules/custom/small_text_ckeditor/small_text_ckeditor.libraries.yml:

small_text:
  version: VERSION
  js:
    js/small_text.js: {}
  dependencies:
    - core/ckeditor5
    - core/ckeditor5-plugin

/web/modules/custom/small_text_ckeditor/small_text_ckeditor.ckeditor5.yml:

small_text_ckeditor_small_text:
  ckeditor5:
    plugins:
      SmallText: {}
  drupal:
    label: 'Small Text'
    library: small_text_ckeditor/small_text
    toolbar_items:
      smallText:
        label: 'Small Text'
    elements:
      - '<small>'

/web/modules/custom/small_text_ckeditor/js/small_text.js:

/**
 * @file
 * Defines the 'Small Text' plugin for CKEditor 5.
 */

(function (Drupal) {
    Drupal.behaviors.smallTextCKEditor = {
      attach: function (context, settings) {
        const editorPromise = Drupal.CKEditor5Instances.get('edit-body-0-value');
  
        if (editorPromise) {
          editorPromise.then(editor => {
            class SmallText {
              static get pluginName() {
                return 'SmallText';
              }
  
              init() {
                editor.model.schema.register('small', {
                  allowWhere: '$text',
                  isInline: true,
                });
                editor.conversion.for('downcast').elementToElement({ model: 'small', view: 'small' });
                editor.conversion.for('upcast').elementToElement({ view: 'small', model: 'small' });
              }
            }
            editor.commands.add('smallText', {
                execute: () => {
                  const model = editor.model;
                  const selection = model.document.selection;
                  model.change(function (writer) {
                          const ranges = selection.getRanges();
                          for (const range of ranges) {
                              const innerText = Array.from(range.getItems('inline'));
                              const isSmall = innerText.every(item => item.hasAttribute('small'));
                              for (const item of innerText) {
                                  if (isSmall) {
                                      writer.removeAttribute('small', item);
                                  } else {
                                      writer.setAttribute('small', true, item);
                                  }
                              }
                          }
                      });
                  },
                refresh: function() {
                    const model = editor.model;
                    const selection = model.document.selection;
                    const firstRange = selection.getFirstRange();
                    if (firstRange) {
                      const selectedElements = Array.from(firstRange.getItems('inline'));
                      this.isEnabled = selectedElements.length > 0 || !selection.isCollapsed;
                      this.value = selectedElements.every(element => element.hasAttribute('small'));
                    } else {
                      this.isEnabled = false;
                      this.value = false;
                    }
                  }
              });
  
            editor.ui.componentFactory.add('smallText', locale => {
              const button = editor.ui.componentFactory.create('button', locale);
              button.set({
                label: 'Small Text',
                icon: '<svg viewBox="0 0 20 20"><text x="50%" y="50%" dominant-baseline="central" text-anchor="middle" style="font-size: 10px;">sm</text></svg>',
                tooltip: 'Small Text',
                withText: false,
              });
              this.listenTo(button, 'execute', () => {
                editor.execute('smallText');
              });
              this.listenTo(editor, 'change:selection', () => {
                button.isEnabled = editor.commands.get('smallText').isEnabled;
                button.isOn = editor.commands.get('smallText').value;
              });
              return button;
            });
          });
        }
      }
    };
  })(Drupal);

I’ve tried various configurations in the .ckeditor5.yml file, including listing SmallText as an array item, but the plugins.map is not a function error persists.

What is the correct way to declare a custom CKEditor 5 plugin in a Drupal 10 module to avoid this error?

Ai voice assistant project [closed]

I am working to build an Ai Voice Assistant by using the htmland css for fortend and javascript for backend..So I need a full source code about this project.
My suggestions is that My Ai voice Assistant give me a answer of my any questions..
Example.. I ask What time is it so Ai assistant reply me the current time.. Similarly i ask present day, past day, future day with dates, weather in any city or country, route finding with traffic and time, give me shortest path to go, Open YouTube in YouTube page i ask close so the YouTube page is closed and in YouTube page i ask search anything so my ai assistant searching for me… And so on features..