CSS sliding strip animation

I tried a lot of stuff but I cannot figure this one out. I want to make a small red line that goes around a box of content infinetely and it stays basically inside the border. However as the animation progresses the line starts to change on it’s way towards the corner and not after. Here is the code:

#main {
  min-height: 300px;
  position: relative;
  padding: 20px;
  border: 2px solid transparent;
}

#main::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 10%;
  height: 2px;
  background-color: red;
  animation: border-slide 4s linear infinite;
}

@keyframes border-slide {
  0% {
    top: 0;
    left: 0;
    width: 10%;
    height: 2px;
  }
  25% {
    top: 0;
    left: 90%;
    width: 2px;
    height: 10%;
  }
  50% {
    top: 90%;
    left: 90%;
    width: 10%;
    height: 2px;
  }
  75% {
    top: 0;
    left: 0;
    width: 2px;
    height: 10%;
  }
  100% {
    top: 0;
    left: 0;
    width: 10%;
    height: 2px;
  }
}

I tried different methods but basically nothing helped. I just want that red line to go around the main content’s box but I just cannot figure it out how.

How do I count html class elements on other page using js

I have a static portfolio website without database, I want to count no. of products on one page and display it on another one .

Right now I have come up with this

<script>
    const elements = document.querySelectorAll('.product');
    const count = elements.length;
    document.getElementById("Count_exec_chair").innerHTML = count;
</script>

But This only works within same page . I want to count products on 3 different pages and display them on 4th one.

React useParams Returns Boolean Value

App.jsx
<Route path="/shop/:gender/:category?/:categoryId?"> <ProductListPage /> </Route> <Route path="/shop/:filter"> <ProductListPage /> </Route> <Route path="/shop/:page"> <ProductListPage /> </Route> <Route path="/shop"> <ProductListPage /> </Route>

I set up my routes like App.jsx. I need to get categoryId as Integer so I can fetch right products.

`export default function ProductListPage() {
 let { gender, category, categoryId } = useParams();

  const dispatch = useDispatch();

  if ((categoryId = !null)) {
  console.log(categoryId);
  dispatch(setCategoryId(categoryId));
  }

  .
  .
  .
  }`

When ı use useParams as this it works on another page but couldn’t work in this page and I couldn’t figure it out. It keeps returning true.

I try to code myselfy accotding to documentation or looking it up on another stackoverflow questions but couldn’t do it.

tcpdf and tag HTML in a PHP page

I have a problem with a PHP page that uses TCPDF.
Everything works fine, but after the Output command I need to ask the user if he wants to repeat the calculation or change the data to be processed.
To do this I add some HTML tags

echo "<p>Click to confirm or choose other data to repeat the calculation.</p>";
echo "<button onclick='myFunction()'>Confirm</button>";
echo "<p id='response'></p>";

myFunction is a javascript function:

function myFunction() {
let text = "Press the button!nYes to confirm or nCancel to perform another calculation.";
if (confirm(text) == true) {
text = "The calculation is no longer available!";
setTimeout(window.history.go(-2),30000);
} else {
text = "You Canceled! You will be redirected to the page for another calculation!";
setTimeout(window.history.go(-1),30000);
}
document.getElementById("response").innerHTML = text;

}

The HTML code and no message are displayed.
I wrote a test page without TCPDF and everything works fine.
Where am I going wrong? o What doesn’t TCPDF like?

Thanks for the help
Andrea

I hope to find out where I’m going wrong.

This is the test page.


<!DOCTYPE html>
<html>
<head>

<script>
function myFunction() {
  let text = "Premi il bottone!n Sì per confermare o nAnnulla per eseguire un altro calcolo.";
  if (confirm(text) == true) {
    text = "La ricevuta non è più modificabile!";
        setTimeout(window.history.go(-2),30000);
  } else {
    text = "Hai Anullato!  Verrai indirizzato alla pagina per un altro calcolo!";
    setTimeout(window.history.go(-1),30000);
  }
  document.getElementById("risposta").innerHTML = text;
  
}
</script>
</head>

<body>

<?php



    $utf8text.= "Riga di testn";
    $utf8text.="===================================n";
    $utf8text.="PAGAMENTO EFFETTUATO IN CONTANTIn";
    $utf8text.="****************************************n";
 // echo '</ul>';
 //echo $utf8text;
//  include_once ("init_pagina_tcpdf.php");

//=====================================
// get external file content

$uid_time= 'Data pagamento: '.date('d/m/Y H:i:s');
$uid_time_file= '_'.date('dmY_Hi');

//echo $uid.$uid_time;
$utf8text.=$uid_time."n";
//++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', true);

// set document information
/*
$pdf->setCreator(PDF_CREATOR);
$pdf->setAuthor('');
$pdf->setTitle('');
$pdf->setSubject('');
*/
//$pdf->setKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->setHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.'', PDF_HEADER_STRING.'');

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->setDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->setHeaderMargin(PDF_MARGIN_HEADER);
//$pdf->setFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->setAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
/*
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
    require_once(dirname(__FILE__).'/lang/eng.php');
    $pdf->setLanguageArray($l);
}
*/
// ---------------------------------------------------------

// set default font subsetting mode
$pdf->setFontSubsetting(true);

// set font
$pdf->setFont('freeserif', '', 12);
// Call before the addPage() method
//$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
// add a page
$pdf->AddPage();



// set color for text Nero
//$pdf->setTextColor(0, 63, 127);
$pdf->setTextColor(0, 0, 0); 

// write the text
$pdf->Write(5, $utf8text, '', 0, '', false, 0, false, false, 0);
$pdf->setFont('freeserif', 'I', 12);
        $utf8text="Nota: Questa è una nota in corsivo!n";
$pdf->Write(5, $utf8text, '', 0, '', false, 0, false, false, 0);
$pdf->setFont('freeserif', 'B', 12);
        $utf8text="Testo Grassetto!!n";
$pdf->Write(5, $utf8text, '', 0, '', false, 0, false, false, 0);
ob_end_clean();


//Close and output PDF document
$pdf->Output("TestCorsivo", 'D');
//============================================================+
// END OF FILE
//============================================================+

echo "<p>Premi il pulsante per confermare la stampa della ricevuta.</p>";
echo "<button onclick='myFunction()'>Conferma Stampa</button>";
echo "<p id='risposta'></p>";

?>

</body>
</html>

This is the include file tcpdf_include.php

<?php
//============================================================+
// File name   : tcpdf_include.php
// Begin       : 2008-05-14
// Last Update : 2014-12-10
//
// Description : Search and include the TCPDF library.
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com LTD
//               www.tecnick.com
//               [email protected]
//============================================================+

/**
 * Search and include the TCPDF library.
 * @package com.tecnick.tcpdf
 * @abstract TCPDF - Include the main class.
 * @author Nicola Asuni
 * @since 2013-05-14
 */

// always load alternative config file for examples
require_once('config/tcpdf_config_alt.php');

// Include the main TCPDF library (search the library on the following directories).
$tcpdf_include_dirs = array(
    realpath(dirname(__FILE__) . 'tcpdf/tcpdf.php'),// True source file
    realpath('tcpdf/tcpdf.php'),// Relative from $PWD
    '/usr/share/php/tcpdf/tcpdf.php',
    '/usr/share/tcpdf/tcpdf.php',
    '/usr/share/php-tcpdf/tcpdf.php',
    '/var/www/tcpdf/tcpdf.php',
    '/var/www/html/tcpdf/tcpdf.php',
    '/usr/local/apache2/htdocs/tcpdf/tcpdf.php'
);
foreach ($tcpdf_include_dirs as $tcpdf_include_path) {
    if (@file_exists($tcpdf_include_path)) {
        require_once($tcpdf_include_path);
        break;
    }
}

//============================================================+
// END OF FILE
//============================================================+

This is the alternate config config/tcpdf_config_alt.php

<?php
//============================================================+
// File name   : tcpdf_config.php
// Begin       : 2004-06-11
// Last Update : 2013-05-16
//
// Description : Example of alternative configuration file for TCPDF.
// Author      : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - [email protected]
// License     : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2004-2013  Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF.  If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
//============================================================+

/**
 * Example of alternative configuration file for TCPDF.
 * @author Nicola Asuni
 * @package com.tecnick.tcpdf
 * @version 4.9.005
 * @since 2004-10-27
 */

/**
 * Define the following constant to ignore the default configuration file.
 */
define ('K_TCPDF_EXTERNAL_CONFIG', true);

/**
 * Installation path (/var/www/tcpdf/).
 * By default it is automatically calculated but you can also set it as a fixed string to improve performances.
 */
//define ('K_PATH_MAIN', '');

/**
 * URL path to tcpdf installation folder (http://localhost/tcpdf/).
 * By default it is automatically set but you can also set it as a fixed string to improve performances.
 */
//define ('K_PATH_URL', '');

/**
 * Path for PDF fonts.
 * By default it is automatically set but you can also set it as a fixed string to improve performances.
 */
//define ('K_PATH_FONTS', K_PATH_MAIN.'fonts/');

/**
 * Default images directory.
 * By default it is automatically set but you can also set it as a fixed string to improve performances.
 */
define ('K_PATH_IMAGES', dirname(__FILE__).'/../images/');

/**
 * Deafult image logo used be the default Header() method.
 * Please set here your own logo or an empty string to disable it.
 */
define ('PDF_HEADER_LOGO', 'logo-cs.jpg');

/**
 * Header logo image width in user units.
 */
define ('PDF_HEADER_LOGO_WIDTH', 50);

/**
 * Cache directory for temporary files (full path).
 */
define ('K_PATH_CACHE', sys_get_temp_dir().'/');

/**
 * Generic name for a blank image.
 */
define ('K_BLANK_IMAGE', '_blank.png');

/**
 * Page format.
 */
define ('PDF_PAGE_FORMAT', 'A4');

/**
 * Page orientation (P=portrait, L=landscape).
 */
define ('PDF_PAGE_ORIENTATION', 'P');

/**
 * Document creator.
 */
define ('PDF_CREATOR', 'TCPDF');

/**
 * Document author.
 */
define ('PDF_AUTHOR', 'TCPDF');

/**
 * Header title.
 */
//define ('PDF_HEADER_TITLE', 'TCPDF Example');
define ('PDF_HEADER_TITLE', '');

/**
 * Header description string.
 */
//define ('PDF_HEADER_STRING', "by Nicola Asuni - Tecnick.comnwww.tcpdf.org");
define ('PDF_HEADER_STRING', "");

/**
 * Document unit of measure [pt=point, mm=millimeter, cm=centimeter, in=inch].
 */
define ('PDF_UNIT', 'mm');

/**
 * Header margin.
 */
define ('PDF_MARGIN_HEADER', 5);

/**
 * Footer margin.
 */
//define ('PDF_MARGIN_FOOTER', 10);
define ('PDF_MARGIN_FOOTER', 0);

/**
 * Top margin.
 */
//define ('PDF_MARGIN_TOP', 27);
define ('PDF_MARGIN_TOP', 30);

/**
 * Bottom margin.
 */
//define ('PDF_MARGIN_BOTTOM', 25);
define ('PDF_MARGIN_BOTTOM', 0);

/**
 * Left margin.
 */
define ('PDF_MARGIN_LEFT', 15);

/**
 * Right margin.
 */
define ('PDF_MARGIN_RIGHT', 15);

/**
 * Default main font name.
 */
define ('PDF_FONT_NAME_MAIN', 'helvetica');

/**
 * Default main font size.
 */
//define ('PDF_FONT_SIZE_MAIN', 10);
define ('PDF_FONT_SIZE_MAIN', 8);

/**
 * Default data font name.
 */
define ('PDF_FONT_NAME_DATA', 'helvetica');

/**
 * Default data font size.
 */
//define ('PDF_FONT_SIZE_DATA', 8);
define ('PDF_FONT_SIZE_DATA', 6);

/**
 * Default monospaced font name.
 */
define ('PDF_FONT_MONOSPACED', 'courier');

/**
 * Ratio used to adjust the conversion of pixels to user units.
 */
define ('PDF_IMAGE_SCALE_RATIO', 1.25);

/**
 * Magnification factor for titles.
 */
define('HEAD_MAGNIFICATION', 1.1);

/**
 * Height of cell respect font height.
 */
define('K_CELL_HEIGHT_RATIO', 1.25);

/**
 * Title magnification respect main font size.
 */
define('K_TITLE_MAGNIFICATION', 1.3);

/**
 * Reduction factor for small font.
 */
define('K_SMALL_RATIO', 2/3);

/**
 * Set to true to enable the special procedure used to avoid the overlappind of symbols on Thai language.
 */
define('K_THAI_TOPCHARS', true);

/**
 * If true allows to call TCPDF methods using HTML syntax
 * IMPORTANT: For security reason, disable this feature if you are printing user HTML content.
 */
define('K_TCPDF_CALLS_IN_HTML', true);

/**
 * List of TCPDF methods that are allowed to be called using HTML syntax.
 * Note: each method name must end with surrounded with | (pipe) character.
 * The constant K_TCPDF_CALLS_IN_HTML must be set to true.
 * IMPORTANT: For security reason, disable this feature if you are allowing user HTML content.
 */
define('K_ALLOWED_TCPDF_TAGS', '|AddPage|Rect|SetDrawColor|write1DBarcode|');

/**
 * If true and PHP version is greater than 5, then the Error() method throw new exception instead of terminating the execution.
 */
define('K_TCPDF_THROW_EXCEPTION_ERROR', false);

//============================================================+
// END OF FILE
//============================================================+

SEO and NextJS APP wrapped into `use client` provider

I have the following provider that wraps my entire NextJS APP:

'use client';

import { useScrollToHash } from '@/hooks/use-scroll-to-hash';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

interface Props {
  children: React.ReactNode;
}

export default function ClientProviders({ children }: Props) {
  const router = useRouter();
  const [isReady, setIsReady] = useState(false);

  useEffect(() => {
    setIsReady(true);
  }, [router]);

  if (isReady) {
    return children;
  }
}

So it returns null until isReady is set to true. Will it have any negative impact on my SEO and I should remove it or it’s fine?

When I remove it, I have a plenty of error during my build like useMediaQuery is a client-only hook. I did what was mentioned here https://stackoverflow.com/a/78209620/24587344 and then I’ve got another error: document is not defined. I found that I have a component form-select that uses:

menuPortalTarget={document.body}

so I did

menuPortalTarget={typeof window !== 'undefined' ? document.body : undefined}

and now application is succesfully built but when I navigate to server side page, I’ve got an error:

Hydration failed because the initial UI does not match what was rendered on the server.

and Fallback component from Suspense is not more rendered and instead the page is instantly loaded but with layout different that normally probably because of this useMediaQuery hoook because I see that initially some mobile only components are rendered and they disappear instantly once full page is client side rendered.

I would appreciate help!

Error: P1013 | MongoDB database, The provided database string is invalid

While executing below query under vs code terminal:
PS C:desktopserver> npx prisma db push
Environment variables loaded from .env
Prisma schema loaded from prismaschema.prisma
Datasource “db”: MongoDB database “RealPropDB” at “cluster0.kmq4a.mongodb.net”
Applying the following changes:

Error: P1013

The provided database string is invalid. An invalid argument was provided: password must be URL encoded in database URL. Please
refer to the documentation in https://www.prisma.io/docs/reference/database-reference/connection-urls for constructing a correct connection string. In some cases, certain characters must be escaped. Please check the string for any illegal characters.

Console message not showing in js brave browser

not display any massage in console.log

display error massage and normal massage in brave browser but not showing console.log massage showing in google browser but not showing in brave browser alert is working properly prompt is working properly but console massage is not showing properly how i fix it ?

Problem in calling JavaScript functions in dataTable

I wrote a project with asp.net core 8 and jQuery and I want the edit and delete functions to be called in JavaScript by clicking on the buttons with the id value of editBtn and deleteBtn And userId and Area should also be sent to the functions. But in the code I wrote, the functions are not executed and nothing happens, and the execution of ajax functions is important to me. In addition, there is no error in the browser console.please help me

View codes in dataTable:

<script type="text/javascript">

 var _registerUrl = '@Url.Action("Register", "Management")';
 var _gridUrl = '@Url.Action("FillUsersGrid", "Management")';
 var _GetUsersUrl = '@Html.Raw(@Url.Action("GetUsers", "Management", new { Province = 1, County = 0, District = 0 }))';

var area = {
                province: 1,
                county: 0,
                district: 0
            };
        </script>


 <script type="text/javascript">

 //List
 $(document).ready(function (e) {
                $.get(_gridUrl).done(function (result) {
                    $("#users-box").html(result);
                });
});

function GridLoad() {
                table = $("#tableList").DataTable({
                    initComplete: function () {
                        $('div.dt-search').addClass("d-flex");
                        $('div.dt-search input').addClass('form-control');
},

"paging": true,
"pagingType": 'full_numbers',
"pageLength": 10,
"processing": false,
"serverSide": true,
"info": false,
"lengthChange": false,
"ordering": true,
"language": {
              "emptyTable": "داده ای ثبت نشده است.",
              "loadingRecords": '<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>',
 "search": `<span class="ms-2">
                        <i class="fa fa-search text-primary"></i>
                                     جست‌و‌جو بر اساس کد ملی:
                         </span>`,
                        "searchPlaceholder": 'مقدار مناسبی برای کد ملی وارد کنید ...',
},
"ajax": {
            "url": _GetUsersUrl,
            "type": "POST",
            "datatype": "json"
},
"columns": [
                  { "data": "userName", "title": "نام کاربری" },
                  { "data": "area", "title": "ناحیه" },
                  { "data": "county", "title": "شهرستان" },
                  { "data": "district", "title": "بخش" },
                  { "data": "firstName", "title": "نام" },
                  { "data": "lastName", "title": "نام خانوادگی" },
                  { "data": "gender", "title": "جنسیت" },
                  { "data": "education", "title": "تحصیلات" },
                  { "data": "employment", "title": "وضعیت استخدامی" },
                  { "data": "maritalStatus", "title": "وضعیت تاهل" },
                  { "data": "insurance", "title": "بیمه" },
                  { "data": "phoneNumber", "title": "شماره همراه" },
                  { "data": "email", "title": "پست الکترونیک" },
                  { "data": "dateOfBirth", "title": "تاریخ تولد" },
                  { "data": "city", "title": "شهر سکونت" },
                  { "data": "address", "title": "نشانی سکونت" },
                  { "data": "isActived", "title": "وضعیت" },
                  { "data": "lastActived", "title": "آخرین فعالیت" },
                  { "data": "registerDate", "title": "تاریخ ثبت" },
                  { "data": "userId", "title": "عملیات", render: function (data, type, row) {

              return `<div class="d-flex py-2">
                       <a class="btn btn-outline-primary btn-sm rounded-circle py-1 ms-1"
                          id="editBtn"
                       >
                              <i class="fa fa-edit" > </i>
                       </a>
                       <a class="btn btn-outline-danger btn-sm rounded-circle py-1"
                           id="deleteBtn"
                        >
                              <i class="fa fa-times" > </i>
                                          </a>
                                       <div>`
                            }
                        }
                    ]
                })
            };

codes in Edit and Delete functions:

$("#tableList").on("click", "a[id='editBtn']", function (e) {
                e.preventDefault();
                var userId = $(this).closest("tr").find("td:eq(19)").text(); 
                var _editUrl = `/Province/Management/Edit?userId=${userId}&province=${area.province}&county=${area.county}&district=${area.district}`;
                $.get(_editUrl).done(function (result) {
                    $("#operation-box").html(result);
                    $("#operation-box").modal("show");
                });
            });

            //Delete
            $("#tableList").on("click", "a[id='deleteBtn']", function (e) {
                e.preventDefault();
                var userId = $(this).closest("tr").find("td:eq(19)").text();
                var _deleteUrl = `/Province/Management/Delete?userId=${userId}&province=${area.province}&county=${area.county}&district=${area.district}`;
                $.get(_deleteUrl).done(function (result) {
                    $("#operation-box").html(result);
                    $("#operation-box").modal("show");
                });
            });
    ```

Calling the Delete and Edit functions by clicking the buttons with the ID editBtn and deleteBtn

HTML onclick dropdown won’t work in mobile but works on desktop

I am working on a responsive multilingual website using purely HTML/CSS and JS. And how it switches language is using a dropdown which works really well on desktop, but when I load it on my mobile phone or just minimizing the size of my desktop browser to resemble a mobile resolution or even using the developer tools to load it like the mobile, the dropdown won’t work for some reason.

I made it console log when the JS is working to change the language, which it seems to work, but the CSS won’t change. Does anybody have any idea why?

I’ve tried changing JS function to something else that is not onclick and I’ve tried isolating the dropdown to a separate webpage and it still won’t work.

Here’s my code below.
Thanks in advance!

// same code for mobile and desktop view

function toggleDropdown() {
  const dropdownMenu = document.getElementById('dropdownMenu');
  if (dropdownMenu) {
    console.log("button clicked");
    console.log("class changed to", dropdownMenu.className);
    if (dropdownMenu.classList.contains('visible1')) {
      dropdownMenu.classList.remove('visible1');
      dropdownMenu.classList.add('hidden1');
    } else {
      dropdownMenu.classList.remove('hidden1');
      dropdownMenu.classList.add('visible1');
    }
    console.log("it is currently", dropdownMenu.className);
  } else {
    console.error("this element does not exist");
  }
}

window.onclick = function(event) {
  if (!event.target.matches('.lang img')) {
    const dropdowns = document.getElementsByClassName('dropdown-content');
    for (let i = 0; i < dropdowns.length; i++) {
      const openDropdown = dropdowns[i];
      if (openDropdown.style.display === 'block') {
        openDropdown.style.display = 'none';
      }
    }
  }
}
@media only screen and (max-width: 768px) {
  .desktop-ui {
    display: none;
  }
  .mobile-ui {
    display: block;
    overflow-x: none;
  }
}

@media only screen and (min-width: 769px) {
  .desktop-ui {
    display: block;
  }
  .mobile-ui {
    display: none;
  }
}

.lang {
  position: absolute;
  z-index: 100;
  top: 35%;
  right: 19.5%;
  transform: translateY(-50%);
  height: 40px;
  width: 40px;
}

.lang img {
  width: 50px;
  height: 50px;
  cursor: pointer;
}

.lang img:hover {
  opacity: 0.7;
  transition: ease-in-out 0.3s;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: transparent;
  min-width: 160px;
  z-index: 1;
  backdrop-filter: blur(8px);
  border-radius: 10px;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.75);
}

.dropdown-content a {
  color: #ffffff;
  padding: 8px 16px;
  text-decoration: none;
  display: flex;
  align-items: center;
  font-size: 14px;
  letter-spacing: 2px;
  font-family: Semibold;
}

.dropdown-content a:hover {
  text-decoration: underline #2E75B6 1.5px;
  color: rgba(209, 209, 209, 0.8);
  transition: ease-in-out 0.5s;
}

.dropdown-content img {
  margin-right: 10px;
  width: 20px;
  height: 20px;
}

.dropdown-content img:hover {
  filter: drop-shadow(0px 0px 5px 0px rgba(0, 0, 0, 0.75));
  transition: ease-in-out 0.5s;
}

.mobile-ui .lang {
  position: absolute;
  z-index: 100;
  top: 40px;
  right: 20px;
  transform: translateY(-50%);
  height: 40px;
  width: 40px;
}

.mobile-ui .lang img {
  width: 50px;
  height: 50px;
  cursor: pointer;
}

.mobile-ui .lang img:hover {
  opacity: 0.7;
  transition: ease-in-out 0.3s;
}
<div class="lang">
  <img src="//cdn.sstatic.net/sites/stackoverflow/img/favicon.ico" alt="Language Icon" onclick="toggleDropdown()" style="width: 35px;height: 35px;">
  <div class="dropdown-content" id="dropdownMenu">
    <a href="index.html"><img src="https://flagsapi.com/GB/flat/64.png">English</a>
    <a href="index.html"><img src="https://flagsapi.com/CN/flat/64.png">中文</a>
  </div>
</div>

I’ve tried changing the function and tried isolating the language switching dropdown into a separate webpage to see if other JS function is conflicting, it still doesn’t work.

importmap raises “SyntaxError: Unexpected identifier” with interact.js

I’m trying to import interact.js with an importmap, but I get the error:

Uncaught SyntaxError: Unexpected identifier 'interactjs'.

My importmap:

<script type="importmap">
    {
        "imports": {
            "interactjs": "https://cdn.interactjs.io/v1.9.20/interactjs/index.js"
        }
    }
</script>

My JavaScript code:

<script type="module">
    import interact from interactjs;

    interact('.item').draggable({
        onmove(event) {
            console.log(event.pageX, event.pageY)
        },
    })
</script>

A normal script src include works without issue.

<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>

Any ideas?

Vue JS – Todo List

I am having trouble creating a todo list with vue.js

Here is the list:

HTML:

<div id="aufgabenApp">
<article class="inhalt">
 <h2>To-do-List</h2>
<p>
<label for="neueAufgabe">Tasks</label>
<input type="text" id="neueAufgabe" v-model="neueAufgabe"> <button class="hinzu" @click="aufgabeHinzu">hinzufügen</button>
</p>

    
<h2>All Tasks</h2>
<ul>
 <li v-for="(aufgabe, index) in aufgaben" :class="{
 'abgeschlossen' : aufgabe.fertig}">
<p>{{aufgabe.beschreibung}}</p>
<button class="erledigtWechseln" @click="erledigtWechseln(index)">&#10003;</button>
<button class="loeschen" @click="loeschen(index)">x</button>
</li> </ul>




<h2>To Do</h2>
<ul>
<li v-for="aufgabe in nichterledigt">{{ aufgabe.beschreibung }}</li>
</ul>
<h2>Already done</h2>
<ul>
<li v-for="aufgabe in erledigt">{{ aufgabe.beschreibung }}</li> </ul>
</div>

JS Code:

<script>
const app = {
  data() {
   return {
    neueAufgabe:"",
      aufgaben: [
       { beschreibung: "Get up", fertig: false },
       { beschreibung: "Sport", fertig: false },
       { beschreibung: "Meditation", fertig: false },
       { beschreibung: "Mails", fertig: false },
       { beschreibung: "Backup", fertig: false },
       { beschreibung: "clean up", fertig: false },
],
neueAufgabe: ''
};
}, 

methods: {
  aufgabeHinzu() {
this.aufgaben.push({beschreibung: this.neueAufgabe, fertig: false});
this.neueAufgabe = '';
  },
  loeschen(index) {
   this.aufgaben.splice(index, 1);
  },
  
    erledigtWechseln(index) {
    this.aufgaben[index].fertig = this.aufgaben[index].fertig ? false : true;
} 
},


computed: {
    erledigt() {
return this.aufgaben.filter(aufgabe => aufgabe.fertig); },
nichterledigt() {
return this.aufgaben.filter(aufgabe => !aufgabe.fertig);
}, 
},

};
Vue.createApp(app).mount("#aufgabenApp");
</script>

</article>

What I am trying to achieve is that the number of already completed and uncompleted tasks

to be shown besides the h2-Headings in this part:

<h2>To Do</h2>
<ul>
<li v-for="aufgabe in nichterledigt">{{ aufgabe.beschreibung }}</li>
</ul>
<h2>Already done</h2>
<ul>
<li v-for="aufgabe in erledigt">{{ aufgabe.beschreibung }}</li> </ul>
</div>

How can I exactly achieve this with “computed properties” and “length” ?

Thanks so much!

How to pass a pointer array from C to JS using Web Assembly

I’m trying to improve my technical skills with Web Assembly, but I’m stuck at the behavior levels between C to JS pointers.

I want to clarify that I’m not a basic C developer, just some notions.

The process is : JS send data to worker -> worker call web assembly (C) -> worker send result -> JS render

When I send my calculations made in C to JS using Web Assembly, I get the pointer, only to translate this pointer back into an array is problematic for me.

The code on the C side seems correct to me (I get the right values ​​once compiled).

C:

#include "vector.h"
#include <stdlib.h>
#include <math.h>

void applyTransformation(Vector3D scale, Vector3D position, Vector3D rotation, Vector3D *vertex) {
    // Scale
    vertex->x *= scale.x;
    vertex->y *= scale.y;
    vertex->z *= scale.z;

    // Translate
    vertex->x += position.x;
    vertex->y += position.y;
    vertex->z += position.z;

    // Rotate
    double x = vertex->x;
    double y = vertex->y;
    double z = vertex->z;

    vertex->x = x * cos(rotation.y) * cos(rotation.z) + y * (cos(rotation.y) * sin(rotation.z) * sin(rotation.x) - sin(rotation.y) * cos(rotation.x)) + z * (cos(rotation.y) * sin(rotation.z) * cos(rotation.x) + sin(rotation.y) * sin(rotation.x));
    vertex->y = x * sin(rotation.y) * cos(rotation.z) + y * (sin(rotation.y) * sin(rotation.z) * sin(rotation.x) + cos(rotation.y) * cos(rotation.x)) + z * (sin(rotation.y) * sin(rotation.z) * cos(rotation.x) - cos(rotation.y) * sin(rotation.x));
    vertex->z = -x * sin(rotation.z) + y * cos(rotation.z) * sin(rotation.x) + z * cos(rotation.z) * cos(rotation.x);
}

Vector3D* cube(Vector3D scale, Vector3D position, Vector3D rotation) {
    Vector3D *vertices = (Vector3D *)malloc(sizeof(Vector3D) * 8);

    if (vertices == NULL) {
        return NULL;
    }

    vertices[0] = (Vector3D){-scale.x / 2, -scale.y / 2, -scale.z / 2};
    vertices[1] = (Vector3D){scale.x / 2, -scale.y / 2, -scale.z / 2};
    vertices[2] = (Vector3D){scale.x / 2, scale.y / 2, -scale.z / 2};
    vertices[3] = (Vector3D){-scale.x / 2, scale.y / 2, -scale.z / 2};
    vertices[4] = (Vector3D){-scale.x / 2, -scale.y / 2, scale.z / 2};
    vertices[5] = (Vector3D){scale.x / 2, -scale.y / 2, scale.z / 2};
    vertices[6] = (Vector3D){scale.x / 2, scale.y / 2, scale.z / 2};
    vertices[7] = (Vector3D){-scale.x / 2, scale.y / 2, scale.z / 2};

    for (int i = 0; i < 8; i++) {
        applyTransformation(scale, position, rotation, &vertices[i]);
    }
    
    return vertices;
}

void freeVertices(Vector3D *vertices) {
    free(vertices);
}

JS:

(async () => {
    importScripts('vector.js');

    const VectorModule = await VectorModuleWasm();

    if (!VectorModule) {
        throw new Error("Failed to load VectorModuleWasm");
    }

    onmessage = (event) => {
        const {
            id,
            scale,
            position,
            rotation,
            origin
        } = event.data;
        const verticesPointer = VectorModule._cube(scale, position, rotation);
        const numVertices = 8;
        const verticeBuffers = new Float32Array(VectorModule.HEAPF32.buffer, verticesPointer, numVertices * 3);

        let vertices = [];
        for (let i = 0; i < numVertices; i++) {
            vertices.push({
                x: verticeBuffers[i * 3],
                y: verticeBuffers[i * 3 + 1],
                z: verticeBuffers[i * 3 + 2]
            });
        }

        console.log(vertices);

        VectorModule._freeVertices(verticesPointer);

        postMessage({
            id: id,
            vertices: vertices,
            origin: origin
        });
    };
})();

And what I get in console log is an array of 8 vertices having x,y,z Infinity|-Infinity.

I need to fire an event for the IndexModel when the user closes the page

This is my code:

<script>
    function sendFieldData() {
        var email = document.getElementById('EmailComprador').value;
        var telefone = document.getElementById('TelefoneComprador2').value;
        var nome = document.getElementById('NomeComprador2').value;
        var data = {
            CostumerEmail: email,
            CostumerName: nome,
            CostumerPhone: telefone,
        };
        if (email) {
            let curfetchUrl = `${window.location.pathname}?handler=SaveAbandonedCart`;
            fetch(curfetchUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]').value
                },
                body: JSON.stringify(data)
            })
                .then(response => {
                    if (!response.ok) {
                        return response.text().then(text => { throw new Error(text); });
                    }
                    return response.json();
                })
                .then(responseData => {
                    console.log('salvo com sucesso', responseData);
                })
                .catch(error => {
                    console.error('erro:', error);
                });
        }
    }
    window.addEventListener('beforeunload', function (event) {
        setTimeout(sendFieldData, 0);
    });
</script>

At first it only calls the method on the IndexModel when I reload the page, but that’s not what I want. I want when the user clicks on close tab to trigger the event to the backend as well.

Obs.: I already used unload, it didn’t work.
I’m using Razor, Js and C#

Why am I only seeing the last typed character in my React input field?

I’m working on a React component where I want to update the state with the value entered in an input field. However, I’m encountering an issue where I’m unable to see what I’m typing in the input field, except for the last character.

function App() {
  const [name, setName] = useState("");
  let newName;

  function handleChange(event) {
    newName = event.target.value;
    console.log(newName);
  }

  function handleClick() {
    setName(newName);
  }

  return (
    <div className="container">
      <h1>Hello {name}</h1>
      <input
        onChange={handleChange}
        type="text"
        placeholder="What's your name?"
        value={name}
      />
      <button onClick={handleClick}>Submit</button>
    </div>
  );
}

I understand that the issue is related to the way the state is being updated, but I’m confused about why I can’t see the characters as I type. Even though handleChange is called and I can see the value in the console, the input field only displays the last typed character.

Could someone explain why this is happening and how I can fix it?

I expected that when handleChange was called, the console would print an empty string because the value of the input is bound to the name state, which is initially an empty string. However, I was surprised to see that only the last character typed was displayed in the input field.