How do I do a user authentication and if it is true it draws main content

I have this code that what I am trying to do is that when userLoggin is true, it does not draw the loggin page but main content, it is a simple application without backend, so I don’t know how to do it when userloggin is true it simply changes to drawing main content
any advice or help?

userData comes from another page saved as a cookie where the user’s registration data is saved and I request it in this script

const mainContainer = document.getElementById("main-container");
const loginContainer = document.getElementById("login-form");
const cookies = document.cookie;
const cookieArray = cookies.split(";");
let userData = null;
let UserLoggin = {
 loggin: false,
};

function toggleContainers() {
 if (UserLoggin.loggin) {
   loginContainer.style.display = "none";
   mainContainer.style.display = "grid";
 } else {
   loginContainer.style.display = "block";
   mainContainer.style.display = "none";
 }
}

for (const cookie of cookieArray) {
 const trimmedCookie = cookie.trim();
 if (trimmedCookie.startsWith("userData=")) {
   const userDataString = trimmedCookie.split("=")[1];
   userData = JSON.parse(decodeURIComponent(userDataString));
   break;
 }
}

if (UserLoggin.loggin) {
 toggleContainers();
}

const btnLoggin = document.getElementById("btnLoggin");

btnLoggin.addEventListener("click", () => {
 const password = document.getElementById("password").value;
 const username = document.getElementById("username").value;

 if (
   userData &&
   password === userData.password &&
   username === userData.username
 ) {
   console.log("¡Inicio de sesión exitoso!");
   password.value = "";
   username.value = "";
   UserLoggin.loggin = true;

   toggleContainers();

   const userLoginJSON = JSON.stringify(UserLoggin);
   function setCookie(name, value, daysToExpire) {
     const expirationDate = new Date();
     expirationDate.setDate(expirationDate.getDate() + daysToExpire);

     const cookieValue = `${name}=${encodeURIComponent(
       value
     )}; expires=${expirationDate.toUTCString()}; path=/`;
     document.cookie = cookieValue;
   }
   setCookie("userLogginData", userLoginJSON, 30);

   console.log(UserLoggin);
 } else {
   console.log("Nombre de usuario o contraseña incorrectos.");
 }
});

mainContainer.addEventListener("load", () => {
 const addTableComponent = document.getElementById("addTableComponent");
 const tablecontainer = document.getElementById("table-container");

 addTableComponent.addEventListener("click", () => {
   const tableComponent = document.createElement("column-table");
   tablecontainer.insertBefore(tableComponent, addTableComponent);
 });
});


Javascript fetch API doesn’t return

I’m running an HTTP server with python -m http.server that’s serving my ressources.
Here’s my layout :

dist/
   bundle.js
   index.html
   style.css
assets/
   tracks/
       listing.json

I have the following code :

fetch("http://localhost:8000/assets/tracks/listing.json")
    .then(() => console.log("Got it"))

So far so good, it prints ‘Got it’ after a few ms.
But when I do that :

fetch("http://localhost:8000/assets/tracks/listing.json")
    .then(() => console.log("Got it"))

while (true) {}

It just somehow freezes without printing anything, and the page has that little blue circle indicating it’s still loading.

I have a way of not using that while loop, and, so to say, to solve the problem.
But I think this has something to do with how asynchronous processes work in Javascript, and I think it could be good for me to learn a bit more about exactly why it doesn’t work.

Thanks !

How can I modify my JavaScript code to remove a specific selected area when right-clicked?

With the code below, I can select areas on an image. However, there is an issue when trying to remove a selected area. Let’s say I’ve created 4 areas, and I want to remove the second one. When I right-click on the second area and select “remove,” it actually removes the most recently added area, and the “remove” action only works once. When I try to remove it again, it doesn’t work.

How can I modify this code so that it only removes the area that was clicked on, and works correctly for each area individually?

Here’s the code:

const imageContainer = document.getElementById('image-container');
const image = document.getElementById('image');
const selectedAreasList = document.getElementById('selected-areas');

let isDragging = false;
let startX, startY, endX, endY;
let currentSelection;
let selections = []; // Seçilmiş alanları saklamak için bir dizi

imageContainer.addEventListener('mousedown', (e) => {
    if (e.button !== 0) return; // Sadece sol tıklama olayını ele al
    if (e.target.classList.contains('selection-box')) {
        e.preventDefault();
        return;
    }
    isDragging = true;
    startX = e.clientX - imageContainer.getBoundingClientRect().left;
    startY = e.clientY - imageContainer.getBoundingClientRect().top;
    currentSelection = document.createElement('div');
    currentSelection.className = 'selection-box';
    currentSelection.style.left = startX + 'px';
    currentSelection.style.top = startY + 'px';
    imageContainer.appendChild(currentSelection);
    selections.push(currentSelection); // Yeni seçili alanı diziye ekleyin
});

document.addEventListener('mousemove', (e) => {
    if (!isDragging) return;
    endX = e.clientX - imageContainer.getBoundingClientRect().left;
    endY = e.clientY - imageContainer.getBoundingClientRect().top;

    let width = endX - startX;
    let height = endY - startY;

    // Genişlik ve yükseklik en az 10 piksel olacak şekilde sınırla
    width = Math.max(width, 10);
    height = Math.max(height, 10);

    currentSelection.style.left = startX + 'px';
    currentSelection.style.top = startY + 'px';
    currentSelection.style.width = width + 'px';
    currentSelection.style.height = height + 'px';
    currentSelection.style.display = 'block';
});

document.addEventListener('mouseup', () => {
    if (isDragging) {
        isDragging = false;
        offsetX = currentSelection.getBoundingClientRect().left - imageContainer.getBoundingClientRect().left;
        offsetY = currentSelection.getBoundingClientRect().top - imageContainer.getBoundingClientRect().top;
        currentSelection.style.cursor = 'grab';

        // Sağ tıklama menüsünü seçilen alana ekleyin
        currentSelection.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            const contextMenu = document.createElement('div');
            contextMenu.className = 'context-menu';
            contextMenu.innerHTML = '<div class="context-menu-item">Kaldır</div>';
            contextMenu.style.left = e.clientX + 'px'; // Mouseun X konumu
            contextMenu.style.top = e.clientY + 'px'; // Mouseun Y konumu
            document.body.appendChild(contextMenu);

            // Kaldır seçeneğine tıklandığında seçimi kaldırın
            const removeItem = contextMenu.querySelector('.context-menu-item');
            removeItem.addEventListener('click', () => {
                imageContainer.removeChild(currentSelection); // Seçim kutusunu kaldır
                const index = selections.indexOf(currentSelection);
                if (index !== -1) {
                    selections.splice(index, 1); // Seçim kutusunu diziden kaldır
                }
                document.body.removeChild(contextMenu); // Sağ tık menüsünü kaldır
            });

            // Sağ tık menüsünü kaybolmasını sağlamak için belgeye bir tıklama olayı ekleyin
            document.addEventListener('click', () => {
                document.body.removeChild(contextMenu);
            });
        });

        selectedAreasList.innerHTML += `<li>(${startX}, ${startY}) - (${endX}, ${endY})</li>`;
    }
});

React Native Paper single date picker not showing save button

I’m creating an app with React Native Paper as my UI framework, and I’m trying to add a single date picker. The date picker works, but I can’t see the save button that is supposed to be there. If I press in the right hand corner where it is supposed to be, it works, but the button is invisible? Can anyone please help me fix this problem?

This is my code:

<View>
            <Text>{date.toLocaleDateString()}</Text>
            <TimePickerModal
              visible={visible && mode === 'time'}
              onDismiss={onDismiss}
              onConfirm={onConfirm}
            />

            <DatePickerModal
              locale="en-GB"
              mode="single"
              visible={visible && mode === 'date'}
              onDismiss={onDismiss}
              date={date}
              onConfirm={onConfirmSingle}
            />

            <View
              style={{
                width: '100%',
                justifyContent: 'space-between',
                flexDirection: 'row',
              }}
            >
              <Button
                mode="outlined"
                onPress={() => {
                  setMode('time')
                  setVisible(true)
                }}
                style={{ width: '50%' }}
              >
                Select Time
              </Button>
              <Button
                onPress={() => {
                  setMode('date')
                  setVisible(true)
                }}
                uppercase={false}
                mode="outlined"
                style={{ width: '50%' }}
              >
                Pick date
              </Button>
            </View>
          </View>

Here is an image of the problem:
Image of how the date picker looks on my phone

I thought maybe the color of the button was the problem, so I tried adding a color property to the styles of the date picker, but nothing happened.

Issue with Modal in Bootstrap 5 – Blazor

I’m working on a Blazor application using Bootstrap for modal handling. I’m trying to use the data-bs-backdrop and data-bs-keyboard attributes in my ModalAlert.razor component to control the behavior of the backdrop and keyboard when the modal is open.

The problem I’m facing is that the backdrop is displayed correctly when the modal is open, but it doesn’t prevent closing the modal by clicking on it, even though I’ve set data-bs-backdrop=”static” and data-bs-keyboard=”false”.

What am I doing wrong? Can someone help me understand how to make the data-bs-backdrop attribute work correctly to prevent closing the modal by clicking on the background?

Thanks in advance for your help!

Screen of “ModalAlert.razor”:
ModalAlert.razor

Blazor project: Blazor Server .NET 7

Can I have a way to get URL from user and use it in page.goto function in Puppeteer in Node js project?

I am trying to automate a web page mainly, will be scraping the content from webpage, but the challenge here is the webpage should be based on URL provided by USER. Want to have a UI where in user provide a webpage URL, taking that URL dynamically I have to scrape the webpage content.

Added a screenshot enter image description here

the example.com must be changed dynamically based on the URL provided by the user.

New to nodeJs, this question might be silly!

Trying to get URL dynamically somehow from nodeJs to run puppeteer.

toggle nav menu bar using javascript

i am trying to toggle a navbar menu on media frame max width 950px . i have figured out how to make it display but how do i toggle it off . i really hope this question its clear enough here is the code snippet below .

document.getElementById('menu').addEventListener('click', Showmenu);
const mymenu = document.querySelector('.myheader__content');
function Showmenu() {
    
    mymenu.style.display = 'initial';
  
    }
@media(max-width:950px){
    .myheader{
       position: relative;
    } 
    #menu{
        display: initial;
        margin-left: auto;
    }
 
    .myheader__btn{
        margin-left: 50px;
        padding-left: 10px;
        padding-bottom: 40px;
        padding-right: 10px;
        
    }
        .myheader__content{
            display: none;
            position: absolute;
            top:100%; left:68% ; right:5%;
            background-color:#FAFDFF;
            flex-direction: column;
            width: 240px;
            border-top: solid 3px #ffb886;
            border-left: solid 1px #ffb886;
            border-right: solid 1px #ffb886;
            border-bottom: solid 1px #ffb886;
        }
        .myheader__btn-search{
            left: 67%;
        }
        .myheader__search{
            width: 180px;
            outline: none;
        
        }
        .myheader__modestyle{
            display: none;
        }
    
}
<div class="myheader__content " >
        <button class="myheader__btn">Agriculture</button>
        <button class="myheader__btn">Business</button>
        <button class="myheader__btn">Lifestyle</button>
        <form action="" class="myheader__form"><input type="text" class="myheader__search" placeholder="Search">
        <button class="myheader__btn-search"><span class="material-symbols-outlined myheader__btn-icon">
            search
            </span></button></form>
            <div class="vl"></div>
            <div class="mode"><span class="material-symbols-outlined myheader__modestyle">
                light_mode
                </span></div>

i want the menu bar display to open when clicked and close when clicked again .

How do I get the resolved result from a Promise?

I have a razor page with the following code:

@code
{
    [Inject]
    private IJSRuntime jsRuntime{ get; set; }

    private string jsonString {get;set;}

    protected override async void OnInitialized()
    {
        string json = await jsRuntime.InvokeAsync<string>("initializeElkJs", jsonString);
    }

    [JSInvokable]
    public static Task DrawGraph(string json)
    {
        int a = 0;
        return null;
    }
}

And a JavaScript function as the following:

window.initializeElkJs = function (jsonData)
{
    const graph = JSON.parse(jsonData);

    const elk = new ELK();
    const layoutOptions = {
        'elk.algorithm': 'layered'
    };

    let result = "";

    elk.layout(graph, layoutOptions)
        .then((g) =>
        {
            //return JSON.stringify(g, null, " "); //Did not work
            result = JSON.stringify(g, null, " "); //Did not work
            //DotNet.invokeMethodAsync('BlazorServerTest', 'DrawGraph', JSON.stringify(g, null, " "));  //Did not work
        });

    return result;  //Did not work
}

I need to get the result string back to the razor page so I could process it in it, but as you can see, none of the method I tried worked, I later find out that return in the then closure returns another Promise, I have also tried using await in JavaScript, but unfortunately that returns yet another Promise, and I can not find any way to “get out of the Promise“.

Could somebody please be so kind teaching me how to properly get the return string so I could process it in the razor page?

Thank you very much for your help!

PS. This is the elkjs library if needed, all you need is elk.bundled.js.

Issues writing to Firebase Realtime Database

I have written the following code to test writing to a Firebase Realtime Database. It wrote data to the database once, but after that will do nothing. Currently, I am just trying to save the first name that the user enters on a form after they press the submit button.

<script type="module">
  
    // Import the functions you need from the SDKs you need
  
    import { initializeApp } from "https://www.gstatic.com/firebasejs/10.4.0/firebase-app.js";
  
    // TODO: Add SDKs for Firebase products that you want to use
  
    // https://firebase.google.com/docs/web/setup#available-libraries
  
  
    // Your web app's Firebase configuration
  
    const firebaseConfig = {
  
      apiKey: "AIzaSyAEGiSKDCg0nkrSxHshqxPEUWxtGI1NP7Q",
  
      authDomain: "wrud-d63af.firebaseapp.com",
  
      databaseURL: "https://wrud-d63af-default-rtdb.firebaseio.com",
  
      projectId: "wrud-d63af",
  
      storageBucket: "wrud-d63af.appspot.com",
  
      messagingSenderId: "491961850138",
  
      appId: "1:491961850138:web:2468aff8d84e08c40ff4a3"
  
    };

    
    
      // Initialize Firebase
    
      const app = initializeApp(firebaseConfig);
      
      import {getDatabase, set, get, update, remove, ref, child} from "https://www.gstatic.com/firebasejs/10.4.0/firebase-database.js"
      
      const db = getDatabase()
      
      var fname = document.getElementById("fname")
      var submitBtn = document.getElementById("submitBtn")
      
      
      function save(){
        
          
          set(ref(db, "/"), {
              Name: fname.value
          })
          
      }
      
      
      submitBtn.addEventListener('click', save)
      
    
    </script>

Issue with undefined post request

I want to make a blood management app and I am having issue for user registration if i want to send data everything is working but I am not able to post data through the post request through rest client.
Each parameter is undefined.
index.js

const express=require('express');
const mongoose=require('mongoose');
const cors=require('cors');
const bodyParser=require('body-parser');
const app=express();
const userRoutes=require('./route/userRoutes')
mongoose.connect('mongodb://127.0.0.1:27017/blood').then(()=>{
    console.log('connected to database')
}).catch((err)=>{
    console.log(err);
})
app.use(bodyParser.json());
// app.use(express.json());
app.use(cors());
app.use('/users',userRoutes);

app.listen(3001,()=>{
    console.log('server working on 3001');
})

userRoutes.js

const express=require('express');
const router=express.Router();
const userController=require('../controller/userController')

router.post('/register',userController.registerUser);

module.exports=router;

userController.js

const bcrypt = require('bcrypt');
const User = require('../model/user');

exports.registerUser = async (req, res) => {
    const { name, email, password, role, gender, bloodtype, age, disease } = req.body;
    console.log(req.body);
    try {
        const existingUser = await User.findOne({ email });
        if (existingUser) {
            return res.status(400).json({ error: 'Email already exists' });
        }
        const hashedPassword = await bcrypt.hash(password, 10);
        const newUser = new User({
            name,
            email,
            password: password,
            role: role || 'user',
            gender,
            bloodtype,
            age,
            disease: disease || 'N/A',
        });
        await newUser.save();
        res.status(201).json({ message: 'New User created' });
    } catch (error) {
        // console.error(error);
        res.status(500).json({ error: 'Server error' });
    }
};

user.js

const mongoose=require('mongoose');

const userSchema=new mongoose.Schema({
    name:{
        type:String,
        required:true,
    },
    password:{
        type:String,
        required:true,
    },
    email:{
        type:String,
        required:true,
    },
    role:{
        type:String,
        enum:['user','admin'],
        default:'user'
    },
    gender:{
        type:String,
        enum:['Male','Female'],
        required:true,
    },
    age:{
        type:Number,
        required:true,
    },
    disease:{
        type:String,
        default:'N/A',
    },
    bloodtype:{
        type:String,
        enum:['A+','A-','B+','B-','AB+','AB-','O+','O-'],
        required:true,
    },
});

const User=mongoose.model('User',userSchema);
module.exports=User

request.rest

using rest client

POST http://localhost:3001/users/register

Content-Type: application/json

{
    "name": "John Doe",
    "email": "[email protected]",
    "password": "securepassword",
    "gender": "Male",
    "age": 30,
    "bloodtype": "A+"
}


I am not able to send the post request send data through post request through the rest client the req.body is empty i.e. each parameter is undefined.

I want to send post data but not able to do that.

Vue push() is overwriting previous data in array

I am passing data from a child component (Form) to its parent component (App).The data is being passed just fine but when I need to add the data to the array created in the App component,all previous elements in the array are overwritten and the same element appears in each position.

<template>
  <Form :addPC="getPC" />
</template>

<script>
import Form from './components/Form.vue'
export default {
  name: 'App',
  components:{
    Form,
  },
  methods:{
    getPC(pc)
    {
      var PC = {}
      PC = pc
      this.PCs.push(PC)
      console.log(this.PCs)
    }
  },
  data(){
      return{
        PCs:[]
      }
    },
}
</script>

How to rename a file with Jquery before download it?

I have a html-jquery script to download a lot of files.
This files are downloades by calling the event onClick on all those url. They are automatically saved on Download folder. But I would like to rename the files before they are saved on Download dfolder.
How can I do it? This is my code:

<script src=https://code.jquery.com/jquery-3.6.0.min.js 
</script>
    
    
<script id="funciones">
        var count = 0;
    
        function linkGen() {
            var requestId =[
                ['111111111111111111111111111111111111','7373'],
                ['222222222222222222222222222222222222','8888'],
                ['333333333333333333333333333333333333','6767'],
                ['444444444444444444444444444444444444','9999']
            ]
            
    
            count = 0;
            var html = '';
            $.each(requestId, function (item, value) {
                var link = 'https://mylink.com/index.php?entryPoint=download&id=' + value[0] + '&type=Note';
                count++;
                var fileName = value[1] + '_' + getFileNameFromUrl(link);
                html += '<div><a href="' + link + '" id="link' + count + '" download="' + fileName + '" onclick="event.preventDefault(); window.open(`' + link + '`, `_blank`);">Link ' + count + '</a></div>';
            })
            $('div').html(html);
        }
    
        function getFileNameFromUrl(url) {
            var parts = url.split("/");
            return parts[parts.length - 1];
        }
    
        linkGen();
    
        link = 0;
        function down() {
            if (link <= count) {
                var enlace = $('#link' + link).attr('href');
                $('#link' + link).click();
                link++;
                console.log(link + ' - ' + enlace);
            }
        }
    
        function buttonOn() {
            setInterval(down, 1000);
        }
</script>

How to create a hierarchy data structure from a template in javascript

I’m trying to build a simple tool that can create a large tree structure automatically. The idea is you define the structure and how many items you want in each nesting and then javascript builds the array for you. I want to end up with a flat list of items with parentIds.

I’ve a “template” structure but don’t know how to turn that into all the data. For example here’s a template I have.

[
    {
        "id": "6acc93d156dc11eea34331ffef2d706d",
        "parentId": null,
        "name": "ep101",
        "seq": [
            "ep101",
            "ep102"
        ]
    },
    {
        "id": "0d305b4056e011eea34331ffef2d706d",
        "parentId": "6acc93d156dc11eea34331ffef2d706d",
        "name": "ep101sh010",
        "seq": [
            "ep101sh010",
            "ep101sh020"
        ]
    },
    {
        "id": "28ea228056e011eea34331ffef2d706d",
        "parentId": "0d305b4056e011eea34331ffef2d706d",
        "name": "Generic",
        "seq": []
    }
]

In this example the resulting tree would look something like this.

ep101
– ep101sh010
–– Generic
– ep101sh020
–– Generic
ep102
– ep102sh010
–– Generic
– ep102sh020
–– Generic

Any help would be appreciated thanks!