JS Toggle not being reflected when I dynamically load in HTML using PHP

I am trying to use JS to toggle a .show class into a div within my HTML which will change the display: none to display: block. This is for a dropdown menu. I am dynamically loading in two different versions based on whether the user is currently logged in or logged out using PHP.

Here is my PHP/HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- EXTERNAL CSS -->
  <link rel="stylesheet" href="../css/navigation-bar-v2.css">
  <!-- EXTERNAL SCRIPTS -->
  <script src="https://kit.fontawesome.com/ec7e0e3eb8.js" crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/jquery-3.1.1.js"
integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
  <script src="../js/navigation.js"></script>
</head>
<body>
    <nav class="nav-bar">
      <div class="section-a">
        <a href="../index.php"><img class="logo" src="../images/logoDarkBlue.png" alt="img"></a>
        <div style="display: flex; justify-content: start;">
          <a href="../index.php">Feed</a>
          <a href="#">Discover</a>
        </div>
      </div>
    <form>
      <input type="text" class="nav-search" placeholder="Search">
    </form>
    
    <div class="section-b">
      <?php
        if(isset($_SESSION["uid"])){
          // LOGGED IN
          echo '
            <div class="notifications">
              <button class="notification-dropdown">
                <i class="fa-solid fa-bell"></i>
              </button>
            </div>
            
            <div class="dropdown">
              <button class="logged-in">
                <span style="font-size: 20px; margin-right: 0.2em; vertical-align: middle;"><i class="fa-regular fa-circle-user"></i></span>
                <span>', $_SESSION["uname"], '</span> &nbsp;<i class="fa-solid fa-angle-down"></i>
              </button>
              <div id="myDropdown" class="dropdown-content">
                <a href="#"><i class="fa-solid fa-circle-info"></i> &nbsp;Terms & Policies</a>
              </div>
            </div>
          </div>
          ';
        }
        else {
          // LOGGED OUT
          echo '
            <div id="login-cont">
              <a href="../login.php">
                <button class="login-btn">
                  <i class="fa-solid fa-right-to-bracket"></i>&nbsp;&nbsp;<span>Log In</span>
                </button>
              </a>
            </div>
            
            <div class="dropdown">
              <button class="log-in">
                <i class="fa-regular fa-user"></i> &nbsp;<i class="fa-solid fa-angle-down"></i>
              </button>
              <div id="myDropdown" class="dropdown-content">
                <a href="#"><i class="fa-solid fa-circle-info"></i> &nbsp;Terms & Policies</a>
              </div>
            </div>
          ';
        }
      ?>
  </nav>
</body>
</html>

Here is my JS:

window.addEventListener("DOMContentLoaded", (event) => {
  $(".log-in").click(() => {
    openNavDropdown();
  });

  $(".logged-in").click(() => {
    console.log("Click!!!");
    openNavDropdown();
  });

  function openNavDropdown() {
    console.log(document.getElementById("myDropdown"));
    document.getElementById("myDropdown").classList.toggle("show");
    console.log(document.getElementById("myDropdown"));
  }

  // Close the dropdown if the user clicks outside of it
  window.onclick = function (event) {
    if (
      !event.target.matches(".log-in") ||
      !event.target.matches(".logged-in")
    ) {
      var dropdowns = document.getElementsByClassName("dropdown-content");
      var i;
      for (i = 0; i < dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if (openDropdown.classList.contains("show")) {
          openDropdown.classList.remove("show");
        }
      }
    }
  };
});

To debug, I ran some console.log commands within my JS and found that the class was actually being added to the proper div. However, within the added class is not being reflected within the actual source code:

enter image description here

enter image description here

All the code required to replicate the problem should be provided above.

if statement in function working before the variables are even given a value

I am working on a HTML, CSS,and Javascript document. I have created this:

let email = ''
let password = ''

function loginInfo() {
  email = document.getElementById('forma').value
  password = document.getElementById('forma').value
  setTimeout(5)
  if (password === '123') and (email==='[email protected]'); {
    console.log('succesful')
  }
}
setTimeout(5)
loginInfo()

When I run the program the console.log('succesful') runs no matter what, before I even type anything into the forms. Why wouldn’t declaring the two variables at the top, email and password make it that the if statement if false and the code doesn’t go through?

I tried adding the timeouts to delay this, and originally I thought all the problem was that I wasn’t setting the variables as blank right away. It should be noted that when I first ran the program it did run any code in the if statement before I put data into the forms, but everytime after that it’s continued to do it before. I even tried deleting the code, running, and putting it back but the problem still persists.

How can i start a net socket and send back data from utilityProcess in Electron

I’m trying to use the new utilityProcess modul for background work instead of a hidden renderer in Electron.

I can’t seem to find any good examples of its. use. The documentation is fairly sparesome.

Only shows snippet like:

// Main process
const { port1, port2 } = new MessageChannelMain()
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
child.postMessage({ message: 'hello' }, [port1])

// Child process
process.parentPort.once('message', (e) => {
  const [port] = e.ports
  // ...
})

I need the util script file to be in Typescript, and also need to start a net socket listener and send back data to renderer from the utility process.

Can anyone help with some examples or links?

Best regards from Peter, Denmark

To unzip and count the number of image files in a zip on client side

The below code is counting the image twice I guess and I am not able to see where I am going wrong with it. Can someone please look at it and help?

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>My Webpage</title>
    <!-- JSZip library for unzipping files -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
    <!-- jQuery library for sending AJAX requests -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <h1>Upload Files</h1>
    <p>Select a ZIP file or a single image file with .nii extension:</p>
    <input type="file" id="file-input">
    
    <script>
      document.getElementById('file-input').addEventListener('change', function(event) {
        const file = event.target.files[0];
        if (file.type === 'application/octet-stream' || file.name.endsWith('.nii')) {
          alert(`Number of images in the file: 1`);
        } else if (file.type === 'application/zip') {
          const archive = new JSZip();
          archive.loadAsync(file).then(function(zip) {
            let numImages = 0;
            zip.forEach(function (relativePath, file) {
              if (!file.dir && relativePath.endsWith('.nii')) {
                numImages++;
              }
            });
            alert(`Number of images in the file: ${numImages}`);
          });
        }
      });
    </script>
  </body>
</html>

Output:
enter image description here
Above is the output

Migrating from then/catch promises chain to async/await

I’m trying to convert a chain of promises .then().catch to async/await functions

const chain = [
    {
        onFulfilled: () => {/*some logic*/},
        onRejected: () => {/*some logic*/},
    {
        onFulfilled: () => {/*some logic*/},
        onRejected: () => {/*some logic*/},
    {
        onFulfilled: () => {/*some logic*/},
        onRejected: () => {/*some logic*/},
    },
    //...
];
const data = 'initial data';
let promise = Promise.resolve(data);
let i = 0;
while (i < chain.length) {
    promise = promise.then(chain[i].onFulfilled).catch(chain[i].onRejected);
    i++;
}

The final promise is equal to:

promise = Promise.resolve()
.then(chain[0].onFulfilled).catch(chain[0].onRejected)
.then(chain[1].onFulfilled).catch(chain[1].onRejected)
.then(chain[2].onFulfilled).catch(chain[2].onRejected)
....

Here is what I’ve tried so far

let data = 'initial data';
for (const fn of chain) {
  try {
      data = await fn.onFulfilled(data);
  } catch (e) {
      data = await fn.onRejected(e);
  }
}

The prolem is: if fn.onRejected throw something, the for loop will stop rather than jump into the next fn.onRejected

Javascript – Toggle on and off multiple png images

Hello I am a relative rookie when it comes to web design in general and am having a heck of a time trying to figure out how to toggle a png image from hidden to visible. Effectively what I want to happen is to have a base image that is always displayed on the webpage and be able to use checkboxes to toggle on or off specific png images. I am sure that it is a very simple thing to do but after spending a half a day searching Google I thought better of myself and decided to ask for some help.

Here is the HTML, CSS, and JavaScript that I have:

<!DOCTYPE html>
<html>
    <head>
        <!---->
        <style>
        .buttonBar {
            width:64%;
            margin: 2% 17%;
            padding: 1%;
            border: 2px solid #44506e;
            border-radius: 5px;
            background-color: #c1baa9;
        }
        .pngCake {
            position: relative;
            width:60%;
            margin-left: 17%;
            padding: 3%;
            border: 2px solid #44506e;
            border-radius: 5px;
            background-color: #c1baa9;
        }
        #base {
            position: relative;
            top: 0;
            left: 0;
        }
        .pngCake #png, .pngCake #png1 {
            position: absolute;
            top: 0;
            left: 0;
            visibility: hidden;
        }
    </style>
        <title>Image Cake</title>
    </head>
    <body>
        <div class="buttonBar">
            <label class="cb">
                <input type="checkbox" onclick="pngLayer()">
                <span class="cm"></span>
            PNG</label>
            <!-- Printer Checkbox -->
            <label class="cb">
                <input type="checkbox" onclick="pngLayer1()">
                <span class="cm"></span>
            PNG 1</label>
        </div>
        <div class="pngCake">
            <img id="base" src="base.png"></img>
            <img id="png" src="png.png"></img>
            <img id="png1" src="png1.png">
        </div>
        <script>
            function pngLayer() {
                var portCheck = document.getElementById("png");
                portCheck.style.visibility = "visible";
            }
            function pngLayer1() {
                var portCheck = document.getElementById("png1");
                portCheck.style.visibility = "visible";
            }
        </script>
    </body>
</html>

In JavaScript I have tried using a toggle command to pull a duplicate of the CSS with the visibility set to visible.
In addition I have tried using if else statements to check and see if the visibility of the png is set to hidden vs visible and changing it.
In each case the result did not work.

if(document.getelementbyid("png").style.visibility == "hidden") {
    document.getelementbyid("png").style.visibility == "visible"
}
else {
    document.getelementbyid("png").style.visibility == "hidden
}

How to ‘unstick’ a fixed container when resizing

I’ve made a draggable and resizable window (a DIV). One minor bug I can’t seem to work out is resizing it before it’s been moved. It’s position is fixed as I need it to stay in place when the page scrolls. If you try to resizing it without first moving it then the div stays glued to the edge of the screen, which is the top and right as I’ve set its initial position. If the user moves the div even 1 pixel then resizes it, it works at one would expect.

Here’s a jsfiddle too

        function createDragElement(el){
            var $header = $(el+" h4");
            var offsetX = 0, offsetY = 0; 
            
            $header.on('mousedown', setDrag);
            
      d = document.getElementById('tile-window');
      
      new ResizeObserver(resize).observe(d);
      
            
            function setDrag(e){
                e.preventDefault();
                
                offsetX = e.offsetX
                offsetY = e.offsetY;

                document.onmousemove = dragMouse
                document.onmouseup = stopDrag;
                
                isDragging = true;
            }
            
            function dragMouse(e){
                e.preventDefault();
                
                $header.parent().css('left', e.clientX-offsetX + "px");
                $header.parent().css('top', e.clientY-offsetY + "px");

            }
            
            function stopDrag(){
                document.onmousemove = null;
                document.onmouseup = null;
                isDragging = false;
            }
      
      function resize(){
        c = $(el+" div");
        $header.css('width', d.offsetWidth);
        c.css('width', d.offsetWidth);
        c.css('height', d.offsetHeight-42);
      }
        
        }
    

    
    createDragElement("#tile-window");
    
    
    
#tile-window{
            position:fixed;
            right:20px;
            top:20px;
            width:200px;
            height:300px;
            background:#000000DE;
            border:1px solid #66666688;
            
            box-shadow: rgba(0,0,0, 0.6) 0px 2px 8px 5px;
            border-radius:5px;
            overflow:hidden;
      resize:both;
        }
        
        #tile-window h4{
            display:table-cell;color:#23b6d6;text-align:center;width:200px;height:40px;margin:0;vertical-align:middle;cursor:move;font-size:1.2em;
            background:linear-gradient(to bottom, rgba(137,144,153,1) 0%,rgba(68,70,73,1) 43%,rgba(10,14,10,1) 51%,rgba(10,8,9,1) 100%);
            border-bottom:1px solid #666666;
        }
        
        #tile-window div{width:200px;height:200px;overflow:scroll;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tile-window">
        <h4>Tiles</h4>
        <div>
            <img src="https://img.freepik.com/premium-vector/random-squares-background_116953-1604.jpg">
        </div>
    </div>

Receiving a promise/async 404 error on axios get request

I’m receiving this error (see picture) on my axios get request. I can’t see anything wrong with this setup, but am still receiving this error.

Picture or error

I’ve tried multiple different ways of writing the request and the teamId does call back with the proper vaue when I console.log() it

Vue –

  async getTeamCallLists() {
    const { data } = await getTeamCallLists(this.teamId)
    this.callListTeams = data
  },

.ts file

import axios from 'axios'
import { CallListTeam } from '../../../server/src/call_list/call-list-team.entity'
import { CallListUser } from '../../../server/src/call_list/call-list-user.entity'

export const getTeamCallLists = (teamId: number | string) => axios.get<CallListTeam>(`/api/v1/call-list/get-team-call-lists/${teamId}`)

Controller –

@Get('get-team-call-lists/:teamId')
getTeamCallLists(@Param('teamId') teamId: number) {
    this.logger.log('Controller reached')
    return this.callListService.getTeamCallLists(teamId);
}

Service –

getTeamCallLists(teamId: number) {
    this.clTeamRepository.find ({
        where: {
            teamId: teamId,
            isActive: true
        }
    })
}

How do I fetch from a page I posted(express backend and html frontend)

I have a login page as index.html, it asks for email and password, and has a submit button like this:

<input type="submit" value="Log In" id="loginbutton">

Then in my app.js I have:

app.post("/login", async(req, res) => {
    // check if the user is in the list of registered users
    const user = users.find((c) => c.user == req.body.email)

    // if user dose not exist, send the user to the register page
    if(user == null) {
        res.json({nouser: true, wrongpassword: false, username: "null", accessToken: "null", refreshToken: "null"})
    }else if(await bcrypt.compare(req.body.password, user.password)) {
        const accessToken = generateAccessToken({user: req.body.email})
        const refreshToken = generateRefreshToken({user: req.body.email})

        res.json({nouser: false, wrongpassword: false, username: user.username, accessToken: accessToken, refreshToken: refreshToken})
    }else {
        res.json({nouser: false, wrongpassword: true,  username: "null", accessToken: "null", refreshToken: "null"})
    }
})

So now when I click on the log in(submit) button I could get to the page of localhost:4000/login with a json in it. However, I don’t want that. I tried to parse that json in my index.html with fetch so that I could decide whether to have an alert or redirect people to the user page or register page, etc. like this:

function main() {
     let url = "http://localhost:4000/login";
     fetch(url, {method: "GET"})
          .then(response => response.json())
          .then(json => {processObject(json)})
}

function processObject({nouser, wrongpassword, username, accessToken, refreshToken}) {
      if(nouser) {
          displayConfirm()
      }else if(wrongpassword) {
          wrongPswdAlert()
      }
}

However it doesn’t stay on index.html to show alert or redirect it to somewhere else like I want it to do. I wonder how could I change my code for it.

Javascript Sudoku generator

I want to generate a sudoku board but I am having trouble with the algorithm. I wanted to generate it for fun but it turned out to be a nightmare.

Problems that I faced:

  • Infinite loops while checking all the conditions of being grid, column and row safe.

The code I tried:

const answers = [];

for (let i = 0; i < 81; i++) {
    answers.push(0);
}
let iterator = 0;
while (iterator < 81) {
    let randomValue = Math.floor(Math.random() * 9) + 1;

    while (
        !isGridSafe(iterator, randomValue) ||
        !isRowSafe(iterator, randomValue) ||
        !isColSafe(iterator, randomValue)
    ) {
        iterator--;
        answers.pop();
        randomValue = Math.floor(Math.random() * 9) + 1;
    }
    if (
        isGridSafe(iterator, randomValue) &&
        isColSafe(iterator, randomValue) &&
        isRowSafe(iterator, randomValue)
    ) {
        answers[iterator] = randomValue;
        iterator++;
    }
}

Animation not working when adding class to parent

I’m making a modal window but the animation doesn’t work.
Here is the html

<div class="dropdown-modal">
   <div class="dropdown-modal__contaner">
      ...
   </div>
</div>

When the button is clicked, dropdown-modal--active is added to the parent block

.dropdown-modal
    display: none
    position: fixed
    z-index: 1060
    top: 0
    left: 0
    width: 100%
    height: 100%
    background: rgba(0,0,0, .5)

    &--active
        display: block
        
    &__contaner
        display: block
        height: 150px
        position: relative
        background: #fff
        transition: transform 0.3s ease-out
        transform: translate(0, -90%)
        
    &--active &__contaner
        transform: transform: none

How to make animation work?

Animation should work

Save data as an array of array instead that array of objects

im using a depedency (react-select) that allows to select multiple options in a dropdown list. The options needs label and value. The info is sent in the next way:

"time": [
{
"label": "10:00",
"value": "10:00"
},
{
"label": "12:00",
"value": "12:00"
}
],

This is my code:

    const [time, setTime] = useState([]);

    const listOfHours = time?.map((hour) => ({ label: hour, value: hour }));

          <Select
          options={listOfHours}
          value={time}
          onChange={setTime}
          isMulti/>

I tried

      const listHours = listOfHours?.map(({value}) => [value])

But i cant set is as the value sent by the dropdown list.

already finished web application (html, css, js) in an mobile application

I made an web application in plain html, css, and js (with modules). I also already created a desktop application with Electron.
Now i want to know if there is an program or framework where I can create an mobile application.
I know I can use React Native but I do not wanna write my whole application again.

I already tried using android studio, but i had some bugs with the Icons (home icon) and now i wondered if there is an tool to “convert” my web application to and mobile application.