Copy image URL to clipboard

with the following scripts I was able to perform the task of uploading a file to wordpress through Ajax. I need to implement a button or link in the form that allows copying to clipboard the URL of the uploaded image. Kindly assist.

HTML

<form enctype="multipart/form-data">
<label>Choose File:</label>
<input type="file" id="file" accept="image/*" />
<input type="submit" id="submit" value="Copy URL" />
</form>

JS

jQuery(function($) {
$('body').on('change', '#file', function() {
    $this = $(this);
    file_data = $(this).prop('files')[0];
    form_data = new FormData();
    form_data.append('file', file_data);
    form_data.append('action', 'file_upload');
    form_data.append('security', blog.security);

    $.ajax({
        url: blog.ajaxurl,
        type: 'POST',
        contentType: false,
        processData: false,
        data: form_data,
        success: function (response) {
            $this.val('');
            alert('File uploaded successfully.');
        }
    });
  });
 });

functions.php

function blog_scripts() {
// Register the script
wp_register_script( 'custom-script', get_stylesheet_directory_uri(). '/js/custom.js', array('jquery'), false, true );

// Localize the script with new data
$script_data_array = array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'security' => wp_create_nonce( 'file_upload' ),
);
wp_localize_script( 'custom-script', 'blog', $script_data_array );

// Enqueued script with localized data.
wp_enqueue_script( 'custom-script' );
}
add_action('wp_enqueue_scripts', 'blog_scripts');

 function file_upload_callback() {
check_ajax_referer('file_upload', 'security');
$arr_img_ext = array('image/png', 'image/jpeg', 'image/jpg', 'image/gif');
if (in_array($_FILES['file']['type'], $arr_img_ext)) {
    $upload = wp_upload_bits($_FILES["file"]["name"], null, file_get_contents($_FILES["file"]["tmp_name"]));
    //$upload['url'] will gives you uploaded file path
}
wp_die();
}


add_action('wp_ajax_file_upload', 'file_upload_callback');
add_action('wp_ajax_nopriv_file_upload', 'file_upload_callback');

When adding a condition to call two functions my expected output changes

I have a function called setQualified() This function determines whether users are qualified to participate in tours offered by different companies. Each tour company has an ID, and users must meet certain criteria to qualify for each company’s tour. setQualified() will call two functions company1Qualified() & beaconQualified(). When these functions are called they will determine the values for the variable “qualifiedCompanyValue”.

I have this function working when I call both functions at the beginning of setQualified(). But when I try to call these functions by adding a condition to check if the companies id’s are in the variable “companiesArray” it does not work. When I add the condition it will only set the first company id from “companiesArray” to my variable “qualifiedCompanyValue”. It will not set both companies as expected. Both companies will get set if I call the functions at the start without adding the condition.

I have two of my solutions commented out below. Why are the conditions affecting the value of “qualifiedCompanyValue”? Is my issue coming from the conditions on the “qualifiedCompanyValue” variable?

Any guidance or help would be greatly appreciated. Thanks!

    //-----------------------------------------------------------------
//set Qualified Runs company1Qualified() and beaconQualified();
//Check if user qualified and set Qualified Company
function setQualified(qualificationCode) {
  console.log("Function setQualified");

  const company1Id = "0011U00002LNeJ9QAL";
  const beaconId = "0011U00002BkHdaQAF";
  let iscompany1Q = company1Qualified();
  let isBeaconQ = beaconQualified();

  // Get List of Bookable Companies.
  let bookableCompanies =
    window.formyoula.form_fields["04ed-50d5-70f1"].get("value");
  console.log("Bookable Companies:", bookableCompanies);
  var companiesArray = bookableCompanies.split(",");

  //This is the field where we store the company id of the tour location the user picked.
  //Get [CompanyId] Pg2
  const choosenCompany =
    window.formyoula.form_fields["1a73-1a95-32e3"].get("value");

  // let iscompany1Q = false;
  // let isBeaconQ = false;

  // // Check if company1Id and beaconId are in bookableCompanies
  // Solution 1:
  // if (companiesArray.includes(company1Id)) {
  //   iscompany1Q = company1Qualified();
  // }
  // if (companiesArray.includes(beaconId)) {
  //   isBeaconQ = beaconQualified();
  // }

  // Solution 2:
  // let iscompany1Q = companiesArray.includes(company1Id)
  //   ? company1Qualified()
  //   : false;
  // let isBeaconQ = companiesArray.includes(beaconId) ? beaconQualified() : false;

  const qualifiedCompanyValue =
    isBeaconQ && iscompany1Q
      ? `${company1Id}, ${beaconId}`
      : isBeaconQ
      ? beaconId
      : iscompany1Q
      ? company1Id
      : "";
  const autoTourQualifiedValue = isBeaconQ || iscompany1Q ? "true" : "false";
  //Set [Qualified Company]  Pg 2
  window.formyoula.form_fields["b57d-0a9a-0bf5"].set({
    value: qualifiedCompanyValue,
  });

  console.log("Qualified Companies:", qualifiedCompanyValue);

  //Set [Auto Tour Qaulified] Pg2
  window.formyoula.form_fields["26d6-d9d7-5ccd"].set({
    value: autoTourQualifiedValue,
  });
  // Check if choosenCompany is in the list of qualified companies
  const isChoosenCompanyQualified =
    qualifiedCompanyValue.includes(choosenCompany);
  console.log("Is Choosen Company Qualified:", isChoosenCompanyQualified);

  // If customer is no longer Qualified for the Tour Location they choose
  if (!isChoosenCompanyQualified) {
    // Show a Toastify message if the chosen company is not qualified
    Toastify({
      text: "There no future promotions available for the company you have choosen.",
      duration: 0, // Duration in milliseconds Set duration to 0 to prevent automatic close
      close: true, // show close button
      gravity: "top", // Set the position of the toast top or bottom
      position: "center", // `left`, `center` or `right`
      style: {
        background: "linear-gradient(to right, #EE5A24, #EA2027",
        width: "600px",
        margin: "auto",
        border: "2px solid snow",
        padding: "12px 40px",
      },
      stopOnFocus: true, // Stop the timer when the toast is hovered
    }).showToast();

    // Call the function to reset the tour location fields
    resetTourLocation();

    stopSpinner();
    enableButton("nextBtn");
  } else {
    stopSpinner();
    enableButton("nextBtn");
  }

  // Set hidden field value based on Id - [reScoredCustomer] -Pg1
  window.formyoula.form_fields["f988-036e-4758"].set({
    value: true,
  });
}

Angular Server Side pagination using community edition and caching the data when navigating from other routes

I have implemented server side pagination using community edition based on this, I have a working example of server side pagination.
When I click on any column I navigate to different screen or different route which has the details of the row item. But when I click back from new route to previous route I am trying not to load the new set of data but render the previous data with all the grid settings.
Reference for server side pagination I used
https://medium.com/weekly-webtips/tech-building-reusable-server-side-pagination-for-ag-grid-in-angular-c8127e2da346

I Have created a sample application for performing server side pagination, I am able to render the users data and making API calls based on the change of pagination. I navigate to any page, and click on the row and this navigates to new screen(route) which has user details and button to navigate back to GRID.
When I navigate back to GRID, rather than making API call again, I want to render previous cached data and also in the table if I was in page number 2 before navigating to user details screen, when I click back on user-details screen I should be on the same page 2 and page 1 and page 2 should be cached.

Server side pagination implementation example: https://stackblitz.com/edit/aggrid-server-side-pagination

Steps to Recreate or navigate

  1. Load the AG-GRID angular server side pagination app
  2. Click on ‘Load Ag-Grid Table Data’ button. this navigates and loads the table data
  3. Navigate to page 2 and click on any row
  4. Now the user page is loaded click on ‘Back to Grid Table’ button
  5. On Table screen, currently it is loading the whole data instead we should render the cached data and the page number should be on page 2, and when I click previous page for pagination it should render cached page 1 data.

Django – Need guidance on filtering data by keywords

In my web-app project, I have a page for advanced search. Initially, all the items from db should be displayed on front-end. From admin interface, for each item I have added keywords separated by comma. What I want to do is to filter the items on FE based on those keywords.
Example: the wine has keywords like: red, dry . When I click on one of those options on front-end, the corresponding wines should be shown. I have created the template, added views and some javascript but now I’m stuck and I don’t understand where the logic lacks.

Here is the template piece:

    <div class="dropdown">
        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
            Filter
        </button>
        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="filterOptions">
        <li><a class="dropdown-item" href="#" data-keyword="red">Red</a></li>
        <li><a class="dropdown-item" href="#" data-keyword="sparkling">Sparkling</a></li>
        <li><a class="dropdown-item" href="#" data-keyword="white">White</a></li>
        <li><a class="dropdown-item" href="#" data-keyword="sweet">Sweet</a></li>
        <li><a class="dropdown-item" href="#" data-keyword="dry">Dry</a></li>
        <li><a class="dropdown-item" href="#" data-keyword="citrus">Citrus</a></li>
        </ul>
    </div>
    <section class="products section-padding">
        <div class="container">
            <div class="row">
                {% for wine in page_obj %}
                <div class="col-lg-4 col-12 mb-3">
                    <div class="product-thumb">
                        <a href="product-detail.html">
                            <img src="{{ MEDIA_URL }}{{ wine.image.url }}" class="img-fluid product-image" alt="">
                        </a>

                        <div class="product-info d-flex">
                            <div>
                                <h5 class="product-title mb-0">
                                    <a href="product-detail.html" class="product-title-link">{{ wine.name }}</a>
                                </h5>

                            <p class="product-p">{{ wine.description }}</p>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
</section>

<div class="pagination">
    <span class="step-links">
        {% if page_obj.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
        </span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
            <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>

Here the “draft” views that are yet to be updated:

def wines_all(request):
    sparkling_wines_list = Wine.objects.all()
    paginator = Paginator(sparkling_wines_list, 9)

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, 'test.html', {'page_obj': page_obj})

def filter_wines(request):
    keyword = request.GET.get('keyword')
    if keyword:
        filtered_wines = Wine.objects.filter(keywords__contains=keyword)
    else:
        filtered_wines = Wine.objects.all()
    wines_data = [{'name': wine.name, 'description': wine.description, 'image': wine.image.url} for wine in filtered_wines]
    return JsonResponse(wines_data, safe=False)

And the js code:

 document.addEventListener('DOMContentLoaded', function () {
 const filterOptions = document.querySelectorAll('#filterOptions a');

 const wineList = document.getElementById('wineList');

 filterOptions.forEach(option => {

option.addEventListener('click', function (event) {

  event.preventDefault();

  const keyword = this.dataset.keyword;

  fetch(`/filter-wines/?keyword=${keyword}`)

    .then(response => response.json())

    .then(data => {

      wineList.innerHTML = '';

      data.forEach(wine => {

        wineList.innerHTML += `

          <div class="col-lg-4 col-12 mb-3">

            <div class="product-thumb">

              <a href="product-detail.html">

                <img src="{{ MEDIA_URL }}${wine.image.url}" class="img-fluid product-image" alt="">

              </a>

              <div class="product-info d-flex">

                <div>

                  <h5 class="product-title mb-0">

                    <a href="product-detail.html" class="product-title-link">${wine.name}</a>

                  </h5>

                  <p class="product-p">${wine.description}</p>

                </div>

              </div>

            </div>

          </div>

        `;

      });

    })

    .catch(error => console.error('Error fetching wines:', error));
      });
     });

       });

I am new to web-development, especially with Django, so I look up lots of tutorials and resources, so it can get all over the place, would be thankful of some corrections/guidance.

Note: What I’m trying to achieve is to be able to choose multiple options and filter data based on multiple choices.
Also for the keyword part, I am using CharField, so I guess the best option is to split the string by commas so i can get the keywords are separate strings

React/Tailwind problem with slideshow height

I am new to web development and I’m learning to use React and Tailwind.

I am trying to do the “About us” section that should be made in the following way.
There are two components: a slideshow of images that automatically change every second and a paragraph with some text.

The two should be arranged like this:

  1. for large screens a row with the slideshow on the first column (left) and the paragraph on the second one (right).
  2. For smaller than large screens there should be 1 column and 2 rows with the slideshow on top and the paragraph on the bottom.

This is the code I have at the moment. It works but there is a problem: it seems like for case 2, it is not understanding correctly the height of the slideshow so the paragraph text is going on top of the slideshow images.

Is there any way to solve this? Thanks.

  const [currentSlide, setCurrentSlide] = useState(0);

  useEffect(() => {
    const interval2 = setInterval(() => {
      setCurrentSlide((prevSlide) =>
        prevSlide === images.length - 1 ? 0 : prevSlide + 1
      );
    }, 3000);

    return () => {
      clearInterval(interval2);
    };
  }, []);

<div className="grid grid-cols-1 grid-rows-2 lg:grid-rows-1 lg:grid-cols-2 w-full">
    {/* Images */}
    <div className="images lg:order-1" data-aos="fade-up">
        <div className="relative">
            {images.map((image, index) => (
                <div
                    key={image.id}
                    className={`absolute top-0 left-0 w-full h-full transition-opacity duration-1000 ${
                        index === currentSlide ? "opacity-100" : "opacity-0"
                    }`}
                >
                    <img src={image.img} className="rounded-md" alt="" />
                </div>
            ))}
        </div>
    </div>

    {/* About us */}
    <div className="lg:order-2 lg:mt-0 mx-auto space-y-4 lg:w-3/4 text-black" data-aos="fade-up">
        <h2 className="text-2xl font-semibold"> Title</h2>
        <p className="text-justify lg:text-start">
            About us 1.
        </p>
        <p className="text-justify lg:text-start">
           About us 2.
        </p>
        <p className="text-justify lg:text-start">
           About us 3.
        </p>
    </div>
</div>

Move canvas object towards mouseclick position in the same speed

I wrote a player class which renders a dot on the canvas. On mouse-down event I want to move the dot towards the desired position. My problem is the following:

If the distance is far it moves in a ‘okay’ speed but the closer the distance is the slower the dot moves toward the location.

Example video: Youtube example

Code:

/* Interfaces */
interface Position {
    x: number
    y: number
}

// Player class
class Player {
    // Properties
    private name: string
    private gender: string
    private position: Position
    private canvas: HTMLCanvasElement
    private dx: number = 0
    private dy: number = 0
    private mouseX: number = 0
    private mouseY: number = 0
    private stepWidthFactor: number = 200

    // Constructor
    public constructor(
        name: string,
        gender: string,
        position: Position,
        canvas: HTMLCanvasElement,
    ) {
        this.name = name
        this.gender = gender
        this.position = position
        this.canvas = canvas
    }

    /* Methods */

    draw = () => {
        this.createPlayer()
    }

    createPlayer = () => {
        // Get canvas context
        const context = this.canvas.getContext('2d')

        // Draw a player
        if (context) {
            context.fillStyle = '#F00000'
            context.beginPath()
            context.arc(this.position.x, this.position.y, 10, 0, 2 * Math.PI)
            context.fill()
        }
    }

    movePlayer = (x: number, y: number) => {
        this.mouseX = x
        this.mouseY = y

        this.dx = ((this.position.x - this.mouseX) / this.stepWidthFactor) * -1
        this.dy = ((this.position.y - this.mouseY) / this.stepWidthFactor) * -1
    }

    update = () => {
        const context = this.canvas.getContext('2d')

        if (context) {
            context.clearRect(0, 0, this.canvas.width, this.canvas.height)
            this.draw()

            var shouldMove =
                Math.abs(this.position.x - this.mouseX) > 1 ||
                Math.abs(this.position.y - this.mouseY) > 1

            if (shouldMove) {
                this.position.x += this.dx
                this.position.y += this.dy
            }

            window.requestAnimationFrame(this.update)
        }
    }

    /* Setters */

    /* Getters */

    // Get player name
    public getName(): string {
        return this.name
    }

    // Get player gender
    public getGender(): string {
        return this.gender
    }

    // Get player position
    public getPosition(): Position {
        return this.position
    }
}

// Export Player class
export default Player

Which way could I use to make the dot move in the same speed?

my mathematical functions are returning NaN

so I have been asking to change my code to simplify my functions but now that i have simpliftied them they are now only returning NaN and i dont really understand why that is, when the input is numbers?

// the purpose of this script is to execute different functions on an array of 3 integers// 
const input = [6, 25, 11];
const findSum = input.reduce((acc, num) => acc + num, 0);
console.log(findSum);

// each function has been assigned parameters to execute //
const subsFrom = (num1, num2, num3) => num1 - num2 - num3;
const subNum = subsFrom(input);
console.log(subNum);
// then call the function and display the answer //

const multiBy = (num1, num2, num3) => num1 * num2 * num3;
const multiNum = multiBy(input)
console.log(multiNum);

const divBy = (findSum, num1, num2, num3) => findSum / num1 / num2 / num3;
const divNum = divBy(findSum, input);
console.log(divNum);

Funciones de JavaScript condiciones

dentro de la programacion tengo un controlador y uno que hace las funciones de js.
el primero es donde se encuentra todas las querys de mis consultas a las bd. en una consiste que me muestre toda la informacion de esa seccion y el otro en caso de no estar en esa bd que me muestre un mensaje y un archivo en formato .pdf

el controlador.php

else if($_POST[‘opcion’] == ‘datosSeccion’){
$seccion = $_POST[‘dato’];

        $query="SELECT id, AsText(geom) geom, claveDT, nombreDT, pobDT, media_pob, circuns, num_circun, dttoL, seccion, pob_x_secc, ln FROM secciones_2024_geo WHERE seccion = '".$seccion."' ORDER BY seccion;";

        // $respuesta=mysqli_query($conectado, $query);
        // $cols=mysqli_fetch_array($respuesta);

        // echo $cols['seccion']."|".$cols['geom'];

        
        $response=array();
        $res=mysqli_query($conexion, $query)or die("Error de conexión 0XEE01: " .mysqli_error($conexion));
        $cols=mysqli_fetch_array($res);

        if($cols == ''){
            $error = array('error');
            echo json_encode($error);
        }

        else if($cols == ''){

            $query="SELECT id, claveDT, nombreDT, seccBaja, seccActual, dttoL FROM secciones_bajas WHERE seccBaja = '".$seccBaja."' ORDER BY seccBaja;";
            $baja = array('baja');
            echo json_encode($baja);
        }

        else{
            foreach($res as $key => $value){
                $datos = array();   
                foreach($value as $v => $d){
                    $datos[$v] = $d;
                }
                array_push($response, $datos);
            }

            //var_dump($response);
            echo json_encode($response);

            // echo "Hola";
        }   

    }

mi funtions.js

function mostrarDatosCasilla(seccion){

const icon = {
    url: "imagenes/punto.png",
    scaledSize: new google.maps.Size(40, 40), // scaled size
    origin: new google.maps.Point(0,0), // origin
    anchor: new google.maps.Point(0, 0) // anchor
};
            


var xmlhttp;

if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

     
      document.getElementById("mapsecc").style.display="block";

     
        /*Inicia propiedades del mapa*/
        bounds = new google.maps.LatLngBounds();
        const mapOptions = {
          center: { lat: 19.432777, lng: -99.133217 },
          // Rotaciín inicial
          heading: 180,
          tilt: 60,
          // Ésto permite la inclinación y la vista 3D
          mapId: "90f87356969d889c",
          zoom: 18,
          //mapTypeId: "terrain"
        };

        map = new google.maps.Map(document.getElementById('mapsecc'), mapOptions);


        const buttons = [
        ["Rotar a la izquierda", "rotate", 20, google.maps.ControlPosition.LEFT_CENTER],
        ["Rotar a la derecha", "rotate", -20, google.maps.ControlPosition.RIGHT_CENTER],
        ["Inclinar hacia abajo", "tilt", 20, google.maps.ControlPosition.TOP_CENTER],
        ["Inclinar hacia arriba", "tilt", -20, google.maps.ControlPosition.BOTTOM_CENTER],
        ];

        buttons.forEach(([text, mode, amount, position]) => {
        const controlDiv = document.createElement("div");
        const controlUI = document.createElement("button");

        controlUI.classList.add("ui-button");
        controlUI.innerText = `${text}`;
        controlUI.addEventListener("click", () => {
          adjustMap(mode, amount);
        });
        controlDiv.appendChild(controlUI);
        map.controls[position].push(controlDiv);
        });

        const adjustMap = function (mode, amount) {
          switch (mode) {
            case "tilt":
              map.setTilt(map.getTilt() + amount);
              break;
            case "rotate":
              map.setHeading(map.getHeading() + amount);
              break;
            default:
              break;
          }
        };
        /*Terminan propiedades del mapa*/

        /*Pintamos poligonos y marcadores*/
        //map.fitBounds(bounds);
        /*Termina la configuración de los poligonos y marcadores*/

    
      //console.log("markers", markers);
      var claveDT, dttoL, dttoF, nombreDT, total_casillas, seccion, casillas_instalar, ubicacion, domicilio, referencia, latitud, longitud, seccCas;
      let contentString = ""; 

      let datos = JSON.parse(xmlhttp.responseText);

      if(datos[0] == 'error' ){
        
        document.getElementById('mapsecc').innerHTML="NO EXISTE LA SECCIÓN ELECTORAL";
        
      }

      else if(datos[0] == 'baja' ){
        
        document.getElementById('mapsecc').innerHTML="EN CASO DE VIVIR EN ESTA SECCIÓN ELECTORAL, CONSULTA LA INFORMACIÓN ANEXO";
        
      }


      else{

      /*Datos del Poligono de la seccion*/
      claveDT=datos[0].claveDT;
      dttoL = datos[0].dttoL;
      nombreDT = datos[0].nombreDT;
      seccion = datos[0].seccion;
      poligonoSecc = datos[0].geom.substring(15, datos[0].geom.length-3);

      /*Declaramos distrito y sus propiedades*/
      const polygonoseccion = new google.maps.Polygon({ 
        map: map,
        //paths: parsearSecc(datos.poligono.split("n")),
        paths: parsearSecc(datos[0].geom.substring(15, datos[0].geom.length-3).split(",")),
        strokeColor: '#6610f2',// Color de linea
        strokeOpacity: 0.8, // Opacidad de la linea
        strokeWeight: 3, // Grosor de la linea
        //fillColor: '#FFFFFF', // Color de relleno
        fillOpacity: 0.0, //Opacidad del relleno
        //zindex: 1,
        //id: seccion,
        //editable: true, //Permite que el poligono sea editable, deve ir despues de paths
      })

      /*Pintamos poligonos y marcadores*/
      map.fitBounds(bounds2);

      dibujarcasillas(seccion);
      }
    
  } 

};
xmlhttp.open("POST", "paginas/controlador.php");
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('opcion=datosSeccion&dato='+seccion);

}

a parte quiero agregar un archivo PDF cuando salga la condicion al momento de ingresa una seccion que no este en la bd

Hola! dentro de la programacion tengo un controlador y uno que hace las funciones de js.
el primero es donde se encuentra todas las querys de mis consultas a las bd. en una consiste que me muestre toda la informacion de esa seccion y el otro en caso de no estar en esa bd que me muestre un mensaje y un archivo en formato .pdf

a parte quiero agregar un archivo PDF cuando salga la condicion al momento de ingresa una seccion que no este en la bd.

Tenia pensado agrega un if anidado

Placing the correct variable in a div

I am building a BMI-calculator, (you put your height and weight and it calculates it) but I am having an issue where an if statement only outputs an error message variable to the div, but won’t output the correct one, even when there are the correct inputs.

I have attempted checking if the variables in the if statement are empty instead of checking for valid input.
Outputting the correct variable itself outside of the if statement works fine, only the if statement has an issue.
The console shows no problems.

let output = 'Your BMI is ' + shortened + '.';
let corrNum = 'Put correct numbers.';

if( weight !== '' && height !== '') {
    document.getElementById("outputField").innerHTML = output;
} else {
    document.getElementById("outputField").innerHTML = corrNum;
}

If there is inputs in both inputboxes, it should output ‘output’.
If one or both inputs are missing, it should output ‘corrNum’.

I would really appreciate any help.

Download file through OneDriver Picker JavaScript

I cloned the MS OneDriver FilePicker Repo (https://github.com/OneDrive/samples/tree/master/samples/file-picking).
I’m currently trying around in the “javascript-basic-consumer” sample. I modified some of the code by hand and some through AI. Azure is configured according to the readme and according to the MS learning article (https://learn.microsoft.com/en-us/onedrive/developer/controls/file-pickers/?view=odsp-graph-online).
Upload is working, but I can’t get the download to work. Neither with documention nor with the help of the other samples or AI.

Could somebody help me out so I get a download after I selected the file and pressed on the “select”-button?

<html>

<head>
    <script type="text/javascript" src="https://alcdn.msauth.net/browser/2.19.0/js/msal-browser.min.js"></script>
    <script type="text/javascript" src="scripts/auth.js"></script>
    <script>
        const baseUrl = "https://onedrive.live.com/picker";
        const params = {
            sdk: "8.0",
            entry: {
                oneDrive: {
                    files: {},   
                }
            },
            authentication: {},
            messaging: {
                origin: "http://localhost:3000",
                channelId: "27"
            },
            typesAndSources: {
                mode: "files",
                pivots: {
                    oneDrive: true,
                    recent: true,
                },
            },
            selection:{
                mode: "multiple",
            },
        };

        
        let port = null;

        async function launchPicker() {
            const frame = document.getElementById("iframe-id");
            const doc = frame.contentDocument || frame.contentWindow.document;

            const authToken = await getToken();

            const queryString = new URLSearchParams({
                filePicker: JSON.stringify(params),
            });

            const url = `${baseUrl}?${queryString}`;

            const form = doc.createElement("form");
            form.setAttribute("action", url);
            form.setAttribute("method", "POST");
            doc.body.append(form);

            const input = doc.createElement("input");
            input.setAttribute("type", "hidden");
            input.setAttribute("name", "access_token");
            input.setAttribute("value", authToken);
            form.appendChild(input);

            form.submit();

            window.addEventListener("message", (event) => {
                if (event.origin !== "https://onedrive.live.com") {
                    return;
                }

                const message = event.data;

                if (message.type === "initialize" && message.channelId === params.messaging.channelId) {
                    port = event.ports[0];
                    port.addEventListener("message", messageListener);
                    port.start();
                    port.postMessage({ type: "activate", });
                }
            });
        }

        async function messageListener(message) {
            
            switch (message.data.type) {
                case "notification":
                    console.log(`notification: ${message.data}`);
                    break;
                case "command":
                    port.postMessage({
                        type: "acknowledge",
                        id: message.data.id,
                    });

                    const command = message.data.data;

                    switch (command.command) {
                        case "authenticate":
                            const token = await getToken();
                            if (typeof token !== "undefined" && token !== null) {
                                port.postMessage({
                                    type: "result",
                                    id: message.data.id,
                                    data: {
                                        result: "token",
                                        token,
                                    }
                                });
                            } else {
                                console.error(`Could not get auth token for command: ${JSON.stringify(command)}`);
                            }
                            break;
                        case "close":
                            win.close();
                            break;
                        case "pick":
                            console.log(`Picked: ${JSON.stringify(command)}`);
                            document.getElementById("pickedFiles").innerHTML = `<pre>${JSON.stringify(command, null, 2)}</pre>`;
                            port.postMessage({
                                type: "result",
                                id: message.data.id,
                                data: {
                                    result: "success",
                                },
                            });
                            win.close();
                            break;
                        default:
                            console.warn(`Unsupported command: ${JSON.stringify(command)}`, 2);
                            port.postMessage({
                                result: "error",
                                error: {
                                    code: "unsupportedCommand",
                                    message: command.command
                                },
                                isExpected: true,
                            });
                            break;
                    }
                    break;
            }
        }
    </script>
</head>

<body style="display: flex; justify-content: center; align-items: center; height: 100vh; flex-direction: column;">
    <iframe id="iframe-id" width="1080" height="680" style="border: none;"></iframe>
    <br />
    <div id="pickedFiles"></div>
</body>

<script type="text/javascript">
    window.onload = function() {
        launchPicker(); // This will automatically launch the picker when the page is fully loaded
    };
</script>

</html>

That’s my code so far. I read in order to download you need to import the Graph API but I didn’t get that to work.
Most likely there’s some code needed in the case “pick”. Additionally probably in “params” as well as far as I understood in the documentation.

After I put some download code in “params” acoording to the documentation I either get a blank site oder it loads after picking a file and then nothing happens again. That’s one edit I made in “params”:

 commands?: {
    /**
     * Specifies the behavior for file-picking.
     */
    pick?: {
      /**
       * A special action to perform when picking the file, before handing the result
       * back to the host app.
       */
      action?: "select" | "share" | "download" | "move";
      /**
       * A custom label to apply to the button which picks files.
       * This must be localized by the host app if supplied.
       */
}
}

Copied from https://learn.microsoft.com/en-us/onedrive/developer/controls/file-pickers/v8-schema?view=odsp-graph-online&source=recommendations

THANK YOU SO MUCH FOR ANY HELP!

My custom useFetch hook does not retrieve 2 types of differents bodies

First of all I will say with React Im a begginer and what I really dont understand is why I cannot fetch 2 endpoints, so they retrieve me data and then I can use it in my differents components

This is my App.jsx

import { Route, Routes } from 'react-router-dom';
import useFetch from './hooks/useFetch';
import { BlogContentPage, Homepage } from './pages';
import AboutPage from './pages/AboutPage';

export default function App() {
  let { loading, data, error } = useFetch('http://localhost:1337/api/blogs?populate=*'); // this one is ok, is recieving data.
  let { data: authors } = useFetch('http://localhost:1337/api/authors?populate=*'); // this one is not, and if I remove the one above this one works (!?!?!)
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error!</p>;
  console.log(authors); // this is null..
  return (
    <div>
      <Routes>
        <Route path='/' element={<Homepage blogs={data ? data : ''} />}></Route>
        <Route path='/blog/:id' element={<BlogContentPage blogs={data ? data : ''} />}></Route>
        <Route path='/about' element={<AboutPage authors={authors ? authors : ''} />}></Route>
      </Routes>
    </div>
  );
}

This is my useFetch custom Hook (and probably I’m doing something wrong here)..

import { useEffect, useState } from 'react';

const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const res = await fetch(url);
        const json = await res.json();
        setData(json);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };
    fetchData();
  }, [url]);

  return { loading, error, data };
};

export default useFetch;

My expectation was that the useFetch hook that I wrote work everytime it gets call.

Rollup config with rollup-plugin-less

I’m having trouble with the rollup-config

rollup: 3.29.4
rollup-plugin-less: 1.1.3

rollup.config.js:

export default [
  {
    input: 'index.js',
    plugins: [
      css(),
      **less(),**
      // Entry point for application build; can specify a glob to build multiple
      // HTML files for non-SPA app
      html({
        input: 'ml-src/index.html',
        output: 'build/index.html'
      }),
...

when I try and use it I continue to get the following error:
[!] RollupError: Unexpected character ‘@’ (Note that you need plugins to import files that are not JavaScript)

I tried updating rollup or trying other plugins but had trouble since I think the requirements were different rollup-styling

Any way to make a goalkeeper in a mini game, by using basic CSS animations and JavaScript, able to save the shot when the ball meets the goalie? [closed]

Need to add animation a mini game that is about a penalty shoot-out. More specifically I need the goalkeeper (who is diving randomly) to knock the ball away when the two divs (goalkeeper and ball) meet.

I have tried the animations both for the ball and the goalie, however when the two ends meet of course there is now difference, the ball ends up inside the goal at all times.

Filter array of objects and get only those whose property matches with the object in the array

I have a array of objects like this

let input = [
    {
        "metadata": { "id": 1071, "name": "USA" },
        "accesories": [ { "name": "steel" } ]
    },
    {
        "metadata": { "id": 1068, "name": "China" },
        "accesories": [ { "name": "electronics" } ]
    },
]

Desired output:

["USA", "China"]

In order to get above result, I use the following

input.map((el) => el?.metadata?.name);

But if I want to filter first by electronics and based on which object has accessories with name as electronics in it, how do I achieve that result?

for e.g.

output: ["USA"] //if I want to filter by object which has name steel
output: ["China"] //if I want to filter by object which has name electronics

Can someone let me know how can I use filter with above map method?

How do I expand a lightbox gallery on click so it overlays the entire screen?

I’ve got several galleries in my html, each identified by an individual div, in a larger wrapping div. I’ve managed to open them individually using this code but am wondering how to open these galleries so that they expand to the entire screen. Does anyone have any ideas?

function LaunchLightbox(num){
  lightboxcontainer=document.getElementsByClassName("slide-show_containers");
  lightboxcontainer[0].style.display="block";
    counter=0;
    slides=document.getElementsByClassName("image_slide" + num.toString());
    lightbox= document.getElementsByClassName("slide-show_" + num.toString() + "container");
    lightbox[0].style.display="block";
    slides[counter].style.display="block";
    totalimages=slides.length;
    console.log(slides);
    console.log(totalimages);
}

function CloseLightbox(num){
  HideImages()
  lightbox = document.getElementsByClassName("slide-show_" + num.toString() + "container");
  lightbox[0].style.display="none";
  lightboxcontainer=document.getElementsByClassName("slide-show_containers");
  lightboxcontainer[0].style.display="none";

I have tried to ascertain how to do this but have so far hit a brick wall