How does one add an image to different id’s in a constant in javascript for a text based adventure game? Please it’s for my girlfriend

I am following this tutorial to build a text based adventure game. Here is the code for the entire game that is mine too.

I’d like to add an image to each page of the game. For example, this:

const textNodes = [
  {
    id: 1,
    text: 'you walk down the road blah blah',
    options: [
      {
        text: 'Take the goo',
        setState: { blueGoo: true },
        nextText: 2
      },
      {
        text: 'Leave the goo',
        nextText: 2
      }
    ]

is a constant where i’d like to add the image to. This:

var imagesDatabase = {
    '1': src="images/bs1.jpg",
    '2': src="images/bs2.jpg",
    '3':src="images/bulb.png"
} 

  var theImageDiv = document.createElement('div');
  theImageDiv.innerHTML = "<img id='the-image-bro' src='" + imagesDatabase[textNodeIndex] + "' height=150 length=500 style='position: fixed; top: 50%'>"
  
  document.getElementById('imagediv').appendChild(theImageDiv);

is the code someone in the comments sugested but it doesn’t work for me. Especially the innerHTML = I dont know what to write there then.

I’d appreciate help a lot. All I wanna do is add an image to each page of the game.

Is it possible to do prop drilling from React Class Component to Functional Component?

I am currently working some React Class Component Code and wanna do a props drilling to allow the child functional component call alert functions in the parent Component.
Specifically, I am doing the following:
In this class constructor, I made the binding:
this.setPtbrRequestAlert = this.setPtbrRequestAlert.bind(this);

setPtbrRequestAlertFunction

And in the section where I pass down the props function, I did this:
Props drilling from Parent to child

However, in the child component, props passed are destructured but I am not able to use them in the functional component as these props are not found.
Can not find name

Can somebody explain what is wrong with this props drilling? Why am I not able to reference these values by desturturing them in the functional child component and if there is a way to address it?

I know somebody may wanna suggest refactor all the codes to functional component but I am trying not to mess around with Prod code right now. I want to gracefully implement new features with functional component and refactor old codes in the future gradually.
Thanks in advance!

Property does not exist on type when using Or for multiple types

In my Angular component I have an Input that will be provided 1 of 2 types.

@Input() profile: UserProfileDetails | BusinessProfileDetails;

The profile template is simple and I’d like to use only the single template so I am not duplicating code. But because the types differ in properties I am receiving a template error.

export interface UserProfileDetails {
  createdOn: Date;
  id: string;
  name: string;
}
export interface BusinessProfileDetails {
  businessId: string;
  businessLocation: string;
  createdOn: Date;
  id: string;
  name: string;
}

and the code in my template:

<div>
  <h1>{{profile.name}}</h1>
  <div>{{profile.createdOn}}</div>
  <div>{{profile.id}}</div>
  <div *ngIf="profile?.businessId">{{profile.businessId}}</div>
  <div *ngIf="profile?.businessLocation">{{profile.businessLocation}}</div>
</div>

I believe I understand why I am receiving the error, but I’m unsure how to resolve the issue while still using the or condition @Input() profile: UserProfileDetails | BusinessProfileDetails;

How do I allow a button “Click” handler to access variables defined by the code that creates the button?

I have code that runs in a report web page for a COTS product via the jQuery.ready() function. My code has 2 parts: The “setup” code checks for a bunch of prerequisites and, if all conditions are good, it creates a button & adds a click handler for the button using AddEventListener.
The second part is the click handler. In that I need most of the same variables that I defined in the “setup” portion. The quick and dirty way to do it is just copy the code from the “setup” but that seems inefficient and prone to error if I change something in the “setup” part and forget to replicate it in the “click handler”.

Is there a way I can pass the variables I define in the “setup” section to an asynchronous event like a click handler?

// the click handler
const delAllSelected = () => {
   // In here I also need the "top_frame", "rpt_doc", "tbl_rptOutput" variables 
   //   defined in the "setup" portion.
   //  ... do stuff ...
}


// setup portion 
jQuery(document).ready(function () {
   var top_frame= top.window.document.querySelector("[name*=reportDialog]");
   var rpt_doc = top?.window?.frames[0]?.frames["List"]?.document;
   var tbl_rptOutput = rpt_doc.querySelector("#ReportOutput");
    ...etc...
   // if all the stars align, create a button and attach click handler
   if (all conditions good) {
       rpt_doc.querySelector("#CheckboxButtons td.btnFrame").insertAdjacentHTML("beforeend",`
       ... html for the "Delete All Selected" button goes here ...
       `);
       tbl_rptOutput.querySelector("#DeleteAllSelected").addEventListener("click",delAllSelected);
    }
}

Ajax Laravel8 – auto populate fields based on selected dropdown value not working

I have a simple form page where I want to display the details of a client based on the selected client, I am a newbie to ajax and I’ve had this problem for quite some time and I really can’t get to make it work.

Note: “Nume” is not a typo, its the way I included it in my db instead of name
Also: id =’sel_depart’ is the id of the selected client
And, name=”sel_emp” id=”sel_emp” is where I want his details to be displayed (which is “iban”)

This is my controller:

public function getClientspay( Request $request, $id){
      $clientsid = $request->clientsid;
      $clients = clients::select('*')->where('id', $clientsid)->get();
     $response['data'] = $clients;
     
     return response()->json($response);
    }

This is my route:

Route::get('/getClientspay', [PlatiController::class,'getClientspay']);

This is the part of the form where I want to display it:

<div class="row">
<label for="">Nume Client</label>
<label for="">Introduceti ID</label>
<select id ='sel_depart' name='sel_depart' >
@foreach ($clients as $clients)
 

 <option   name='search' value="{{$clients->id}}">{{$clients->nume}}</option>
@endforeach
</select>
<select name="sel_emp" id="sel_emp">
<option value="0"></option>


</select>

And this is my ajax request

 $('#sel_depart').change(function(){

         // Department id
         var id = $(this).val();

         // Empty the dropdown
         $('#sel_emp').find('option').not(':first').remove();

         // AJAX request 
         $.ajax({
           url: 'getClientspay',
           type: 'get',
           data: {_token: CSRF_TOKEN, clientsid: clientsid},
           dataType: 'json',
           success: function(response){

             var len = 0;
             if(response['data'] != null){
               len = response['data'].length;
             }

             if(len > 0){
               // Read data and create <option >
               for(var i=0; i<len; i++){

                 var id = response['data'][i].id;
                 var iban = response['data'][i].iban ;

                 var option = "<option value='"+id+"'>"+iban+"</option>"; 

                 $("#sel_emp").append(option); 
               }
             }

           }
        });
      });

    });

Resource response style in express js with API?

I’m a nob in expressjs and just using it so I have this response in my controller

....
res.json({
    'data': {
        'user': {
            'id': user.id,
            'name': user.name,
            'email': user.email,
        },
        'token': token
    }
});

In Laravel, there is something called eloquent-resources that takes the data of something and puts it in a separate class, and arranges this data as you need!

IS there any thing like this in express js

Javascript Cannot read property ‘push’ of undefined

i have a problem in a game while using javascript and html.
Uncaught TypeError: Cannot read property 'push' of undefined (@mtl-drivingschool/assets/js/javascript.js:44)

So now i don’t know what i can do, i edited so much but i don’t find the error.
I use the game GTA V and FiveM, thats the only error i get. I tried to use an javascript compiler but i don’t get anything because its weird. It’s because its nested wrong?

Theory.html

$(document).ready(function () {
  var currentQuestion = 1;
  var userAnswer = [];
  var goodAnswer = [];
  var usedQuestions = [];
  var displayedQuestions = 10;
  var needRightAnswers = 8;
  var possibleQuestions = 15;

  function initializeQuestions() {
    var randomQuestion = getRandomQuestions();
    $("#questionHeader").html("Frage Nr. " + currentQuestion + ": ");
    $("#questionSelf").html(tableQuestions[randomQuestion].question);
    $(".answerA").html(tableQuestions[randomQuestion].propositionA);
    $(".answerB").html(tableQuestions[randomQuestion].propositionB);
    $(".answerC").html(tableQuestions[randomQuestion].propositionC);
    $(".answerD").html(tableQuestions[randomQuestion].propositionD);
    $("input[name=question]").attr("checked", false);
    goodAnswer.push(tableQuestions[randomQuestion].response);
  }

  function getRandomQuestions() {
    var continueQuestion = true;
    var random;
    while (continueQuestion) {
      continueQuestion = false;
      random = Math.floor(Math.random() * possibleQuestions);
      if (currentQuestion == 1) {
        return random;
      }
      for (i = 0; i < currentQuestion - 1; i++) {
        if (random == usedQuestions[i]) {
          continueQuestion = true;
        }
      }
    }
    usedQuestions.push(random);
    return random;
  }

  $("#question-form").submit(function (e) {
    e.preventDefault();
    if (currentQuestion != displayedQuestions) {
      userAnswer.push($('input[name="question"]:checked').val());
      currentQuestion++;
      initializeQuestions();
    } else {
      userAnswer.push($('input[name="question"]:checked').val());
      var goodAnswer = 0;
      for (i = 0; i < possibleQuestions; i++) {
        if (userAnswer[i] == goodAnswer[i]) {
          goodAnswer++;
        }
      }

      if (goodAnswer >= displayedQuestions) {
        //openResultGood();
      } else {
        //openResultBad();
        var currentQuestion = 1;
        var userAnswer = [];
        goodAnswer = [];
        var usedQuestions = [];
      }
    }
  });

  var btnContainer = document.getElementById("sidebar");

  var btns = btnContainer.getElementsByClassName("nav-link");

  var homeButton = document.getElementById("homeButton");
  var LogInButton = document.getElementById("LogInButton");
  var theoryButton = document.getElementById("theoryButton");
  document.getElementById("spinner-anmeldung").style.display = "none";
  

  var registerButton = document.getElementById("anmelden-button");
  registerButton.onclick = function (event) {
    // ANMELDEN ON CLICK
  };

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

      var containHomeButton = homeButton.classList.contains("active");
      var containLogInButton = LogInButton.classList.contains("active");
      var containTheoryButton = theoryButton.classList.contains("active");

      if (!containHomeButton) {
        document.getElementById("home").style.display = "none";
      } else {
        document.getElementById("home").style.display = "block";
      }

      if (!containLogInButton) {
        document.getElementById("anmelden").style.display = "none";
        document.getElementById("wrong-personalData").style.display = "none";
        document.getElementById("right-personalData").style.display = "none";
      } else {
        document.getElementById("anmelden").style.display = "block";
        document.getElementById("wrong-personalData").style.display = "none";
        document.getElementById("right-personalData").style.display = "none";
      }

      if (!containTheoryButton) {
        document.getElementById("theorie").style.display = "none";
      } else {
        document.getElementById("theorie").style.display = "block";
        initializeQuestions();
      }
    });
  }

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'=/]/g, function (s) {
      return entityMap[s];
    });
  }

  $(function () {
    window.onload = function (event) {
      window.addEventListener("message", (event) => {
        var item = event.data;
        if (item !== undefined && item.type === "ui")
          if (item.display === true) {
            $("#fullscreen").css("display", "block");
          } else {
            $("#fullscreen").css("display", "none");
          }
      });
    };

    $("#closeButton").click(function () {
      $.post("https://mtl-drivingSchool/close", JSON.stringify({}));
      return;
    });

    $("#anmelden-button").click(function () {
      let inputValueVorname = escapeHtml($("#Vorname").val());
      let inputValueNachname = escapeHtml($("#Nachname").val());
      let inputValueStrasse = escapeHtml($("#Strasse").val());
      let inputValueHausnummer = escapeHtml($("#Hausnummer").val());
      let inputValuePLZ = escapeHtml($("#PLZ").val());
      let inputValueStadt = escapeHtml($("#Stadt").val());

      spinner = document.getElementById("spinner-anmeldung").style.display =
        "block";
      var registerButton = document.getElementById("anmelden-button");
      registerButton.disabled = true;
      //setTimeout(() => {}, 4000);

      spinner = document.getElementById("spinner-anmeldung").style.display =
        "none";
      $.post(
        "https://mtl-drivingSchool/checkPersonalData",
        JSON.stringify({
          Vorname: inputValueVorname,
          Nachname: inputValueNachname,
          Strasse: inputValueStrasse,
          Hausnummer: inputValueHausnummer,
          PLZ: inputValuePLZ,
          Stadt: inputValueStadt,
        })
      );
    });
  });
});
@font-face {
    font-family: 'Akrobat';
    src: url('../fonts/subset-Akrobat-Bold.woff2') format('woff2'),
        url('../fonts/subset-Akrobat-Bold.woff') format('woff'),
        url('../fonts/subset-Akrobat-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
    font-display: swap;
}

@font-face {
    font-family: 'Akrobat';
    src: url('../fonts/subset-Akrobat-Regular.woff2') format('woff2'),
        url('../fonts/subset-Akrobat-Regular.woff') format('woff'),
        url('../fonts/subset-Akrobat-Regular.ttf') format('truetype');
    font-weight: 500;
    font-style: normal;
    font-display: swap;
}

@font-face {
    font-family: 'Akrobat';
    src: url('../fonts/subset-Akrobat-Light.woff2') format('woff2'),
        url('../fonts/subset-Akrobat-Light.woff') format('woff'),
        url('../fonts/subset-Akrobat-Light.ttf') format('truetype');
    font-weight: 300;
    font-style: normal;
    font-display: swap;
}

@font-face {
    font-family: 'Akrobat';
    src: url('../fonts/subset-Akrobat-Regular_1.woff2') format('woff2'),
        url('../fonts/subset-Akrobat-Regular_1.woff') format('woff'),
        url('../fonts/subset-Akrobat-Regular_1.ttf') format('truetype');
    font-weight: 500;
    font-style: normal;
    font-display: swap;
}

html, body, p {
    margin: 0;
    line-height: 1.5;
    font-family: Akrobat, sans-serif !important;
}

h1, h2, h3, h4, h5, h6 {
    font-family: Akrobat, sans-serif !important;
    font-weight: 500;
}

.nav-link.active {
    background-color: #22252e !important;
}

#fullscreen {
    display: none;
}

#anmelden, #theorie {
    display: none;
}
<!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">
        <title>Theorieprüfung</title>

        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        <link href="../css/style.css" rel="stylesheet" />
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
        <link rel="preload" href="../fonts/subset-Akrobat-Bold.woff2" as="font" type="font/woff2" crossorigin>

        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
        <script src="nui://game/ui/jquery.js" type="text/javascript"></script>
        <script type="text/javascript" src="../js/questions.js"></script>
        <script type="text/javascript" src="../js/javascript.js"></script>
        <script type="text/javascript" src="https://cfx-nui-mtl-drivingSchool/javascript.js" async></script>
    </head>
    <body style="background: transparent !important;">
        <div id="fullscreen" class="container-fluid mt-5">
            <div class="container-sm d-flex mh-100 justify-content-center bg-light d-flex bd-highlight shadow" style="padding-left: 0 !important;">
                <div class="d-flex flex-column flex-shrink-0 pt-1" style="background-color: #313443 !important; width: 4.5rem;">
                    <a class="d-block p-3 link-dark text-center" style="border-bottom: 0px !important;" title="" >
                      <i class="bi bi-stoplights" style="color: lightyellow; font-size: 1.3rem;"></i>
                      <span class="visually-hidden">Icon-only</span>
                    </a>
                    <ul id="sidebar" class="nav nav-pills nav-flush flex-column mb-auto text-center" >
                      <li class="nav-item">
                        <a href="#" class="nav-link active py-3" id="homeButton" aria-current="page" title="" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-original-title="Start">
                            <i class="bi bi-house" style="color: white; font-size: 1.3rem;"></i>
                        </a>
                      </li>
                      <li>
                        <a id="LogInButton" href="#" class="nav-link py-3" title="" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-original-title="Anmelden">
                            <i class="bi bi-journal" style="color: white; font-size: 1.3rem;"></i>
                        </a>
                      </li>
                      <li>
                        <a id="theoryButton" href="#" class="nav-link py-3" title="" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-original-title="Prüfung">
                            <i class="bi bi-easel" style="color: white; font-size: 1.3rem;"></i>
                        </a>
                      </li>
                      <li>
                        <a id="closeButton" href="#" class="nav-link py-3" title="" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-original-title="Abmelden">
                            <i class="bi bi-door-open" style="color: white; font-size: 1.3rem;"></i>
                        </a>
                      </li>
                    </ul>
                </div>
                <div id="home" class="p-5 flex-fill mh-100 bd-highlight bg-light">
                    <h3>Herzlich Willkommen in der einzigartigen Fahrschule in ganz Nordrhein-Westfalen.</h3>
                    <br>
                    <p class="bg-light fs-5">
                        Wenn Sie uns zum ersten Mal besuchen, lesen Sie sich diesen Text durch. Wir erklären Ihnen den Ablauf zu einem ganz besonderen Freiheitsgefühl.
                        Zu Beginn melden Sie sich bitte bei uns an. Dazu benötigen Sie Ihren Personalausweis, den wir gerne für Sie scannen. Nach erfolgreicher Anmeldung
                        und dem Studieren der Lerninhalte können Sie den theoretischen Teil der Fahreignungsprüfung absolvieren. Dabei dürfen Sie maximal 2 Fehler haben.
                        <br><br>
                        Nachdem Sie die Theorie bestanden haben, erwartet Sie der praktische Teil der Fahreignungsprüfung. In dem Sie, für einen Fahranfänger geeigneten, Peugot 206
                        fahren. Dabei dürfen Sie weder zu schnell fahren, noch das Fahrzeug demolieren. Dabei dürfen Sie maximal 3 Fehler haben.
                        <br><br>
                        Bedenken Sie, dass Sie die Kosten für die Fahrprüfung nicht erstattet bekommen. Wir wünschen Ihnen viel Glück und Verstand.
                    </p>
                </div>

                <div id="anmelden" class="p-5 flex-fill mh-100 bd-highlight bg-light">
                  <h3>Anmeldeformular</h3>
                  <br>
                  
                  <div id="logInForm" class="container">
                    <div id="wrong-personalData" aria-live="polite" aria-atomic="true" class="bg-dark position-relative bd-example-toasts">
                      <div class="toast-container position-absolute p-3" id="toastPlacement">
                        <div class="toast">
                          <div class="toast-header">
                            <img src="..." class="rounded me-2" alt="...">
                            <strong class="me-auto">Fahrschule</strong>
                          </div>
                          <div class="toast-body">
                            Die Daten stimmen nicht überein, bitte mach es neu.
                          </div>
                        </div>
                      </div>
                    </div>

                    <div id="right-personalData" aria-live="polite" aria-atomic="true" class="bg-dark position-relative bd-example-toasts">
                      <div class="toast-container position-absolute p-3" id="toastPlacement">
                        <div class="toast">
                          <div class="toast-header">
                            <img src="..." class="rounded me-2" alt="...">
                            <strong class="me-auto">Fahrschule</strong>
                          </div>
                          <div class="toast-body">
                            Die Daten stimmen überein, geh weiter zur Theorieprüfung.
                          </div>
                        </div>
                      </div>
                    </div>
                    <form class="row g-3">
                      <div class="col-md-6">
                        <label for="Vorname" class="form-label">Vorname</label>
                        <input type="text" class="form-control" id="Vorname" placeholder="Max" required>
                      </div>
                      <div class="col-md-6">
                        <label for="Nachname" class="form-label">Nachname</label>
                        <input type="text" class="form-control" id="Nachname" placeholder="Mustermann" required>
                      </div>
                      <div class="col-6">
                        <label for="Straße" class="form-label">Straße</label>
                        <input type="text" class="form-control" id="Strasse" placeholder="Musterstr." required>
                      </div>
                      <div class="col-6">
                        <label for="Hausnummer" class="form-label">Hausnummer</label>
                        <input type="text" class="form-control" id="Hausnummer" placeholder="100" required>
                      </div>
                      <div class="col-md-6">
                        <label for="PLZ" class="form-label">PLZ</label>
                        <input type="text" class="form-control" id="PLZ" placeholder="12345" required>
                      </div>
                      <div class="col-md-6">
                        <label for="Stadt" class="form-label">Stadt</label>
                        <input type="text" class="form-control" id="Stadt" placeholder="Musterstadt" required>
                      </div>
                      <div class="col-12">
                        <div class="form-check">
                          <input class="form-check-input" type="checkbox" id="gridCheck" required>
                          <label class="form-check-label" for="gridCheck">
                            Ich akzeptiere die Datenschutzbestimmungen.
                          </label>
                        </div>
                      </div>
                      <div class="col-4 text-left">
                        <button id="anmelden-button" type="submit" class="mr-2 btn btn-primary" style="margin-right: 10px">Personalausweis zum Abgleich übergeben</button>
                        <div id="spinner-anmeldung" class="spinner-border" style="vertical-align: middle;" role="status">
                          <span class="visually-hidden">Laden...</span>
                        </div>
                      </div>
                    </form>
                  </div>
              </div>

              <div id="theorie" class="p-5 flex-fill mh-100 bd-highlight bg-light">
                <h3>Theorieprüfung</h3>
                <br>
                  <div class="row">
                    <div class="col-9">
                        <h5 id="questionHeader">Frage 1: </h5><h5 id="questionSelf">Lädt...</h5>
                        <form class="form" id="question-form">
                          <div class="form-check">
                            <input id="answerA" class="form-check-input" type="radio" name="question" id="answerA" value="A">
                            <label class="form-check-label answerA" for="flexRadioDefault1">
                              Lädt...
                            </label>
                          </div>
                          <div class="form-check">
                            <input id="answerB" class="form-check-input" type="radio" name="question" id="answerB" value="B">
                            <label class="form-check-label answerB" for="flexRadioDefault2">
                              Lädt...
                            </label>
                          </div>
                          <div id="answerC" class="form-check">
                            <input class="form-check-input" type="radio" name="question" id="answerC" value="C">
                            <label class="form-check-label answerC" for="flexRadioDefault2">
                              Lädt...
                            </label>
                          </div>
                          <div id="answerD" class="form-check">
                            <input class="form-check-input" type="radio" name="question" id="answerD" value="D">
                            <label class="form-check-label answerD" for="flexRadioDefault2">
                              Lädt...
                            </label>
                          </div><br>
                          <button type="submit" id="submit" class="mr-2 btn btn-primary" style="margin-right: 10px">Weiter</button>
                        </form>
                    </div>
                    <div class="col-3">
                      <div class="card text-dark bg-light" style="max-width: 18rem;">
                        <div class="card-body">
                          <h5 class="card-title">Fehlerpunkte</h5>
                          <p class="card-text bg-light">0/3</p>
                        </div>
                      </div><br>
                      <div class="card text-dark bg-light" style="max-width: 18rem;">
                        <div class="card-body">
                          <h5 class="card-title">Übrige Zeit</h5>
                          <p class="card-text bg-light">3 Minuten</p>
                        </div>
                      </div><br>
                    </div>
                  </div>
                  
            </div>
            </div>
        </div>          
    </body>
</html>
var tableQuestions = [
    {   question : "Wie schnell darf innerorts gefahren werden?",
        propositionA : "30 km/h",
        propositionB : "50 km/h",
        propositionC : "100 km/h",
        propositionD : "70 km/h",
        response : "D"
    },
    {   question : "Ein alter Mann geht auf einen Fußgängerüberweg zu. Wie reagierst du?",
        propositionA : "Beschleunigen, und vor ihm die Straße zu queeren.",
        propositionB : "Schlagartig Bremsen und 10 Meter vor dem Überwegr anhalten.",
        propositionC : "Bremsen und kurz vor dem Überweg halten und den Mann passieren lassen.",
        propositionD : "Umkehren",
        response : "C"
    },
    {   question : "Sie überholen auf einer Autobahn. Von hinten nähert sich ein Pkw mit hoher Geschwindikeit, Lichthupe und eingeschaltetem Blinker. Wie verhalten sie sich?",
        propositionA : "Auch Beschleunigen und vor ihm bleiben.",
        propositionB : "Ich verzögere.",
        propositionC : "Ich überhole weiter.",
        propositionD : "Ich bremse stark ab.",
        response : "C"
    },
    {   question : "Wozu kann eine plötzliche Verschlechterung des Fahrbahnzustandes führen?",
        propositionA : "Reifen gehen kaputt.",
        propositionB : "Zu schleuder- und Rutschgefahr",
        propositionC : "Schnneleres beschleunigen",
        propositionD : "Verzögerte Reaktionszeit",
        response : "D"
    },
    {   question : "Welchen Mindestabstand von eriner Ampel muss ein Fahrzeug beim Halten einhalten, wenn diese druch das Fahrzeug vedeckt würde?",
        propositionA : "10 Meter",
        propositionB : "5 Meter",
        propositionC : "15 Meter",
        propositionD : "20 Meter",
        response : "A"
    },
    {   question : "Wie schnell darf man auf der Autobahn Fahren?",
        propositionA : "140 km/h",
        propositionB : "80 km/h",
        propositionC : "100 km/h",
        propositionD : "200 km/h",
        response : "A"
    },
    {   question : "Ein Fahrzeug mit Blaulicht nähert sich. Wie reagierst du?",
        propositionA : "Ich bleibe stehen.",
        propositionB : "Ich fahre normal weiter.",
        propositionC : "Ich beschleunig schnell.",
        propositionD : "Ich mache Platz.",
        response : "D"
    },
    {   question : "Was heißt Rechts vor Links?",
        propositionA : "Von rechts kommende Fahrzeuge haben vorrang",
        propositionB : "Von links kommende Fahrzeuge haben vorrang",
        propositionC : "Es hat nichts zu bedeuten.",
        propositionD : "Nur wichtig für Fußgänger",
        response : "A"
    },
    {   question : "Was kann Aquaplancing (Wasserglätte) zur Folge haben",
        propositionA : "Eine verringerte Bremsfähigkeit des Fahrzeuges",
        propositionB : "Eine vergrößerte Haftung der Reifen",
        propositionC : "Nichts",
        propositionD : "Ich kann lenken wie ein Profi",
        response : "A"
    },
    {   question : "Vor dir rennt ein Kind auf die Straße. Was machst du?",
        propositionA : "Ich führe eine Gefahrenbremsung durch",
        propositionB : "Ich fahre weiter",
        propositionC : "Ich fahre einen großen Bogen",
        propositionD : "Ich hupe laut und beschimpfe das Kind",
        response : "A"
    },
    {   question : "Welche Beudeutung haben Weisungen von Polizeibeamten?",
        propositionA : "Ihnen ist Folge zu leisten, wenn sie mit den Aufgestellten verkehrszeichen übereinstimmen.",
        propositionB : "Ihnen ist Folge zu leisten!",
        propositionC : "Sie entbinden von der Sorgfaltspflicht",
        propositionD : "Gar nichts",
        response : "B"
    },
    {   question : "Wo führt schnelles fahren häufig zu Unfällen?",
        propositionA : "An Fußgängerüberwegen",
        propositionB : "An Straßenkreuzungen und -einmündungen",
        propositionC : "In Kurven",
        propositionD : "Auf Geraden",
        response : "C"
    },
    {   question : "Was müssen Sie beim ausfahren eines Kreisels beachten?",
        propositionA : "Blinken und Schulterblick",
        propositionB : "Nichts",
        propositionC : "Nur Blinken",
        propositionD : "Blinken und Beschleunigen",
        response : "A"
    },
]

How to remove event listener or emitter listeners in React Native

I am trying to remove an event listener. The old way is deprecated. We are told to use .remove(). I am not sure how to refactor my code to do so. I am using a class component.

Can you provide an example of how to remove event listener. Currently my event listener is inside of another function. I have it that way as I may need to create another event listener every time the button is press and I need to remove the listener after the function runs.

startProcess = (result) => {
  //  stuff for running process
  console.log("your function is running its process");

  //deprecated but easy way to remove the event listener below
  // eventEmitter.removeListener('PreparePaywallFinished', onPreparePaywallFinished);

  //new way to remove event listen use remove() method on the EventSubscription returned by addEventListener()
  this.subscribeStartProcess.remove;
};

handleBtnPress = () => {
  // the listener
  eventEmitter.addListener("onMidiStart", this.startProcess);

  // emitter
  NativeModules.midiBridgeStart(true, 2);
};

render(){
  return <Button title='press' onPress={()=> handleBtnPress() />
}

Embed a website in an iframe that is blocked by CORS policy

Let’s say I would like to embed this website in an iframe. Then my console would show me that this website is blocked by CORS policy.

If I add for example X-Frame-Bypass, the problem is still there as you can see here:

<script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
<script type="module" src="https://unpkg.com/x-frame-bypass"></script>
<iframe is="x-frame-bypass" src="https://www.uni-weimar.de/de/universitaet/aktuell/ukraine-hilfe-der-universitaet/" width="500" height="400"></iframe>

Strangely enough, it works perfectly here.

What do I need to do to embed an iframe of this website on any website? I would be very thankful for help!

Check if two arrays are the same, if not, don’t add data to ChartJS

I’m trying to compare two arrays to see if they are the same. If they are the same, I don’t want it to update the chart.

As I’m getting data from an echo using a XMLHTTPRequest, the data comes in this format: [“9″,”1″,”7″,”5″,”6”].

Javascript:

var Data;
var lastNum;

function loadXMLDOC() {
var request = new XMLHttpRequest(); 
request.onreadystatechange = function () {
    if (request.readyState == 4 && request.status == 200) {
        lastNum = Data
        Data = this.responseText;

        for (var i = 0; i < Data.length; i++) {
            if (Data[i] !== lastNum[i]) {
                
            } else {
                myChart.data.labels = " ";
                myChart.data.datasets[0].data = Data;
            }
        }

        myChart.update('active');
    }
}
request.open('GET', "data.php", true);
request.send(); // send the request
}
setInterval(function () {
loadXMLDOC();
},1000)

window.onload = loadXMLDoc;

I’m extremely new to JavaScript, but I have to do this for a project I’m working on. I don’t think I’m checking the arrays properly to see if they’re the same.

Any help would be appreciated.

Is it possible to get the jQuery object from a $(‘#myElement’)?

I’m working in a mixed environment of prototype/scriptaculous and jQuery. Not my implementation, but now it’s my problem: I’m working to remove prototype/scriptaculous everywhere and replace both with vanillaJS as time permits.

In the meantime, let us say I have a DOM element, jQuery’d like this:

$(“#myElement”)

Is it possible to get the jQuery object from this so I don’t have to pass ‘$’ from function to function as an extra parameter? e.g.:

function foo($) {
    const myElement = $("#myElement");
    ...do some stuff to myElement here...
    bar(myElement);
}

function bar(myElementIn) {
    const $ = {somehow get the jQuery object from myElementIn};
    ...do more stuff with other elements related to myElementIn...
}

Longshot, I’m sure, but figured it was worth asking.

HOC’s handler function bypassed in Jest

Can anyone help me understand why the handler function in the HOC does not get called when the blur event is simulated in this jest test?

//MyInput.js
export const MyInput = (props) => {
  <div>
    ...
    <input onBlur={ props.onBlur } />
    ...
  </div>
}


//HOC.js
export const HOC = (SomeComponent) => {
  return (props) => {
    const handleBlur = () => {
      console.log('this does not get called');
      //do stuff
      props.onBlur();
    }

    return <SomeComponent onBlur={handleBlur} />;
  }
}

// test.js
describe('HOC', () => {
  it('fires a  callback in response to the blur event' () => {
    const ModifiedInput = withHOC(MyInput);
    const onBlurMock = jest.fn(() => {
      console.log('this does get called');
    });
    const wrapper = mount(<ModifiedInput onBlur={onBlurMock} />);
    const input = wrapper.find('input');
    input.simulate('blur);
    expect(onBlurMock).toHaveBeenCalled();
  })
})

Why can we assign console.log to a variable

I am confused how we can assign console.log(`${tempCel} to ${tempFar}. What are we truly displaying?

const tempCel = Number(prompt("Enter a temperature in Celsius degrees:"));
const tempFar = tempCel * 9 / 5 + 32;
console.log(`${tempCel}°C = ${tempFar}°F`);