Why won’t onmouseover=” ” work in this specific area?

I’m trying to make a hamburger menu, I have made the actual hamburger, but want to add a border, or maybe slightly increase the size of each div in the hamburger or some other fancy effect.

When I write function that targets this it doesn’t work, however when i set it to change the body backgroundColor it works, or if i set it to open a prompt it works.

what works:

Display: none;
background-color: 'red';
<div class="nav-ham" onmouseover="prompt()">

What isn’t working:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="nav-ham" onmouseover="hamHover()">
        <div class="ham-bars"></div>
        <div class="ham-bars"></div>
        <div class="ham-bars"></div>
    </div>


<script src="script.js"></script>
</body>
</html>

CSS

body {
    background-color: #F9F7F7;
}

.nav-ham {
    position: absolute;
    top: 0;
    right: 5%;
    width: 50px;
    height: 50px;
}

.ham-bars {
    width: 100%;
    height: 15%;
    border-radius: 10%;
    background-color: #112D4E;
}

.nav-ham :nth-child(1) {
    position: absolute;
    top: 15%;
}

.nav-ham :nth-child(2) {
    position: absolute;
    top: 45%;
}

.nav-ham :nth-child(3) {
    position: absolute;
    top: 75%;
}

JS

function hamHover() {
    document.getElementsByClassName('ham-bars').style.height = '20%';
}

I can only come to the conclusion that I’m making a typo I’m not spotting or i have a fundamental misunderstanding of the language, which is most likely given i only just completed the course last week.

I imagine it’s something basic, but I am new to this so forgive me.

Threlte stopPropagation on click event

Using Threlte i can create two shapes in a file like so :

<T.Mesh on:click={(e) => console.log("little shape") } >
</T.Mesh>

<T.Mesh on:click={(e) => console.log("bigger shape") } >
</T.Mesh>

In order to avoid the second shape to tigger it’s event on a click on the small one, I can add e.stopPropagation() like so :

<T.Mesh on:click={(e) => {console.log("little shape"); e.stopPropagation() }}>
</T.Mesh>

Issue comes when I wants to create a separate component out of my little shape. stopping propagation inside the other file is pointless, and stopImmediatePropagation() isn’t recognized as a function.

App.svelte
<LittleShape
  on:click >
>/LittleShape>

<T.Mesh
   on:click={(e) => {console.log("bigger shape") }} >
</T.Mesh>
LittleShape.svelte
<T.Mesh></T.Mesh>

How can I split my file while preventing propagation

Thanks in advance!

Applying an ‘active’ class to a button isn’t working

I have an image portfolio with filter buttons at the top. When the user selects one of these filters, the button should change colour to show that it is selected. I created a script to handle this, but it’s not working and I’m unsure why it’s not.

HTML:

<div class="dp-projects-button-container" id="dp-projects-button-container" style="margin-bottom: 35px;">

<button id="btn" class="btn active" onclick="filterSelection('all')"> SHOW ALL</button>

<button id="btn" class="btn" onclick="filterSelection('residential_multiunit')"> RESIDENTIAL: MULTI-UNIT</button>

<button id="btn" class="btn" onclick="filterSelection('residential_privatehouses')"> RESIDENTIAL: PRIVATE HOUSES</button>

<button id="btn" class="btn" onclick="filterSelection('offices_fitout')"> OFFICES & FIT-OUT</button>

<button id="btn" class="btn" onclick="filterSelection('sports_leisure')"> SPORTS & LEISURE</button>

<button id="btn" class="btn" onclick="filterSelection('education_childcare')"> EDUCATION & CHILDCARE</button>

<button id="btn" class="btn" onclick="filterSelection('admin_finance')"> ADMINISTRATIVE & FINANCIAL</button>

<button id="btn" class="btn" onclick="filterSelection('retail')"> RETAIL</button>

<button id="btn" class="btn" onclick="filterSelection('industrial_warehousing')"> INDUSTRIAL & WAREHOUSING</button>

<button id="btn" class="btn" onclick="filterSelection('restaurant_public_houses')"> RESTAURANTS & PUBLIC HOUSES</button>

<button id="btn" class="btn" onclick="filterSelection('hotels')"> HOTELS</button>

<button id="btn" class="btn" onclick="filterSelection('health_agedcare')"> HEALTH & AGED CARE</button>
</div>

JAVASCRIPT:

var btnContainer = document.getElementById("dp-projects-button-container");
var btns = btnContainer.getElementsByClassName("btn");

for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function(){
        var current = document.getElementsByClassName("active");
        current[0].className = current[0].className.replace(" active", "");
        this.className += " active";
    });
}

(I have CSS which applies the colour to .btn.active)

I’ve tried playing around with ‘class’ vs ‘id’, but to no avail. I’ve also triple-checked my class names, css properties and spelling, also to no avail.

I’m fairly new to JavaScript so any help is really appreciated, thanks

Window and Leveling doesn’t update to image displayed in Javascript

I have these html file that I is a simple window to load an image and to use two sliders to adjust the window and leveling of the loaded image. The image loads and the sliders adjust but the image doesn’t update as the sliders move.

I am very new to js and html so it’s probably something obvious

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Window and Level Adjustment</title>
    <style>
        #imageCanvas {
            border: 1px solid black;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>

    <canvas id="imageCanvas" width="512" height="512"></canvas>
    <br>
    <label for="window">Window: </label>
    <input type="range" id="window" min="0" max="1000" value="500">
    <br>
    <label for="level">Level: </label>
    <input type="range" id="level" min="0" max="1000" value="500">

    <script>
        const canvas = document.getElementById('imageCanvas');
        const ctx = canvas.getContext('2d');

        const windowSlider = document.getElementById('window');
        const levelSlider = document.getElementById('level');

        let originalImageData;
        let imageData;

        // Load the image
        function loadImage() {
            const img = new Image();
            img.src = 'output_image.png';  // Load the uploaded image
            img.onload = function () {
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                originalImageData = new Uint8ClampedArray(imageData.data);

                // Calculate min and max intensity for dynamic slider range
                let minIntensity = 255, maxIntensity = 0;
                for (let i = 0; i < originalImageData.length; i += 4) {
                    let intensity = originalImageData[i];
                    if (intensity < minIntensity) minIntensity = intensity;
                    if (intensity > maxIntensity) maxIntensity = intensity;
                }

                console.log("Min intensity:", minIntensity);
                console.log("Max intensity:", maxIntensity);

                windowSlider.min = 0;
                windowSlider.max = maxIntensity - minIntensity;
                windowSlider.value = (windowSlider.max - windowSlider.min) / 2;

                levelSlider.min = minIntensity;
                levelSlider.max = maxIntensity;
                levelSlider.value = (levelSlider.max - levelSlider.min) / 2;

                applyWindowLevel();
            };
        }

        function applyWindowLevel() {
            const window = parseInt(windowSlider.value);
            const level = parseInt(levelSlider.value);
            const minVal = level - (window / 2);
            const maxVal = level + (window / 2);

            // Create a copy of the original image data to work on
            imageData.data.set(originalImageData);

            for (let i = 0; i < originalImageData.length; i += 4) {
                let intensity = originalImageData[i];
                let adjusted = (intensity - minVal) * (255 / (maxVal - minVal));
                adjusted = Math.min(Math.max(adjusted, 0), 255);

                imageData.data[i] = imageData.data[i + 1] = imageData.data[i + 2] = adjusted;
            }

            ctx.putImageData(imageData, 0, 0);
        }

        windowSlider.addEventListener('input', applyWindowLevel);
        levelSlider.addEventListener('input', applyWindowLevel);

        loadImage();

    </script>

</body>
</html>

This is output Displayed Image

validate and convert input string in react

I have one form in react in which I have used formik and Yup library for validations. I have requirement that input field should allow only lowercase alphanumeric values which allow hyphen and length between 2 to 30 characters. Also if user is typing Uppercase letters or space then convert that string to lowercase and replace space with hyphen.
e.g. for input like “Shop name123” should convert to “shop-name123”

formik validation is as follows:

postfix: Yup.string()
                  .required(message.ENTER_POSTFIX)
                  .matches(new RegExp("^[a-z0-9- ]{2,30}$"), {
                    message: message.PUBLIC_URL_POSTFIX_INVALID,
                  })

on change of that field I have following code

<Field
                          type="text"
                          className="form-control"
                          style={{ marginTop: "32px" }}
                          value={values.postfix? values.postfix: ""}
                          name="postfix"
                          onChange={(e) => {
                            setFieldValue(
                              "postfix",
                              tranformStrToVar(e.target.value)
                            );
                          }}
                        />

method tranformStrToVar as follows

export function tranformStrToVar(str) {
  let newStr = "";
  if (str) {
    newStr = str.replace(/s+/g, "-").toLowerCase();
    newStr.match(/[^/]+/g).join("-");
  }
  return newStr;
}

With above code working for some cases and getting failed if input has only “—–” etc. That also should not allowed.

How should I validate and convert input at same time and get valid, required input having lowercase alphanumeric seperated by hyphen having character length between 2 to 30 ?

Please help and guide. Thanks

Express Cookie Sent With Header and Saved in Storage but After Reload they are gone

I’ve searched almost every topic about this issue but still could not fixed the problem. Set-Cookie is avaliable in response headers, see below, with a little warning. I am using http therefore i have to set secure to false. I even tried “SameSite=lax|strict” but still could not solve the problem. Also the cookies is presence in the application tab but when I change my url or refresh it the cookies are removed.

I start request with the function below and after this function I am sending the cookies with options configured. I’ve also shared cors options policy below.

http://localhost:3000/ this is my url, I am also aware an issue that it can also caused because a front-end and back-end domain are different. Im not acquinted with web so deeply I dont know how do I check domains are the same.

By the way I am using chrome version 127 and on macos.

enter image description here

const signInHandler = async function(e){
try {
    await axios({
        method: "POST",
        url: "http://127.0.0.1:3000/api/v1/users/login",
        data:{
            name: userName.value,
            password: password.value
        },
        withCredentials: true
    });
    
    
    // window.setTimeout(() => {
    //     location.assign("/");
    // },500);

} catch (error) {
    console.log(error);
    
}

}

const sendToken = function(user, res){
const token = createJWTToken(user);

const cookieOptions = {
    expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000),
    httpOnly: true,
    secure: false,
    sameSite: "None"
}

res.cookie("jwt", token, cookieOptions);  

Below are my cors options.

const corsOptions = {
origin: true,
credentials: true
}

app.use(cors(corsOptions));

Is there a way to implement D3.js in Odoo?

I have managed to make some charts using d3.js but I wanted to put them into Odoo. I managed to get a dashboard run using Chart.js but d3.js is more complete for me. I loaded the d3.js but the charts aren’t showing.

This is the d3.js javascript’s I’m using. I resorted to pastebin because I don’t know what else could I add for this issue. Please bear with me. But I don’t really know why it is not showing…

Dynamically change padding in Vue js 3

Hello I want to change padding based on my selected locale, since div width is changing.

  <div
    class="input-group modal-check-show show-modal"
    :style="paddingLeft"
  >
  . . .
  </div>

const EnPaddingLeft = ref('padding-left: 27%;')
const DePaddingLeft = ref('padding-left: 28%;')
const SrPaddingLeft = ref('padding-right: 33% !important;')

const setPaddingLeft = computed(() => {
  let padding
  if (Tr.currentLocale === 'en') {
    padding = EnPaddingLeft
  } else if (Tr.currentLocale === 'de') {
    padding = DePaddingLeft
  } else if (Tr.currentLocale === 'sr') {
    padding = SrPaddingLeft
  } else {
    padding = EnPaddingLeft
  }
  return padding
})
const paddingLeft = setPaddingLeft

missing padding style

When I change computed to method it shows up at div tag, but it doesn’t change padding when I change locale.

My function that changes the elements background color isn’t working but works fine when changing the documents background color?

I’m using a switch statement to determine which button is being pressed, they both work with the same function when changing the documents background color, however, when I pass in the actual element and target it within the function and attempt to change it’s background color nothing is happening.

Changing the background color of the actual document works fine, but changing the background color of elements passed into the function is not working.

<div class="gender-toggle">
        <div class="toggle">
          <div id="male-toggle">
            <p>Male</p>
          </div>
          <div id="female-toggle">
            <p>Female</p>
          </div>
        </div>
</div>
const maleToggle = document.getElementById('male-toggle').addEventListener('click', changeGenderClick);
const femaleToggle = document.getElementById('female-toggle').addEventListener('click', changeGenderClick);

function changeGenderClick(event){
  const genderId = event.target.id;
  switch(genderId){
    case 'male-toggle':
      changeGender(femaleToggle);
      break;
    case 'female-toggle':
      changeGender(femaleToggle);
    break;
  }
}

function changeGender(currentGender){
  currentGender.style.backgroundColor = 'red';
};

how to get a line number in contenteditable div [closed]

I’m encountering an issue in my Vue 3 project where I need to determine the line number where the cursor is located in contenteditable div. This should work not only when typing but also when clicking anywhere within the text.

I’ve searched through many forums but only found solutions related to character offsets, not line numbers.

JavaScript Array of object get the data not present in other array

need an help I’ve two array which I needed to filte

const arr1 = [
    {
        "id": "processType",
        "name": "Conceptual Target State Process Model",
        "display_name": "Conceptual Target State Process Model",
        "checked": true
    },
    {
        "id": "processType",
        "name": "Current State Process Map",
        "display_name": "Current State Process Map",
        "checked": true
    },
    {
        "id": "processSubType",
        "name": "Current State Process Model",
        "display_name": "Current State Process Model",
        "checked": true
    },
    {
        "id": "processSubType",
        "name": "Current State Process Model (MCA)",
        "display_name": "Current State Process Model (MCA)",
        "checked": true
    }
]

const arr2 = [
    {
        "id": "processType",
        "name": "Current State Process Map",
        "display_name": "Current State Process Map",
        "checked": true
    }
]
 const filteredElements = arr1.filter(function(obj) {
        return !arr2.some(function(obj2) {
            return obj.name === obj2.name;
            //         ^             ^
        });
    });
console.log(filteredElements);

My expected output is

[
    { id: "processType",  name: "Current State Process Map", display_name: "Current State Process Map", checked: true
    },
    { id: "processSubType", name: "Current State Process Model", display_name: "Current State Process Model", checked: true
    },
    { id: "processSubType", name: "Current State Process Model (MCA)", display_name: "Current State Process Model (MCA)", checked: true
    }
]

Not sure what’s going wrong, I need to filter based on id & name
I’m filtering arr1 and using some checking for the name.

Socket.io not receiving data properly in React and Node JS

`I am trying to build a connection between a web application and a frontend using socket.io. I want it so that anytime I click on a button, I receive the JSON data that is being sent from the server side (web app) to the client (frontend). The server side is built with express/node and the client is built with react.

I click on the first button, and the JSON message “hello” appears. When I click “done with JSON”, I do not get another JSON message and instead get “Done with JSON” Anyone know how to solve this?

//////server side
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');



const app = express();
const server = app.listen(8080);
const io = require('socket.io')(server, {
    cors: {
      origin: '*',
    }
});
PORT = 8080;


app.get('/', (req, res) => {
    res.send('Socket.IO Server Running');
});

io.on('connection', (socket)=>{
    console.log("Connected");

      //this messsage is sent and received by the client
    const firstJson = {message:"hello"};
    socket.emit("receiveJson", firstJson);

    socket.on('jsonProcessed', () => {
        console.log('Client has processed the first JSON.');
        setTimeout(() => {
                  //this message is not received by the client
            const secondJson = { message: 'This is your second JSON!' };
            socket.emit('receiveJson', secondJson);
        }, 1000); // 1-second delay
    });
    
    socket.on('disconnect', ()=>{
        console.log('User disconnected');
    });
});



//Client side
`import React, {useRef, useState, useEffect} from 'react';
import { useNavigate } from 'react-router-dom';
import io from 'socket.io-client';
const Male = ({title})=>{
    const navigate = useNavigate();
    const socket = io('http://localhost:8080');

   
        const [jsonData, setJsonData] = useState(null);

        useEffect(()=>{
            socket.on('connect',()=>{
                console.log('Connection to server established');
            })
            socket.on('receiveJson',(data)=>{
                console.log('Received JSON from server: ', data);
                setJsonData(data);

            })
            return()=>{
                console.log("Disconnected from socket");
                socket.disconnect();
            }
        },[]);

        const handleJsonProcessing = () =>{
            console.log('Emitting jsonProcessed event');
            
            socket.emit('jsonProcessed');
            setJsonData(null);
        };
return(

</div>
                        {jsonData ? (
                <div>
                    <pre>{JSON.stringify(jsonData, null, 2)}</pre>
                    <button onClick={handleJsonProcessing}>Done with JSON</button>
                </div>
            ) : (
                <p>No JSON data received.!!</p>
            )}
);
};

It might also help if I show my console statements, which come up here:log statements

Vanilla JS in Vite can not detect web components

I’ve used npm create vite to create a vanilla JS project. I want to implement web components. This is my instruction as follow:

export class Header extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    const template = document.getElementById(
      "headerComponent"
    ) as HTMLTemplateElement;
    if (template) {
      const content = template.content.cloneNode(true);
      this?.appendChild(content);
    }
  }
}

customElements.define("my-header", Header);

I have imported this class in main.ts:

import { Header } from "./components/Header";

And this is index.html:

<template id="headerComponent">
  <h1>Header</h1>
  <p>Header is a component.</p>
</template>

<my-header></my-header>

But after opening the console, nothing is being shown in <my-header></my-header> tag.

What is the problem? What should I do?

Any help will be appreciated!

how to `getElementById` for an element inside a modal?

I have a webpage with a button. clicking the button opens a modal. inside this modal there’s a (Django) form. it has few inputs and some buttons (including a submit button).

  1. my form is: <form method="post" id="backupCreateForm" action="/backup/create/"> ...</form>
  2. its parent, the modal is : <div class="modal fade in" id="createModal" tabindex="-1" role="dialog" aria-labelledby="createModalLabel" aria-hidden="true">

I can’t seem to select the submit button within the form element with document.getElementById, it returns undefined. how can I select it?

<div class="modal fade" id="createModal" tabindex="-1" role="dialog" aria-labelledby="createModalLabel" xit
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createModalLabel">Create Form</h5>
            </div>
            <div class="modal-body">
                <form method="post" id="backupCreateForm" action="{% url 'backup_create' %}">
                </form>
            </div>
        </div>
    </div>
</div>

backupCreateForm:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-success" id="submitButton">Create</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</form>

my final goal is to add some extra functionality to the button (an api call) alongside actually submitting the form (I want to keep it in the template, and not in Django views/models)

P.S one idea is to programmatically submit the form with something like:

  document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('myform');
    form.addEventListener('submit', function(event) {
      event.preventDefault();
      submitForm();
    });
  });

  function submitForm() {
    const form = document.getElementById('myform');
    const formData = new FormData(form);

    fetch('{% url "form_submit" %}', {
      method: 'POST',
      body: formData,
      headers: {
        'X-CSRFToken': '{{ csrf_token }}'
      }
    })
    .then(response => response.json())
    .then(data => {
      // Handle the response from the server
      console.log(data);
      if (data.success) {
        // Call the API
        callAPI();
      } else {
        // Handle form errors
        console.error(data.errors);
      }
    })
    .catch(error => {
      // Handle any errors
      console.error(error);
    });
  }

  function callAPI() {
    fetch('/api/endpoint/', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then(data => {
      // Handle the API response
      console.log(data);
    })
    .catch(error => {
      // Handle any errors
      console.error(error);
    });
  }

but how can I do the same thing without writing the form submission manually?