J’essai d’utiliser document.queryselector() sur une classe et seul un élément de cette classe fonctionne correctement

            document.querySelector ('.keys').style.visibility="visible" ;

La classe est appliqué a des boutons et visiblement le script fonctionne mais seulment pour un seul des boutons

j’ai d’abord essayé en donnant un identifiant différent a chaque bouton, ce qui ne fonctionnait pas non plus.
le but du code est de faire apparaitre et disparaitre plusieurs image en cliquant dessus

React – How do i set one button to change its colour and the other buttons another colour instead of all having the same colour?

I made a quiz app where when the user clicks an answer button where case 1 is the user clicks the correct answer button and it turns green and where case 2 is the user clicks the wrong answer and it turns red while the correct answer will be shown in green. However, from what i made, i made all the buttons turn either red ( if user picks the wrong answer ) or turns green ( if user picks the correct answer ). Why it is like this is because i was testing and playing around with it but now im not sure how to change it.

Here’s my code:

import { useEffect, useState } from "react";
import styles from '@component/styles/Home.module.css'
import { shuffleArray } from "./Helper";

export default function ShowQuestions() {

    const [data, setData] = useState(null);
    const [quesno, setQuesno] = useState(0);
    const [answersArr, setAnswersArr] = useState([]);
    const [message, setMessage] = useState("");
    const [able, setAble] = useState(false);
    const [styleButton, setStyleButton] = useState(styles.answerbutton);
    const [score, setScore] = useState(0);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        async function getData() {
          let res = await fetch(`https://opentdb.com/api.php?amount=10`);
          let body = await res.json();
          setData(body.results);
        }
        
        getData();
      }, []);

    useEffect(() => {
        if (data) {
            setLoading(true);
            const newAnswersArr = [];
            newAnswersArr.push(data[quesno].correct_answer);
            const incorrectAnswers = data[quesno].incorrect_answers;
            for (let i = 0; i < incorrectAnswers.length; i++) {
                newAnswersArr.push(data[quesno].incorrect_answers[i]);
            }

            const shuffledArray = shuffleArray(newAnswersArr);
            setAnswersArr(shuffledArray);
        }

    }, [data, quesno]);
    
    

    function nextQuestion() {
        if (quesno < data.length - 1) {
            setQuesno(quesno + 1);
            setMessage("");
            setAble(false);
            setStyleButton(styles.answerbutton);
        }
    } 
    function checkAnswer(answer) {
        let correctIndex = answersArr.indexOf(data[quesno].correct_answer);
        for (let i = 0; i < answersArr.length; i++) {
            if (answersArr[i] === answer) {
                if (i === correctIndex) {
                    setMessage("Correct Answer!");
                    setScore(score + 1);
                    setStyleButton(styles.correctanswer);
                    
                } else {
                    setMessage("WRONG!!!!");
                    setStyleButton(styles.incorrectanswer);
                }
            }
        }
            setAble(true);
    }

    return (
        <section className={styles.box}>
            <div className={styles.centering}>
                <object type="image/svg+xml" data="/loading.svg" hidden={loading} ></object>
            </div>
            {data && (
                    <>
                        <h3 className={styles.centering}>Marks: {score} /10</h3>
                        <p className={styles.category}>{data[quesno].category}</p>
                        <p className={styles.type}>Type: {data[quesno].type}</p>
                        <p className={styles.difficulty}>Difficulty: {data[quesno].difficulty}</p>
                        <p className={styles.question}>{data[quesno].question}</p>

                        {answersArr.map(answer => (
                            <div className={styles.buttonarrangement}>
                            <button className={styleButton} key={answer} onClick={ () => checkAnswer(answer)} disabled={able} >{answer}</button>
                            </div>
                        ))}
                    </>
                )}

            {message && (
                <h3 className={styles.centering}>{message}</h3>
            )}
            <div className={styles.nextquestion}>
                <button className={styles.nextbutton}  onClick={ () => nextQuestion()}>Next question</button>
            </div>
        </section>
    );
}

How to effectively create a user role table that handles many switches using React JS?

Description

I want to create table like this :

enter image description here

However, I have done it well, but I am doubtful of my code, it seems too complicated and not simple.

Here’s my code so far :

const FormCreateRole = ({ switches, onChange }) => {
  // Array for table header and its data
  const tableHeader = [
    "No",
    "Menu",
    "Sub Menu",
    "Lihat",
    "Tambah",
    "Ubah",
    "Hapus",
    "Export",
  ];

  const submenu = [
    ["-"],
    [
      "Akun Pengguna",
      "Grup & Kontrol Hak Akses Akun",
      "Antrian Pasien",
      "Rawat Jalan",
    ],
    ["Pemeriksaan Penunjang", "Rekam Medis", "Admisi Rawat Jalan"],
    ["Status dan Penempatan Kamar", "Transfer Pasien"],
  ];

  let i = 1;

  const tableDataMenu = [
    [i++, "Dashboard", submenu[0], "", null, null, null, ""],
    [i++, "Konfigurasi/Pengaturan", submenu[1], "", "", "", "", null],
    [i++, "Layanan Pasien", submenu[2], "", "", "", "", null],
    [i++, "Rawat Inap", submenu[3], "", "", "", "", null],
  ];
  // end Array data

  return (
    <Table className="table-responsive">
      <thead style={{ backgroundColor: "#ECEFF1" }}>
        <tr>
          {tableHeader.map((header, index) => (
            <th
              key={index}
              className="txt-blue-grey-700 base-md text-bold text-center"
              style={{ padding: "0.75rem" }}
            >
              {header}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {tableDataMenu.map((row, idx) => (
          <React.Fragment key={idx}>
            <tr>
              {row.slice(0, 2).map((cell, idx) => (
                <td key={idx} className="text-center">
                  {cell}
                </td>
              ))}
              <td>
                {row[2] && (
                  <div>
                    {row[2].map((sub, idx) => (
                      <div key={idx} className="mb-3">
                        {sub}
                      </div>
                    ))}
                  </div>
                )}
              </td>
              {row.slice(3).map((cell, idx) => {
                return (
                  <td key={idx}>
                    {row[2] &&
                      row[2].map((subIdx) => {
                        if (cell !== null) {
                          return (
                            <div key={subIdx} className="mb-3 text-center">
                              <Form.Check
                                type="switch"
                                id={`${subIdx}-${idx}`}
                                label=""
                                checked={switches[`action${idx}`]}
                                onChange={onChange}
                              />
                            </div>
                          );
                        }
                      })}
                  </td>
                );
              })}
            </tr>
          </React.Fragment>
        ))}
      </tbody>
    </Table>
  );
};

Question

Can you help me in efficiently, readable and effectively creating the code for the table? I apologize, I am currently learning a lot and struggling to master React JS.

Any help will be appreciated, thank you.

javascript event loop with I/O-bound operations

sorry to ask something sounds a bit stupid. I’ve looked up a bunch of documents and asked some people but I am still a bit confused.

So my question is:

  • Let’s say I have 3 jobs currently, two of them (A, B) are synchronized jobs, and one (C) is a time-consuming asynchronized I/O bound operation.

  • So at first, A and B are in the call stack and C is in the callback queue. After A and B are finished, C would be pushed onto the call stack and starts to execute. But while C is running, a new synchronized job D is entered

  • Now, what happens?

I understand that if C is CPU-bound, then the execution would be just A->B->C->and D. And what I found online or in the document is that once a job starts to execute, even if it is an I/O bound, it will still finish it up first. but if that is, then why is javascript still a non-blocking language?

And plus what I found in my experience is that in my express server, if I have a function that spends a very long time querying in the database, and another request just entered, it wouldn’t block by the querying.

Randomly generate sprite. Is date.now() making this random

https://codepen.io/KilledByAPixel/pen/ZEWyRwO

I came across this really cool random pixel sprite generator.

Checking out the code, I can see that the code generates a sprite based on a seed determined by Date.now()

Based on your understanding of this code, does this mean that every time you refresh, the sprites should be unique?

Of course nothing is infinite, but is the chances of duplicate negligible?

Or am I misunderstanding this code.

let seed, x, R, i, j, pass, s, X, Y;

seed = Date.now();    // seed for random generaton, can be replaced with hardcoded value
x = c.getContext`2d`; // 2d canvas context
x.lineWidth = 2;      // set 2 pixel wide line width to make the black outline
R = ()=> (Math.sin(++s + i*i) + 1)*1e9 % 256 | 0; // get a seeded random integer between 0-256

for(i = 32 * 16; i--;)                          // for each sprite (32 rows x 16 columns)
for(pass = 4; pass--;)                          // 4 passes, outline left/right and fill left/right
for(s = seed, j = R()/5 + 50|0; j--;)           // set seed, randomize max sprite pixels, 50-101
  X = j&7, Y = j>>3,                            // X & Y pixel index in sprite
  R() < 19 ?                                    // small chance of new color
    x.fillStyle = `rgb(${R()},${R()},${R()})` : // randomize color
    R()**2 / 2e3 > X*X + (Y-5)**2 &&            // distance from center vs random number
      x[pass&2 ? 'strokeRect' : 'fillRect'](    // stroke first for outline then fill with color
          7 + i%32*16 - pass%2*2*X + X,         // x pos, flipped if pass is even
          2 + (i>>5)*16 + Y,                    // y pos
          1, 1);                                // 1 pixel size

I am wondering if this code will always generate unique sprites. Or course, possibilities are probably in the trillions, but assuming Date.now() always created a unique seed, is this always going to be unique?

why won’t any of my JavaScript work in my html?

first off I have both my JavaScript and my html files in the same folder. I cannot understand why none of my javascript works in the html file.

I have tried putting the Script directly into the html file without sourcing the Script file. I have attempted 3 different ways of adding my function to the html file to no avail. I am trying to make a hangman game for practice because I figured it was probably the easiest thing to try after going thru all the classes I took. However, I cannot even get through testing if my JavaScript even works. I’ll let the code speak for itself. (this JS code is within the body of the html file if that helps)
1st try:
html:

<div id="game">
  <button id="testA" onclick="showWord()">show word</button>
  <p id="word"></p>
</div>

external JS file code:

function showWord() {
document.getElementById("word").innerHTML = "test";}

2nd try:
html:

<div id="game">
  <button id="testA">show word</button>
  <p id="word"></p>
</div>

external JS file code:

function showWord() {
    document.getElementById("testA").addEventListener("click", function(){
    document.getElementById("word").innerText = "test";}

after this, I tried adding this code directly to the script tag and omitted the external script and still no luck. I also tried adding the onclick attribute to the html file with this with no change.
3rd try:(tried saving the element selection to a global variable here in case that was the problem)
html:

<div id="game">
      <button id="testA" onclick="showWord()">show word</button>
      <p id="word"></p>
</div>

external JS file code:

const test = document.querySelector("#word");
function showWord() {
    test.innerHTML = "try 3";
}

still… no change… please help!

contenteditable inside div is main

When I put a div in it contenteditable I want the first thing the user writes to create a div that is basic and not deleted and the text is inside the div

I do not like this :

enter image description here

I like this :

enter image description here

Even if the user deletes everything, there remains a div that he writes inside

Masonry Desandro grid height not fit the items after append item with ajax

This my first init code (Before append item with ajax):

 $('#edrea-ajax-wrapper').imagesLoaded( function() {
        $('#edrea-ajax-wrapper').masonry({
            itemSelector: '.edrea-card',
            transitionDuration: '1.4s',
            columnWidth: '.edrea-grid-sizer'
        });
    });

And this the code on my ajax:

   $.ajax({
      type: "POST", 
      url: ajax_url,
      dataType: 'html',
      data: {
         action:'edrea_load_more',
         count: total_posts
      },
      success: function( res ){

         if( res.length > 0 ) {
             var $content = $( res );
             $('#edrea-ajax-wrapper').imagesLoaded().done( function() {
                  $('#edrea-ajax-wrapper').append( $content ).masonry( 'appended', $content );
              });
             $('#edrea-ajax-wrapper').masonry('layout');
          } 
        },
   });

But, after I reload the page atleast once, the masonry work properly. This thing is only happens when I open the page on first time (Incognito mode or If after I clear the cache).

Thanks for the help!

I’ve been try use imagesLoaded plugin from Desandro itself, but still got this problem.

Typing a function that takes object with functions and binds them to the object

I’m typing this function for this weird library I’m writing for fun, and it takes an input object with methods and maps the methods to an output object whose methods call the input methods, but with the output object as the first parameter.

For example, turning this

{ f(thing, x, y) { ... } /* g()... */ }

to this:

thing = { f(x, y) { return (input object).f(thing, x, y); } }

I’ve typed it like this in typescript 5.0.1-rc (for the const generic)

export type Thing<T extends Record<string, (thing: Thing<T>, ...args: any[]) => unknown>> = {
    [K in keyof T]: T[K] extends (thing: Thing<T>, ...args: infer Args) => infer Return ? (...args: Args) => Return : never
};

declare function thingdoer<const T extends Record<string, (thing: Thing<T>, ...args: any[]) => unknown>>(input: T): Thing<T>;

and so this is nice and all if I do something like this,

thingdoer({ f() { ... } }).f();

but when I get it to take arguments,

thingdoer({ f(thing) { ... } }).f();

the signature of f() becomes (...args: any[]) => unknown, which I would rather not have happen.

Uncaught TypeError TypeError: collection.find(…).limit(…).toarray is not a function

I’m working with node and mongodb 5. A simplified version of my code is:

var murl = "mongodb://localhost:27017/local";
const client = new MongoClient(murl);
client.connect();
const database = client.db("mydata");
const collection = database.collection("p2");

async function getRecords(firstNum) {

  const filter = { 'total': { $exists: false }, 'UseCode': { $regex: /^00/ } };
  let records = await collection.find(filter).limit(firstNum).toarray();
  // let records = await collection.find(filter).limit(firstNum);
  // let records = collection.find(filter).limit(firstNum).toarray()
  console.log('number of records selected from db: ', records.length);
  return records;

}

async function run() {

  const records = await getRecords(firstNum);
  ....
}

run();

I’ve conformed that the filter works (in the compass gui) and firstnum is set to 1. I am getting the following error:

Uncaught TypeError TypeError: collection.find(...).limit(...).toarray is not a function
at getRecords (/home/gmail-username/node/netlifyfunction1/public/pimaBase.js:24:63)

What am I doing wrong?

How to show an alert to the first user with duplicate login?

I already made logic for remove session of first user when second user success login.

here is config

@WebListener
public class SessionConfig implements HttpSessionListener {
    
    private static final Map<String, HttpSession> sessions = new ConcurrentHashMap<>();
    
    public synchronized static String getSessionIdCheck(String type, String compareId) {
        String result = "";
        for(String key : sessions.keySet()) {
            HttpSession hs = sessions.get(key);
            if(hs != null && hs.getAttribute(type) != null && hs.getAttribute(type).toString().equals(compareId)) {
                result = key.toString();
            }
        }
        removeSessionForDoubleLogin(result);
        return result;
    }
    
    private static void removeSessionForDoubleLogin(String userId) {
        System.out.println("=========== remove userId : " + userId + " ===========");
        if(userId != null && userId.length() > 0) {
            sessions.get(userId).invalidate();
            sessions.remove(userId);
        }
    }
    
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("=========== sessionCreated : " + se + " =========== ");
        sessions.put(se.getSession().getId(), se.getSession());
    }
    
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        if(sessions.get(se.getSession().getId()) != null){
            sessions.get(se.getSession().getId()).invalidate();
            sessions.remove(se.getSession().getId());   
        }
    }
}

and here is controller

if(userId != null){
            String sessionChkUserId = SessionConfig.getSessionIdCheck("login_id", userId);
            System.out.println(userId + " : " + sessionChkUserId);
            session.setMaxInactiveInterval(60 * 60);
            session.setAttribute("login_id", userId);
}

In this case, removed session of first user and logout also back to login page.
And second user can connect website.

But I can not develope to show alert for first user when second user login.

How can I do this?

MapKit JS – Have Map Fit Height/Width of Browser

I’m working with MapKit JS for the first time and using the Custom Callout example from the Apple website. I’m trying to get the map to resize automatically to fit the size of the browser window but am getting stuck with this.

I can see there is a CSS style for the map height: 600px which presumably is the reason why the map is leaving an empty white space as shown in this screenshot:

enter image description here

I’ve tried adjusting this to height: 100% which results in a blank page and can’t work out the syntax to get the map to show in the whole window regardless of the size of the window.

Here’s the full code from the Apple example:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">

  <script src="https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js"></script>

  <style>
    #map {
      height: 600px;
    }
    
    a:link,
    a:visited {
      color: #2aaef5;
      outline: none;
      text-decoration: none;
    }
    
    .landmark {
      width: 250px;
      padding: 7px 0 0 0;
      background: rgba(247, 247, 247, 0.75);
      border-radius: 5px;
      box-shadow: 10px 10px 50px rgba(0, 0, 0, 0.29);
      font-family: Helvetica, Arial, sans-serif;
      -webkit-transform-origin: 0 10px;
      transform-origin: 0 10px;
    }
    
    .landmark h1 {
      margin-top: 0;
      padding: 5px 15px;
      background: #2aaef5;
      color: rgba(255, 255, 255, 0.9);
      font-size: 16px;
      font-weight: 300;
    }
    
    .landmark section {
      padding: 0 15px 5px;
      font-size: 14px;
    }
    
    .landmark section p {
      margin: 5px 0;
    }
    
    .landmark:after {
      content: "";
      position: absolute;
      top: 7px;
      left: -13px;
      width: 0;
      height: 0;
      margin-bottom: -13px;
      border-right: 13px solid #2aaef5;
      border-top: 13px solid rgba(0, 0, 0, 0);
      border-bottom: 13px solid rgba(0, 0, 0, 0);
    }
    
    @-webkit-keyframes scale-and-fadein {
      0% {
        -webkit-transform: scale(0.2);
        opacity: 0;
      }
      100% {
        -webkit-transform: scale(1);
        opacity: 1;
      }
    }
    
    @keyframes scale-and-fadein {
      0% {
        transform: scale(0.2);
        opacity: 0;
      }
      100% {
        transform: scale(1);
        opacity: 1;
      }
    }
  </style>

</head>

<body>
  <div id="map"></div>

  <script>
    mapkit.init({
      authorizationCallback: function(done) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "/services/jwt");
        xhr.addEventListener("load", function() {
          done(this.responseText);
        });
        xhr.send();
      }
    });

    // Landmarks data
    var sanFranciscoLandmarks = [{
        coordinate: new mapkit.Coordinate(37.7951315, -122.402986),
        title: "Transamerica Pyramid",
        phone: "+1-415-983-5420",
        url: "http://www.transamericapyramidcenter.com/"
      },
      {
        coordinate: new mapkit.Coordinate(37.7954201, -122.39352),
        title: "Ferry Building",
        phone: "+1 (415) 983-8030",
        url: "http://www.ferrybuildingmarketplace.com"
      },
      {
        coordinate: new mapkit.Coordinate(37.8083396, -122.415727),
        title: "Fisherman's Wharf",
        phone: "+1 (415) 673-3530",
        url: "http://visitfishermanswharf.com"
      },
      {
        coordinate: new mapkit.Coordinate(37.8023553, -122.405742),
        title: "Coit Tower",
        phone: "+1 (415) 249-0995",
        url: "http://sfrecpark.org/destination/telegraph-hill-pioneer-park/coit-tower/"
      },
      {
        coordinate: new mapkit.Coordinate(37.7552305, -122.452624),
        title: "Sutro Tower",
        phone: "+1 (415) 681-8850",
        url: "http://www.sutrotower.com"
      },
      {
        coordinate: new mapkit.Coordinate(37.779267, -122.419269),
        title: "City Hall",
        phone: "+1 (415) 701-2311",
        url: "http://sfgsa.org/index.aspx?page=1085"
      },
      {
        coordinate: new mapkit.Coordinate(37.8184493, -122.478409),
        title: "Golden Gate Bridge",
        phone: "+1 (415) 921-5858",
        url: "http://www.goldengatebridge.org"
      },
      {
        coordinate: new mapkit.Coordinate(37.7785538, -122.514035),
        title: "Cliff House",
        phone: "+1 (415) 386-3330",
        url: "http://www.cliffhouse.com/"
      }
    ];

    // Landmark annotation callout delegate
    var CALLOUT_OFFSET = new DOMPoint(-148, -78);
    var landmarkAnnotationCallout = {
      calloutElementForAnnotation: function(annotation) {
        return calloutForLandmarkAnnotation(annotation);
      },

      calloutAnchorOffsetForAnnotation: function(annotation, element) {
        return CALLOUT_OFFSET;
      },

      calloutAppearanceAnimationForAnnotation: function(annotation) {
        return ".4s cubic-bezier(0.4, 0, 0, 1.5) 0s 1 normal scale-and-fadein";
      }
    };

    // Landmarks annotations
    var annotations = sanFranciscoLandmarks.map(function(landmark) {
      var annotation = new mapkit.MarkerAnnotation(landmark.coordinate, {
        callout: landmarkAnnotationCallout,
        color: "#c969e0"
      });
      annotation.landmark = landmark;
      return annotation;
    });

    var map = new mapkit.Map("map");
    map.showItems(annotations);

    // Landmark annotation custom callout
    function calloutForLandmarkAnnotation(annotation) {
      var div = document.createElement("div");
      div.className = "landmark";

      var title = div.appendChild(document.createElement("h1"));
      title.textContent = annotation.landmark.title;

      var section = div.appendChild(document.createElement("section"));

      var phone = section.appendChild(document.createElement("p"));
      phone.className = "phone";
      phone.textContent = annotation.landmark.phone;

      var link = section.appendChild(document.createElement("p"));
      link.className = "homepage";
      var a = link.appendChild(document.createElement("a"));
      a.href = annotation.landmark.url;
      a.textContent = "website";

      return div;
    }
  </script>
</body>

</html>

Adding a dollar sign next to a span?

I’m working on a budget app that lets the user write in their budget and as many expenses as the user wishes.
The total budget, expenses, and balance (each of these is a span tag in HTML) are kept in a container div.

I want to add a dollar sign next to each of these spans. How do I add a dollar sign that sits right next to the amount? I need to make it a separate tag from the money tags.

I tried adding it in the form of a template string such as

amount.innerHTML = `$${tempAmount}`
expenditureValue.innerText = `$${sum};

However, doing this results in messing up with numbers adding together. Adding more than one expense results in “NaN” appearing on the page.

I also tried adding it into the HTML page, but the dollar sign is skewed from the number result. It ends up looking like:

$
    10000

Any advice on what I can do?

Rotate IMG based on cursor coordinates

I’m trying to create a website using next.js, tailwind.css and wanted to create an animation, which rotates an image of these eyeballs so it looks at the cursor when navigating the webpage
**
index.tsx**

const HomePage = () => {
  return (
    
  <container>
    <script src="eyeball.js" defer></script>
    <div class="drop-shadow-sm h-2 bg-gradient-to-r from-sky-500 to-indigo-500"></div>
    
    <nav class="drop-shadow-lg bg-white border-gray-200 px-2 sm:px-4 py-2.5 rounded dark:bg-slate-900">
      <div class="absolute container flex flex-wrap items-center justify-between mx-auto">
        <a href="https://jonas.wiki/" class="flex items-center">
          <img src="logo.svg" class="h-6 mr-3 sm:h-9" alt="wiki" />
          <span class="self-center text-xl font-semibold whitespace-nowrap dark:text-white">Jonas.wiki</span>
        </a>
        <button data-collapse-toggle="navbar-default" type="button" class="inline-flex items-center p-2 ml-3 text-sm text-gray-500 rounded-lg md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600" aria-controls="navbar-default" aria-expanded="false">
          <span class="sr-only">Open main menu</span>
          <svg class="w-6 h-6" aria-hidden="true" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"></path></svg>
        </button>
      <div class="hidden w-full md:block md:w-auto" id="navbar-default">
        <ul class="flex flex-col p-4 mt-4 border border-gray-100 rounded-lg bg-gray-50 md:flex-row md:space-x-8 md:mt-0 md:text-sm md:font-medium md:border-0 md:bg-white dark:bg-gray-800 md:dark:bg-slate-900 dark:border-gray-700">
          <li>
            <a href="#" class="block py-2 pl-3 pr-4 text-white bg-blue-700 rounded md:bg-transparent md:text-blue-700 md:p-0 dark:text-white" aria-current="page">Home</a>
          </li>
          <li>
            <a href="#" class="block py-2 pl-3 pr-4 text-gray-700 rounded hover:bg-gray-100 md:hover:bg-transparent md:border-0 md:hover:text-blue-700 md:p-0 dark:text-gray-400 md:dark:hover:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent">About</a>
          </li>
          <li>
            <a href="#" class="block py-2 pl-3 pr-4 text-gray-700 rounded hover:bg-gray-100 md:hover:bg-transparent md:border-0 md:hover:text-blue-700 md:p-0 dark:text-gray-400 md:dark:hover:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent">Services</a>
          </li>
          <li>
            <a href="#" class="block py-2 pl-3 pr-4 text-gray-700 rounded hover:bg-gray-100 md:hover:bg-transparent md:border-0 md:hover:text-blue-700 md:p-0 dark:text-gray-400 md:dark:hover:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent">Pricing</a>
          </li>
          <li>
            <a href="#" class="block py-2 pl-3 pr-4 text-gray-700 rounded hover:bg-gray-100 md:hover:bg-transparent md:border-0 md:hover:text-blue-700 md:p-0 dark:text-gray-400 md:dark:hover:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent">Contact</a>
          </li>
        </ul>
      </div>
      </div>

    </nav>
    <section class= "block grid grid-cols-2 gap-0 container mx-auto md:w-2/3 lg:w-1/2 segment content-center bg-transparent h-300">
      <img id="anchor" class=" mt-20 -z-50 absolute h-96 w-96 " src="/jones_1024_v2.png" alt="Jones"></img>
      <div id="eyes" class="block">
        <img id="eye" class="mt-[132px] ml-[160px] z-20" src="/jones_eye.png" alt="Jones Eye"></img>
        <img id="eye" class="mt-[132px] ml-[188px] -z-20" src="/jones_eye.png" alt="Jones Eye"></img>
      </div>
    </section>
    <section class= "drop-shadow-xl z-20 grid grid-cols-2 gap-1 container mx-auto md:w-2/3 lg:w-1/2 segment content-center bg-slate-900 rounded-md mt-60">
      
        <div class= "py-0 mx-auto h-full grid col-start-1">
          
          <div class= "rounded-md mx-10 py-2 pl-0 h-max">
            <h1 class = "mx-5 text-2xl text-left text-white-600">Hello!</h1>           
            <div class= "mt-2 rounded-md mx-5 py-0 pl-0 h-200 bg-gradient-to-r from-sky-500 to-indigo-500">

              <h1 class = "mx-2 text-2l text-left text-white-600 ">
                My name is Jonas Lindegaard Veile.
                
              </h1>  
            </div>
          </div>
        </div>
        <div class= "py-60 mx-auto h-full grid col-start-2">
          
          <div class= "rounded-md mx-10 py-2 pl-0 h-max">
            <h1 class = "mx-5 text-2xl text-left text-white-600">Hello!</h1>           
            <div class= "mt-2  rounded-md mx-5 py-0 pl-0 h-200 bg-gradient-to-r from-sky-500 to-indigo-500">
              <h1 class = "mx-2 text-2l text-left text-white-600 ">
                My name is Jonas Lindegaard Veile.
              </h1>  
            </div>
          </div>
        </div>

      
        
      

    
    </section>
    


  </container>
  

 
  
    
  )
}

This is my javascript – I get the console to show coordinate output but I won’t let me rotate my imported image.

eyeball.js

document.addEventListener('mousemove', (e) => {
    
    console.log(e)

    const mouseX = e.clientX;
    const mouseY = e.clientY;
  
    const anchor = document.getElementById('anchor')
    const rekt = anchor.getBoundingClientRect();
    const anchorX = rekt.left + rekt.width / 2;
    const anchorY = rekt.top + rekt.height / 2;
  
    const angleDeg = angle(mouseX, mouseY, anchorX, anchorY)
  
    console.log(angleDeg)
    
    const eyes = document.querySelectorAll('.eye')
    eyes.forEach(eye => {
      eye.style.transform = "rotate(${90 + angleDeg}deg)";
    })
  
  })
  
  function angle(cx, cy, ex, ey){
    const dy = ey - cy;
    const dx = ex - cx;
    const rad = Math.atan2(dy, dx);
    const deg = rad * 180 / Math.PI;
    return deg;
  }`

Does anybody have an idea what might be wrong?:)

I tried changing altering between display, position and such in html/css and tried selecting other images to rotate but nothing has worked so far. The only thing which seems to work is getting the coordinates of the cursor