Setting active-class to work across multiple independent v-lists in vue 3

I’m unable to make navigation selections using active-classes to work properly across multiple independent navigation v-list items in Vue 3.

Here is a reference to the navigation setup:

V-List 1: Item 1 (can be active)

V-List 1: Item 2 (can be active)

……………………………

V-List 2: Item 1 (cannot be active) – Used for on expanding sub items actions.

—->V-List 2: Sub-Item 1 (can be active)

End goal is to only have one item that can be active in an active state (and thus selected).

Example: If [V-List 1: Item 1] is active/selected then [V-List 1: Item 2] & [V-List 2: Sub-Item 1] cannot be selected.

Example 2: If [V-List 2: Sub-Item 1] is selected then [V-List 1: Item 1] & [V-List 1: Item 2] cannot be selected.

<div>
    <v-list nav active-class="activeNav">
        <v-list-item title="V-List 1: Item 1" value="Item1"></v-list-item>
        <v-list-item title="V-List 1: Item 2" value="Item2"></v-list-item>
    </v-list>

    <div v-if="session.navOption == 'Something'">
        <Vlist2-Nav :menu="menuItems" />
    </div>
</div>

/*import component*/
import Vlist2-Nav from "@/components/ui/vlist2-Nav.vue";

vList2-Nav.vue file:

<template>
    <v-list nav active-class="activeNav">
        <v-list-group v-for="item in V-List2Obj.menu" :key="item.title" :id="getId(item.title)">
            <template>
                //V-List 2: Item 1
                <v-list-item:title="item.title"></v-list-item>
            </template>
            <template v-if="!close">
                //V-List 2: Item 2
                <v-list-item v-for="subItems in item.items" :key="subItems.title" :title="subItems.title"></v-list-item>
            </template>
        </v-list-group>
    </v-list>
</template>

Any help is greatly appreciated!

scroll method in javascript is not working

scroll method not working but ı can use style.left and get it done. How can i use the scroll method and get the same result ?

HTML:

<div class="wrapper">
      <div id="prev">
        <i class="fa-solid fa-caret-left"></i>
      </div>
      <div class="slider">
        <div class="slide" style="background-image: url(./img1.jpg)">
          SLIDE 1
        </div>
        <div class="slide" style="background-image: url(./img2.jpg)">
          SLIDE 2
        </div>
        <div class="slide" style="background-image: url(./img4.jpg)">
          SLIDE 3
        </div>
        <div class="slide" style="background-image: url(./img5.jpg)">
          SLIDE 4
        </div>
      </div>
      <div id="next">
        <i class="fa-solid fa-caret-right"></i>
      </div>
    </div>
    <script
      src="https://kit.fontawesome.com/66df44010b.js"
      crossorigin="anonymous"
    ></script>

CSS:

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap');

* {
  border: 0;
  margin: 0;
  padding: 0;
  outline: 0;
  list-style: none;
  text-decoration: none;
  box-sizing: border-box;
}

body {
  background-color: #333;
  min-height: 100vh;
  width: 100%;
  font-size: 12px;
  font-family: 'Poppins';
  display: flex;
  align-items: center;
  justify-content: center;
}

.wrapper {
  width: 800px;
  height: 400px;
  border: 1px solid #777;
  position: relative;
  overflow: hidden;
}

#prev,
#next {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #eee;
  border-radius: 100%;
  font-size: 18px;
  cursor: pointer;
  z-index: 999;
  position: absolute;
  top: calc(50% - 15px);
}

#prev {
  left: 15px;
}
#next {
  right: 15px;
}

.slider {
  width: fit-content;
  display: flex;
  height: 400px;
  position: relative;
  left: 0;
  transition: 0.5s all ease;
}

.slide {
  width: 800px;
  height: 400px;
  background-size: cover;
  background-position: center center;
  background-attachment: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-family: 'Poppins', sans-serif;
  font-size: 36px;
  font-weight: bold;
}

JAVASCRIPT:

let counter = 0
const prev = document.querySelector('#prev')
const next = document.querySelector('#next')
const slider = document.querySelector('.slider')
const wrapper = document.querySelector('.wrapper')
const max = document.querySelectorAll('.slide').length - 1

function sliderFunc() {
  if (counter < max) {
    counter++
    console.log(counter)
    slider.style.left = '-' + 800 * counter + 'px'
    // ` ${-800*counter}px`
  } else {
    counter = 0
    slider.style.left = '-' + 800 * counter + 'px'
  }
}

let timer = setInterval(sliderFunc, 3000)

wrapper.addEventListener('mouseover', () => {
  clearInterval(timer)
  console.log('üzerinde')
})
wrapper.addEventListener('mouseout', () => {
  timer = setInterval(sliderFunc, 3000)
  console.log('durdu')
})

next.addEventListener('click', sliderFunc)

prev.addEventListener('click', () => {
  if (counter >= 0) {
    counter--
    console.log(counter)
    slider.style.left = '-' + 800 * counter + 'px'
  }
})

My JavaScript code above is working fine. I attempted to achieve the same result using a different approach, namely the scroll method, but it didn’t work, and it also didn’t give any error messages.

let counter = 0
const prev = document.querySelector('#prev')
const next = document.querySelector('#next')
const slider = document.querySelector('.slider')
const wrapper = document.querySelector('.wrapper')
const max = document.querySelectorAll('.slide').length - 1
let count = 0

console.log(wrapper.offsetWidth)
console.log(slider.offsetWidth)

function sliderFunc() {
  counter++
  slider.scroll({
    top: 0,
    left: -(wrapper.offsetWidth * counter),
    behavior: 'smooth',
  })
}
next.addEventListener('click', sliderFunc)

This is not working… How should I use the scroll method?

How can i make my snake movement not delayed

i am making a snake game, by myself but i ran into a problem when i pressed my keys my interval pauses for a major time, i dont want it to pause i want it to continue going on

   const trackMovement = () => {
        let direction
        const catchError = (e) => {
            // cells that are places on the border
            if (e instanceof TypeError) {
                location.reload()
            } else {
                location.reload()
            }
        }
        let movementInterval;
        const movePlayerMinus = (num) => {
            try {
                const newIndex = randomGreenIndex - num;
                // Check if the new index is within the grid boundaries and not hitting the right wall
                // when you divide by 16 all the left cells - num of the wall have a remainder of 15
                // This checks to see if a new row has started
                if (newIndex >= 0 && newIndex % 16 === 15) {
                    location.reload()
                } else {
                    playerGreenCell.classList.remove(snakeColor);
                    randomGreenIndex = newIndex;
                    playerGreenCell = cellArray[randomGreenIndex];
                    playerGreenCell.classList.add(snakeColor);
                }
            } catch (e) {
                catchError(e);
            }
        };

        const movePlayerPositive = (num) => {
            try {
                const newIndex = randomGreenIndex + num;
                // Check if the new index is within the grid boundaries and not hitting the left wall
                // when you divide by 16 all the right cells + num of the wall have no remainder
                // this checks to see if a new row has started
                if (newIndex < cellArray.length && newIndex % 16 === 0) {
                    location.reload()
                } else {
                    playerGreenCell.classList.remove(snakeColor);
                    randomGreenIndex = newIndex;
                    playerGreenCell = cellArray[randomGreenIndex];
                    playerGreenCell.classList.add(snakeColor);
                }

            } catch (e) {
                catchError(e);
            }
        };
        document.addEventListener("keydown", (e) => {
            if (movementInterval) {
                clearInterval(movementInterval);
            }
            switch (e.key) {
                case "ArrowUp":
                case "w":
                case "W":
                    movementInterval = setInterval(() => movePlayerMinus(16), 200)
                    break;
                case "ArrowDown":
                case "s":
                case "S":
                    movementInterval = setInterval(() => movePlayerPositive(16), 200)
                    break;
                case "ArrowRight":
                case "d":
                case "D":
                    movementInterval = setInterval(() => movePlayerPositive(1), 200)
                    break;
                case "ArrowLeft":
                case "a":
                case "A":
                    movementInterval = setInterval(() => movePlayerMinus(1), 200)
                    break;
                default:
                    console.log("not working")
            }
        });


    };

https://github.com/MuhammaduBarry/Snake-Game – is my github, i am using vite, if you want to test it out you can do npm run dev in the terminal. thank you in advanced

When i press my keys it slows down or just stops if the interval is slow enough, i think i am doing it wrong but i just need a little guidance.

JavaScript touch event listeners on iOS do not register quick swipes

Im implementing simple swipe events with touchstartandtouchend its working fine on Androis but on IOS 13, 14, 15 it`s registering swipes only if you make them slow. Here is my js code maybe you can spot my issue or now sollution.

const carousel_wrapper = document.querySelector(".carousel");
const carousel = document.querySelector(".wheel-container");
const slides = document.querySelectorAll(".slide");
const controlLinks = document.querySelectorAll(".controls-container a");

let touchStartY = 0;
let accumulatedDeltaY = 0;
let threshold = 0;

function updateCarousel(deltaY, threshold) {
  accumulatedDeltaY += deltaY;

  // Check if the accumulated delta exceeds the threshold
Math.abs(accumulatedDeltaY) >= threshold
? (() => {
    const currentIndex = getCurrentIndex();

    // Calculate the target slide based on scroll direction
    const targetIndex = calculateTargetIndex(currentIndex);

    // Update carousel rotation and active slides
    rotateCarousel(targetIndex);
    activeSlideChanger(targetIndex);

    // Reset the accumulated delta
    accumulatedDeltaY = 0;
  })()
: null;

}

// Get current active element index
function getCurrentIndex() {
  return Array.from(controlLinks).findIndex((control) =>
    control.classList.contains("active")
  );
}


function calculateTargetIndex(currentIndex) {
  const scrollDirection = Math.sign(accumulatedDeltaY);
  return scrollDirection > 0
    ? Math.min(currentIndex + 1, controlLinks.length - 1)
    : Math.max(currentIndex - 1, 0);
}

// Rotate carousele 
function rotateCarousel(targetIndex) {
  const rotationAngle = targetIndex * 90;
  carousel.style.transform = `rotate(${rotationAngle}deg)`;
  slides.forEach((slide, slideIndex) => {
    const slideRotation = -rotationAngle;
    slide.style.transform = `rotate(${slideRotation}deg)`;
  });
}

// Change active slide
function activeSlideChanger(targetIndex) {
  document.querySelector(".slide.active").classList.remove("active");
  const activeSlide = document.querySelector(
    `.slide:nth-child(${controlLinks[targetIndex].dataset.index})`
  );
  activeSlide.classList.add("active");
  document.querySelector("a.active").classList.remove("active");
  controlLinks[targetIndex].classList.add("active");
}

// Add control on wheel scroll (desktop)
carousel_wrapper.addEventListener("wheel", (event) => {
  const deltaY = event.deltaY;
  threshold = 200;
  updateCarousel(deltaY, threshold);
});

//Add control on touch start (mobile)
document.addEventListener("touchstart", function (event) {
  threshold = 0;
  touchStartY = event.touches[0].clientY;
  accumulatedDeltaY = 0;
}, false);

// Add control on touch end (mobile)
document.addEventListener("touchend", function (event) {
  const touchEndY = event.changedTouches[0].clientY;
  const deltaY = touchEndY - touchStartY;
  updateCarousel(-deltaY, threshold);
}, false);

Tried adding stuff like: html { touch-action: manipulation; } and some other solutions, but nothing seems to work for me.

Error: cannot find module. any suggestions?

i am trying to make and use a local module using node js. i have written all code taking help by angela yu’s course and it is giving me a cannot find module error. this is code written in my date.js file:

console.log(module);

function getDate(){

    let today = new Date();

  let options = {
    weekday : "long",
    day : "numeric", 
    month : "long" 
  }; 

    let day = today.toLocaleDateString("en-US", options);

    return day;
}
 

This is the code written in my app.js file:

const express = require("express");
const bodyp = require("body-parser");
const date = require(__dirname + "/date.js");

const app = express();

let items = ["Play basketball", "Perform theatre", "Study web-development"];
let workitems = [];

app.set('view engine', 'ejs');

app.use(bodyp.urlencoded({extended: true}));

app.use(express.static("public"));








app.get("/", function(req, res){

  res.render('list', {listtitle: day, newitems: items});

});

app.post("/", function(req, res){
  let item = req.body.todo;

  if(req.body.list == "Work"){
    workitems.push(item);
    res.redirect("/work");
  }
  else{
    items.push(item);
    res.redirect("/");
  }

});








app.get("/work", function(req, res){

  res.render('list', {listtitle: "Work List", newitems: workitems})

});

app.get("/about", function(req, res){

  res.render("about");
})












app.listen(3000, function(){

  console.log("Server is running at port 3000.");
}); 

so when i saw this is not working, i googled and from what i understood the solution given was using

module.exports = getDate //in date.js file

and then

const date = require(“./date.js”) //in app.js file

so i used both these yet there was an error. any suggestions how to remove this error?

Closing all windows from within the browser in Electron 28.2.2

Looked at:

I’m using Electron 28.2.2 and all of the above is outdated for me (no way to enable remote).

require("electron") is returning undefined for remote and app in the browser window. Here is my browser initialization:

const window = new BrowserWindow({
    width: 1024,
    height: 640,
    menuBarVisible: false,
    autoHideMenuBar: true,
    titleBarStyle: "hidden",
    webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
    },
});
window.loadFile("src/index.html");

Here is my browser script:

const { app: application } = require("electron");

export class HeaderNavigation {
    constructor() {
        // Close button
        this.closeButton = document.querySelector("#navigationBar #close");
        this.closeButton.addEventListener("click", e => {
            application.quit();
        });
    }
}

how to replace all instances of quotation marks-comma-quotation marks in a string with just a comma using Regex and javascript?

I’m trying to remove all instances of quotation marks-comma-quotation marks in a string “,” and replace them with just a comma, but I’m having trouble with the Regex. In other words, wherever there is a “,” in my string, I want to replace it with just , :

newOutput.replace(/","/g, ","); //does not get rid of them all

mouseenter / mouseleave solution that doesn’t trigger when mouse enters the smaller second element positioned in the first element

Here is a simple html+css+js code

var myDiv = document.getElementById('myDiv');

myDiv.addEventListener('mouseenter', function() {
  console.log('Mouse entered the div');
});

myDiv.addEventListener('mouseleave', function() {
  console.log('Unfortunately this message happens when we enter the smaller div');
});
#myDiv {
  width: 300px;
  height: 300px;
  background-color: yellow;
  position: absolute;
}
#smaller {
  border: 1px solid red;
  width: 100px;
  height: 100px;
  position: absolute;
  top: 100px;
  left: 100px;
}
<div>
  <div id="myDiv"></div>
  <div id="smaller">
    
  </div>
</div>

The issue here is mouseleave triggers when the mouse appears above the second element. Any nice and simple solution to avoid that? Tried another events. No luck.

P.S. JS solution is preferable. CSS hover is not the way to go for my case.
The important note – divs are on the same level (the second div is not a child of the first div).

Login failing when using correct credentials with MongoDB and Express Server

When i am logging in with the correct credentials it is saying they are invalid
and i can not figure out why.

auth.routes.js

    const express = require('express');
    const router = express.Router();
    const bcrypt = require('bcryptjs');
    const jwt = require('jsonwebtoken');
    const User = require('../models/user.model.js'); // 
    
    // User registration endpoint
    router.post('/register', async (req, res) => {
        const { username, email, password } = req.body;
        console.log(`Registration attempt for username: ${username}, email: ${email}`); // Log the attempted registration details
        try {
            let user = await User.findOne({ email });
            if (user) {
                console.log(`User already exists with email: ${email}`); // Log if user already exists
                return res.status(400).json({ msg: 'User already exists' });
            }
    
            console.log(`Creating new user with email: ${email}`);
            user = new User({
                username,
                email,
                password
            });
    
            const salt = await bcrypt.genSalt(10);
            user.password = await bcrypt.hash(password, salt);
    
            await user.save();
            console.log(`User created successfully: ${user.id}`);
    
            const payload = {
                user: {
                    id: user.id
                }
            };
    
            jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: 360000 }, (err, token) => {
                if (err) {
                    console.error(`Error generating JWT for user: ${email}`, err);
                    throw err; // Log and throw the error if JWT generation fails
                }
                console.log(`JWT generated for user: ${email}`);
                res.json({ token });
            });
        } catch (err) {
            console.error(`Server error during registration for username: ${username}, email: ${email}`, err.message);
            res.status(500).send('Server error');
        }
    });
    
    
    // Simplified User login endpoint with detailed diagnostic logging
    router.post('/login', async (req, res) => {
        const { email, password } = req.body;
        console.log(`[Login Attempt] Email: ${email}`);
    
        try {
            // Step 1: Find the user by email
            const user = await User.findOne({ email });
            if (!user) {
                console.log(`[Error] No user found for email: ${email}`);
                return res.status(400).json({ msg: 'Invalid Credentials' });
            }
            console.log(`[Success] User found for email: ${email}, Username: ${user.username}`);
    
            // Step 2: Compare the submitted password with the user's stored hashed password
            bcrypt.compare(password, user.password, (err, isMatch) => {
                if (err) {
                    console.log(`[Error] bcrypt comparison error: `, err);
                    return res.status(500).send('Server error during password comparison');
                }
                if (!isMatch) {
                    console.log(`[Mismatch] Password does not match for user: ${email}`);
                    console.log(`[Debug] Submitted password: ${password}`); // # FOR DEBUG ONLY
                    return res.status(400).json({ msg: 'Invalid Credentials' });
                }
    
                // Step 3: Password matches, proceed to generate JWT
                console.log(`[Success] Password matches for user: ${email}`);
                const payload = {
                    user: { id: user.id }
                };
    
                jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: 360000 }, (err, token) => {
                    if (err) {
                        console.error(`[Error] JWT generation error for user: ${email}`, err);
                        return res.status(500).send('Server error during JWT generation');
                    }
                    console.log(`[Success] JWT generated for user: ${email}`);
                    res.json({ token });
                });
            });
        } catch (err) {
            console.error(`[Server Error] During login for user: ${email}`, err.message);
            res.status(500).send('Server error');
        }
    });
    
    module.exports = router;

user.model.js

    const mongoose = require('mongoose');
    const bcrypt = require('bcryptjs');
    
    // Define the schema for our user model
    const userSchema = new mongoose.Schema({
        username: {
            type: String,
            required: true,
            unique: true,
            trim: true, // Removes whitespace from both ends of a string
            minlength: 3 // Minimum length of the username
        },
        email: {
            type: String,
            required: true,
            unique: true,
            trim: true, // Removes whitespace from both ends of a string
            match: [/.+@.+..+/, 'Please fill a valid email address'] // Regex to validate email format
        },
        password: {
            type: String,
            required: true,
            minlength: 6 // Minimum length of the password
        }
    }, {
        timestamps: true // Automatically adds createdAt and updatedAt fields
    });
    
    // Pre-save hook to hash the password before saving it to the database
    userSchema.pre('save', async function(next) {
        // Only hash the password if it has been modified (or is new)
        if (!this.isModified('password')) return next();
    
        try {
            // Generate a salt and use it to hash the password
            const salt = await bcrypt.genSalt(10);
            this.password = await bcrypt.hash(this.password, salt);
            next();
        } catch (error) {
            next(error);
        }
    });
    
    // Instance method to check if the provided password matches the hashed password in the database
    userSchema.methods.matchPassword = async function(enteredPassword) {
        return await bcrypt.compare(enteredPassword, this.password);
    };
    
    // Create the model from the schema and export it
    const User = mongoose.model('User', userSchema, 'users');
    
    module.exports = User;

output i am getting

"Server started on port 5000 MongoDB Connected [Login Attempt] Email: email i used [Success] User found for email: email i used, Username: username i used [Mismatch] Password does not match for user: email i used [Debug] Submitted password: password"

I have signed up succesfully with the output

_id 65c51a381f0331aa2edfb9d5 username "username i used" email "email i used" password "$2a$ hashed pass" createdAt 2024-02-08T18:15:20.965+00:00 updatedAt 2024-02-08T18:15:20.965+00:00 __v 0

in the database, but when i login it says invalid credentials.

If you have any idea what i could do here to fix this, please let me know. I have been debugging none stop and i originally thought the password wasnt being compared properly when logging in, but it is as i printed in the debug logs and it outputted as the decrypted password, thanks.

In odoo How to catch product list on change event in POS screen

I am working on a module making something when any change happens
in the product grid in the POS screen 
this is my code 

/** @odoo-module **/
const ProductScreen = require('point_of_sale.ProductScreen');
const Registries = require('point_of_sale.Registries');
const { Gui } = require('point_of_sale.Gui');


export const ChangePOSGrid = (ProductScreen) =>
  class extends ProductScreen {
       //@override
        async _onClickPay() {
           console.log('Code here');
        }
}
Registries.Component.extend(ProductScreen, ChangePOSGrid);

In this code, I already catch the Pay Button click event
but I need to catch the product list change event

how to do this can anyone help me?

JS React – differing rotation in svg components

Seeking advice on working with svg components and their rotation.

I have a react functional component where I can add figures, move them around the screen and rotate them.

Those figures are implemented as svgs.
Example:

    <svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg" transform={`rotate(${props.rotation})`}>
        <ellipse style={{ "fill": "rgb(216, 216, 216)", "stroke": "rgb(0, 0, 0)" }} cx="250" cy="250" rx="125" ry="125" />
        <text className='unselectable' style={{ "whiteSpace": "pre", "fill": "rgb(51, 51, 51)", "fontFamily": "Arial, sans-serif", "font-size": "152.2px" }} x="166.561" y="303.035" transform="matrix(0.66583, 0, 0, 0.739777, 79.047778, 60.064947)">{props.tableName}</text>
    </svg>

So I handle the rotation by calculating the number and applying it in the transform of the svg.
The problem is, that the text components also rotates and it becomes unreadable.

I tried to apply a negative degree to the text component but that does not work properly as the text drifts away (see screenshot).

Is there any solution to make the text not rotate while everything else in the svg rotates?

include and indexof not working, How to find substring in string in javascript?

I try to find if substring audio.text in string item.audioName but not matter if I use includes() or *indexOf(), it not working. but when try it in browser it working fine.

the code is in vuejs.3 function.

for(let i = 0; i < audioList.length; i++){
    const item = audioList[i];
    console.log(item.audioName)
    console.log(audio.text)
    console.log(item.audioName.indexOf(audio.text))
  }

enter image description here

New @for loop in angular 17

I want to display items of an array of strings from index 1.

arr = [ "str1", "str2", "str3", "str4", "str5" ]

Output should be:

str2
str3
str4
str5

Print all except first one, using new @for loop in angular.

How do I assign variables to an SQL query with multiple paramters? [duplicate]

I am using Nodejs to send a query to my MySQL database from my server side and send it back to the client, but the query has multiple parameters. With what I have tried, all the variables gets assigned to the first parameter.

const express = require('express');
var mysql = require('mysql');
const db = mysql.createConnection({
    host:
    database:
    user:
    password:});

let sql = 'SELECT * FROM table WHERE subID = ? AND department = ? AND trackingNum = ?';
let values = {
    subID: "inputted value",
    department: "inputted value",
    trackingNum: "inputted value"
    };

db.query(sql, values, (err, results) => {...

Logging the query on the console using this prints the query where all the values are trying to be assigned to subID. And I am trying to get the subID value in the query to be assigned to the inputted value that corresponds with the subID in values and similar for the other 2.