Compare emails to check if they are equal gives error

I would like help with this question. If email1 and email2 (Strings) are equal when submit is pressed, an alert message box will be displayed. I didn’t add an else statement.

Error:

Uncaught ReferenceError ReferenceError: email1 is not defined
at (script.js:7:17)

function equals_function(email1, email2) {
  if (email1 != email2) {
    alert("You didn't enter matching email addresses in the input!") // output alter
  }
}

equals_function(email1, email2)
<form>
  <label for="email1">Email Address:</label>
  <input type="text" name="emailone" id="emailone">

  <p>
    <label for="email2">Email Address Confirmation:</label>
    <input type="text" name="emailtwo" id="emailtwo">
  </p>
  <p><input type="submit"></p>
</form>

Please, JavaScript and condition to compare strings. Easy, with HTML included (Simple form to check if arrays are equal)

I would like help with this question. If email1 and email2 (Strings) are equal when submit is pressed, an alert message box will be displayed. I didn’t add an else statement. The code for both labels is included. Thanks!

The equals_function at the bottom is incorrect with the quotes. I had equals_function(email1, email2) but had no luck, was getting an error in Visual Studio code. Please help with this code.

...
<label for="email1">Email Address:</label>
<input type="text" name="emailone" id="emailone">

<p>
<label for="email2">Email Address Confirmation:</label>
<input type="text" name="emailtwo" id="emailtwo">
<p>

<input type="submit">

...
</form>

Please, and the javascript

function equals_function(email1, email2) {
    if (email1 != email2 ) {
            alert("You didn't enter matching email addresses in the input!") // output alter
    }
}

equals_function("[email protected]", "[email protected]")

highchart multiple chart type duplicates the series as many as the chart types

I’m trying to load multiple chart type here using Highchart.

function loadChartDataMultiViz(variables, chartTypes, chartId) {
    $.ajax({
        url: '/datacap/site/getdatamulti',
        data: { variable: variables }, // Pass comma-separated variables
        success: function(response) {
            if (Object.keys(response).length > 0) {
                var series = [];
                var categories = Object.keys(response); // Extract years for x-axis
                var titles = [];
                chartTypes = chartTypes.split(',').map(type => type.trim());
                // Create a separate series for each chart type
                chartTypes.forEach(chartType => {
                    if (chartType === 'pie') {
                        // For pie charts, format the series differently
                        series.push({
                            type: chartType,
                            name: 'Data', // Generic name for the pie chart
                            colorByPoint: true,
                            data: categories.map(year => {
                                return {
                                    name: year, // Use year or any relevant label for each slice
                                    y: response[year][Object.keys(response[year])[0]].value || 0 // Use value for each slice, default to 0 if missing
                                };
                            })
                        });

                        // Collect titles for pie chart
                        titles.push(response[categories[0]][Object.keys(response[categories[0]])[0]].title);
                    } else {
                        // For other chart types (e.g., line, bar), create a series for each variable
                        for (const variable of Object.keys(response[categories[0]])) {
                            const data = categories.map(year => {
                                return response[year][variable] ? response[year][variable].value : 0; // Default to 0 if not available
                            });

                            series.push({
                                type: chartType,
                                name: variable, // Use the variable name for the series
                                data: data,
                            });

                            // Collect titles for each variable
                            if (response[categories[0]][variable] && response[categories[0]][variable].title) {
                                titles.push(response[categories[0]][variable].title);
                            }
                        }
                    }
                });

                Highcharts.chart(chartId, {
                    chart: {
                        type: 'container' // Use a container chart to hold multiple series
                    },
                    title: {
                        text: titles.join(',<br>'), // Combine all variable titles with a comma
                        align: 'left'
                    },
                    xAxis: {
                        categories: categories,
                        title: {
                            text: 'Year' // Example label for x-axis
                        }
                    },
                    yAxis: {
                        title: {
                            text: response[categories[0]][Object.keys(response[categories[0]])[0]].unit || 'Values'
                        }
                    },
                    series: series, // Pass the constructed series (formatted for pie or other charts)
                    annotations: [],
                    plotOptions: {
                        area: {            
                            marker: {
                                enabled: false,
                                symbol: 'circle',
                                radius: 2,
                                states: {
                                    hover: {
                                        enabled: true
                                    }
                                }
                            }
                        },
                        scatter: {
                            tooltip: {
                                pointFormatter: function () {
                                    // Customize the tooltip for scatter points
                                    return 'Year: <b>' + this.category + '</b><br>' +
                                        'Value: <b>' + this.y + '</b>';
                                }
                            },
                            lineWidth: 0, // Remove any connecting lines for the scatter plot
                            marker: {
                                radius: 5 // You can adjust the marker size here
                            }
                        }
                    },
                }, function (chart) {
                    // Add annotations after the chart is created
                    const data = chart.series[0].data.map(point => point.y);
                    addAnnotations(chart, data, 'highest'); // Annotate highest value
                    addAnnotations(chart, data, 'latest');  // Annotate latest value
                });
            }
        }
    });
}

My problem is, why is the data showing up 3 times for 3 variables (if I use 3 types of chart-type) here? This shows the title and everything else (legend, tooltips) also 3 times:

loadChartDataMultiViz('4,5,8', 'area,spline,column', 'd3-chart1'); // Example for multiple series

The code shows fine if I choose only one type of chart, like this:

loadChartDataMultiViz('4,5,6', 'spline', 'd3-chart2'); // Example for multiple series 
loadChartDataMultiViz('12,8', 'area', 'd3-chart3'); // Example for multiple series

How to ommit 3 levels inner key in typescript?

Giving following typescript code. how would you omit the email that is inside options and inside data?

interface SignUpObject {
  email:string, // not this one
  password: string,
  options: {
    emailRedirectTo: string,
    captchaToken?: string,
    data: {
      preferedLanguage: number
      name: string
      email: string // but this one!
      agreeTermsCheckbox: boolean
      whatJobYouHave: number
      birthday: string
      techYearsOfExpierence: string
      is_subscriber: boolean
      is_admin: boolean
      subscriber_expiration_timestamp: string | null
    }
  }
}

I already ommit password:

interface UpdateUserData extends Omit<SignUpObject, 'password'> {
  password?: string
}

I try search online, reading the docs, looking in forums and more

Trouble with CSS Autoprefixing and Minification in Webpack Configuration

I’m having a frustrating time getting my CSS to apply autoprefixing and minification correctly in my Webpack setup. Despite following various tutorials and adjusting my configuration, the resulting CSS does not seem to reflect the expected styles, and the autoprefixer does not seem to be working.

Here’s a breakdown of my project setup:

Project Structure:


        /my-project
    |-- /src
    |   |-- /js
    |   |   |-- app.js
    |   |-- /styles
    |   |   |-- app.scss
    |   |-- index.html
    |-- package.json
    |-- webpack.config.js
    |-- postcss.config.js

package.json Dependencies:


        {
      "devDependencies": {
        "autoprefixer": "^10.4.0",
        "css-loader": "^6.5.1",
        "html-webpack-plugin": "^5.3.2",
        "mini-css-extract-plugin": "^2.4.5",
        "postcss-loader": "^6.2.1",
        "postcss-preset-env": "^7.0.1",
        "cssnano": "^5.0.7",
        "sass-loader": "^12.1.0",
        "webpack": "^5.59.0",
        "webpack-cli": "^4.9.1",
        "webpack-dev-server": "^4.0.0"
      }
    }

webpack.config.js:


    const path = require("path");
    const HtmlWebpackPlugin = require("html-webpack-plugin");
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");
    const glob = require("glob");
    
    module.exports = (env, argv) => {
      const isProduction = argv.mode === "production";
    
      return {
        entry: "./src/js/app.js",
        output: {
          path: path.resolve(__dirname, "dist"),
          filename: "js/app.bundle.js",
          clean: true,
        },
        module: {
          rules: [
            {
              test: /.(s[ac]ss|css)$/i,
              use: [
                isProduction ? MiniCssExtractPlugin.loader : "style-loader",
                "css-loader",
                "postcss-loader",
                "sass-loader",
              ],
            },
          ],
        },
        plugins: [
          ...glob.sync("./src/**/*.html").map((file) => {
            return new HtmlWebpackPlugin({
              template: file,
              filename: path.basename(file),
            });
          }),
          ...(isProduction
            ? [
                new MiniCssExtractPlugin({
                  filename: "css/[name].css",
                }),
              ]
            : []),
        ],
        mode: isProduction ? "production" : "development",
      };
    };

postcss.config.js:


    module.exports = {
      plugins: [
        require('postcss-preset-env')({
          stage: 1,
        }),
        require('autoprefixer'),
        require('cssnano')({
          preset: 'default',
        }),
      ],
    };

CSS File (app.scss):


    body {
    display: flex;
    align-items: center;
    justify-content: center;
    }

Issues Encountered:
The resulting CSS file does not include any prefixes for flexbox properties.
The CSS is not being minified as expected in production mode.
I’ve confirmed that all necessary packages are installed, and I’m running the commands correctly.

What I’ve Tried:
I ensured that all dependencies are up to date.
I simplified my Webpack configuration for testing.
I checked the output in both development and production modes.
I verified the structure of my SCSS and JavaScript files.

Additional Information:


    "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "dev": "webpack serve --mode development",
    "build": "webpack --mode production"
    },

Questions:
What might be causing the autoprefixer not to work as expected in my Webpack setup?
Are there any common pitfalls in configuring PostCSS with Webpack that I might be missing?
Any help or insights would be greatly appreciated!

Emulator from Virtual Device Manager in Android Studio doesn’t recognize changes in code using Expo and React Native for Android. Fast refresh broken?

I’ve detected some annoying behaviour on Android emulator.

When changing the code in a JavaScript file that is not where the rendering snippet of the code is, the emulator seems to not recognize the changes after the file is saved and, even if an event is triggered, the changes do not take effect. I created a blank app just to test this behaviour, since I thought any library might have modified the Metro Bundler.

Didn’t find a quick solution on anywhere, so I copied and pasted the code is below:

App.js file:

import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View, Button } from "react-native";
import { PrintOutside } from "./assets/model/Print";

export default function App() {
PrintOutside();

function PrintInside() {
console.log("Printing inside 2");
}
return (
<View style={styles.container}>
<View style={styles.buttonView}>
<Button title="Printing from outside file" onPress={PrintOutside} />
</View>
<Button title="Print from inside file" onPress={PrintInside} />
<StatusBar style="auto" />
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
buttonView: {
marginBottom: 10,
},
});

Print.js file:

export function PrintOutside() {console.log("Printing outside")}

Whenever I click on the “Printing from outside file” button, It always log the same value, even if I change it on Print.js file and save it. However, if I change anything on the App.js file and save it, then the changed value on Print.js is logged. And on the other hand, any changes that I make in App.js file, after saved, are recognized by the emulator. For example, if I change console.log(“Printing inside 2”) to console.log(“Printing inside 3”), it works immediatly after saving the file and clicking the “Print from inside file” button.

Tried all the below, without success:

  1. Modifying app.json file, including "web": {"bundler": "metro"}, on expo property.
  2. Running expo start --clear to restart with a clean cache.
  3. Using the Expo development build, through npx expo run:android.
  4. Installing and using react-refresh.
  5. rm .git/index.lock (file does not exist)

The closest article that I found regarding my problem is the one below:

I’m really annoyed by this behavior cause it demands me to keep reloading the app so I can go on with my development.

Razor page issue .net 8

This is a Razor page issue. I have simple text box and corresponding search button created in the razor page, say it as index.cshtml.

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search Button Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            // Disable the button initially
            $('#searchButton').prop('disabled', true);
 
            // Enable button if text box has value
            $('#searchInput').on('input', function () {
                const inputValue = $(this).val();
                if (inputValue.trim() !== "") {
                    $('#searchButton').prop('disabled', false);
                } else {
                    $('#searchButton').prop('disabled', true);
                }
            });
        });
    </script>
</head>

and simple onGet method , which contains nothing.

The issue is: the search button is only enabled when user enters the text, which is working fine. But when the user press forward or back button of browser and reach to same page, button got disabled again, although it contains the data in the text box.

How can I resolve this?

Why is my pageLoad function suddenly undefined when I convert my javascript file to a module?

I’ve been developing a javascript application the old fashion way. That is, by referencing scripts one after the other in the html page header:

    <head>
        ...
        <script src="./helpers.js"></script>
        <script src="./pwvlogic.js"></script>
    </head>

But I would like to treat helpers.js as a module and import it into pwvlogic.js, and then remove the reference to it from the html page.

Here’s what helpers.js looked like before the change:

function createLineDiv(line) {
    ...
}

function fillActionButtonsContainer(actionButtonsContainer, line) {
    ...
}
  
function highlightSearchString(content) {
   ...
}

And here’s what it looks like after the change:

export function createLineDiv(line) {
    ...
}

export function fillActionButtonsContainer(actionButtonsContainer, line) {
    ...
}
  
export function highlightSearchString(content) {
   ...
}

export default {
   createLineDiv,
   fillActionButtonsContainer,
   highlightSearchString
}

And in pwvlogic.js, I add an import statement at the top:

import { createLineDiv, fillActionButtonsContainer, highlightSearchString } from './helpers.js';

Then in the html file, I remove the reference to helpers.js and add type="module" to the pwvlogic.js reference:

<script src="./pwvlogic.js" type="module"></script>

Now there is an issue with loading the pageLoad() function. In my html, I have this:

<body onload="pageLoad()">

And in pwvlogic.js, I have the pageLoad function:

function pageLoad() {
   ...
}

In the browser, I get the error:

Uncaught ReferenceError: pageLoad is not defined

Why is pageLoad suddenly undefined? Can I not reference it in a javascript module the same way I can a regular javascript file? How do I fix this?

Thanks!

How to deal with Safari on Macs not supporting alpha video?

I have a site with a video with an alpha layer. This works fine on every browser and platform except for Apple devices running Safari. This is because, for whatever reason, Apple has not deigned to implement support for video w/ alpha with the VP9 codec and WebM container, a combination which is supported ubiquitously otherwise.

I have found instructions online for using HEVC (H.265) with Alpha support to make the same approach work on Safari on an Apple device, but I haven’t been able to get it to work. In my testing, no matter what I do, it ignores the MOV or MP4 video that specifies codec hvc1 and instead plays the WebM file. Without the alpha channel, the video covers a rectangular area instead of only affecting the desired pixels.

At this point in time, I want to temporarily make the site simply not try to do this on Safari on Macs, until I figure out how to make it work. How can I do this, though? Everywhere I go, everyone says “test for the feature, not the browser” — that’s all fine and good, except that the “feature” in this case is essentially a browser “bug” and I don’t believe there is a way to test for it directly from JavaScript. User Agent strings are all but useless because anything based on Chrome seems to claim that it is Safari (and everything else) — Google’s deliberate attempt (mostly successful?) to kill the ability to detect which browser the page is running in, by the looks of it.

How can I detect specifically the combination of Safari on an Apple device and avoid enabling the visual composition that has disastrous results?

As an aside, if anybody wants to come at this from the other angle and try to just make the video with alpha work, I’ve got a separate question in the Video exchange:

https://video.stackexchange.com/questions/37745/how-to-encode-hevc-with-alpha-without-a-mac

How to save an image with custom quality using Jimp?

Im getting this error: leftHalf.quality is not a function

the original image is a jpeg, how to save it with the quality reduced?

            const buffer = Buffer.from(decodedData, 'base64')

            // Read the image using Jimp (synchronously)
            const image = await Jimp.read(buffer)

            // Get image dimensions
            const width  = image.width
            const height = image.height

            // Calculate the split point (vertical split)
            const splitPoint = Math.floor(width / 2)

            // Create two new images
            const leftHalf = image.clone().crop({ x: 0, y: 0, w: splitPoint, h: height })
            const rightHalf = image.clone().crop({ x: splitPoint, y: 0, w: width - splitPoint, h: height })

            await leftHalf.write('leftHalf.jpg')
            await rightHalf.write('rightHalf.jpg')

            await new Promise((resolve, reject) =>
            {
                leftHalf.quality(70).write('leftHalf2.jpg', (err) =>
                    {
                        if (err) reject(err)
                        else resolve()
                    })
            });

await leftHalf.write(‘leftHalf.jpg’)

await rightHalf.write(‘rightHalf.jpg’)

Both saves the images correctly, but how to also save it with the quality reduced to also reduce their sizes?

I have "jimp": "^1.6.0"

AudioJS – Get Average Frequency

I’m working on a ThreeJS project, and I need to get the average Frequency of a sound to visualize audio on a mesh.

I’ve tried the THREE.Audio() and works well, but my app needs to play the Audio at the beginning and three audio doesn’t do that. So I’m working with native Audio JS, but I’m a bit lost with how to create the audio context for passing to the analyzer and get the data.

I’m trying things like this but no success

    // Create Audio Context
    const audioContext = new (window.AudioContext || window.webkitAudioContext)();

    // Create Analyser Node
    const analyser = audioContext.createAnalyser();
    Set FFT size for the analyser (higher values = more frequency bins)
    analyser.fftSize = 2048;

    // Create a buffer to store the frequency data
    const bufferLength = analyser.frequencyBinCount;

    const frequencyData = new Uint8Array(bufferLength);

    // Connect audio element to analyser
    const source = audioContext.createMediaElementSource(music);
    source.connect(analyser);

    // Connect analyser to destination
    analyser.connect(audioContext.destination);

Some links that I’ve read

https://www.reddit.com/r/learnjavascript/comments/131hlma/how_can_we_get_frequency_values_in_hertz_from_an/

https://henrypye.medium.com/reading-audio-frequency-data-using-file-uploader-in-html-web-audio-api-and-p5-js-8cd819ff9ae0

https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API

Why does authInstance.isSignedIn.get() return always null?

i am trying to build a web game and at first I have this JavaScript “App.js”, where the user can log in via google and if he is logged in, he can log out.

But authInstance.isSignedIn.get() does always return null, after the user is logged in

import logo from './logo.svg';
import './App.css';
import LoginButton from "./components/login";
import LogoutButton from "./components/logout";
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import Dashboard from './components/dashboard'; // Dashboard-Seite
import Search from './components/search'; // Dashboard-Seite
import { gapi } from 'gapi-script';
const clientId = "MyApiURL";


function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false); // State für den Anmeldestatus


  useEffect(() => {
      function start() {
          gapi.client.init({
              clientId: clientId,
              scope: ""

          }).then(() => {
        const authInstance = gapi.auth2.getAuthInstance();

        // Setzt den Status basierend auf der aktuellen Anmeldung
        setIsLoggedIn(authInstance.isSignedIn.get());

        // Hört auf Änderungen des Anmeldestatus
        authInstance.isSignedIn.listen(setIsLoggedIn);
      });

      };

      gapi.load('client:auth2', start);

  }, []);

  
  
  return (
   <Router>
      <div className="App">
        <Routes>
          {/* Login-Route */}
          <Route path="/" element={isLoggedIn ? <LogoutButton /> : <LoginButton />} />
           <Route path="/search" element={<Search />} /> {/* Route für Search */}
          
          {/* Dashboard-Route nach erfolgreichem Login */}
          <Route path="/dashboard" element={<Dashboard isLoggedIn={isLoggedIn} />} />
        </Routes>
      </div>
    </Router>
  );
}

export default App;

This is the Login code. When the LoginButton is hit, this is carried out.

import {GoogleLogin} from 'react-google-login';
import { useNavigate } from 'react-router-dom';
import { gapi } from 'gapi-script';

const clientId = "...";



function Login(){
     const navigate = useNavigate();  // Initialisiere useNavigate

    const onSuccess = (res) => {
        console.log("LOGIN SUCCESS! Current user: ", res.profileObj);
        navigate('/dashboard'); 
    }

    const onFailure = (res) => {
        console.log("LOGIN FAILED! res: ", res);
    }
    
    return(
        <div id = "signInButton">
            <GoogleLogin
                clientId={clientId}
                buttonText="Login"
                onSuccess={onSuccess}
                onFailure={onFailure}
                cookiePolicy={'single_host_origin'}
                isSignedIn={true}
            />
        

        </div>
    )
}
export default Login;

drag and drop functionality for extjs tab panel

I have been searching for a way to implement drag and drop functionality for reordering tab items inside a tab panel component. I am using ExtJS 7 and as far as I know this functionality was only available back in ExtJS 4, using a plugin called Ext.ux.panel.DDTabPanel. Any ideas on if there is another way to drag and drop tab panel items?

Why are the pages on my Vite+React multi-page app defaulting to the homepage?

My React app should have 2 main webpages: localhost:3001/ and localhost:3001/tags/. The issue is that loading localhost:3001/tags/ will display the contents at localhost:3001/. I can also tell that /tags/ isn’t loading properly because I set the page title for it to “Tags” but instead, “Homepage” shows as the page title.

The file structure:

.env
index.html
package.json
vite.config.ts
etc.
src/
  | App.tsx
  | main.tsx
  | tags/
    | index.html
    | tags.tsx

The main index.html has the script tag with src="/src/main.tsx". The src/tags/index.html is the same as the main index.html except with <title>Tags</title> and script tag with src="./tags.tsx".

tags.tsx has a simple “Hello world” inside the createRoot().

vite.config.ts:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3001
  },
  build: {
    outDir: 'dist',
    emptyOutDir: true,
    rollupOptions: {
      input: {
        main: 'index.html',
        tags: 'src/tags/index.html'
      }
    }
  }
 })

How to resolve correctly my promise (React)

When i click some “ficha” the promise is completed correctly but when i click some other element in the DOM my event doesn´t finalice.
I want that when I click anything other than a token, the promise ends.
How can i resolve this?

The code:

import React from "react";
import { CardMovUser } from "../components/Cards/CardMovement";

const CardMovementContainer = ({
  movement,
  index,
  selectedCard,
  waitingForEvent,
  onCardClick,
  onEventComplete,
  isMyTurn
}) => {

  const handleClick = () => {
    if (!isMyTurn) return; 

    console.log("Clicked card", index);
    onCardClick(index);

    // Solo iniciar el evento de espera si `waitingForEvent` no está activo.
    if (!waitingForEvent) {
      waitForEvent("click", "[data-ficha-id]").then(() => {
        console.log("Ficha clicked OAAAAAAA");
        onEventComplete();
      });
    }
  };

  const waitForEvent = (eventType, selector) => {
    return new Promise((resolve) => {
      const handler = (event) => {
        console.log("Evento detectado en:", event.target); 
        const fichaElement = event.target.closest(selector);  selector
  
        if (fichaElement) {
          console.log("Ficha seleccionada: ", fichaElement); 
          document.removeEventListener(eventType, handler); 
          console.log("Evento removido");
          resolve();
        } 
      };
  
      console.log(`Añadiendo listener para ${eventType} en elementos que coincidan con ${selector}`);
      document.addEventListener(eventType, handler);
    });
  };

  return (
    <CardMovUser
      img_url={movement.movimiento.img_url}
      movetype={movement.movimiento.movement}
      handleClick={handleClick}
      clicked={selectedCard === index}
    />
  );
};

export default CardMovementContainer;

I’m trying to add an else statement, but when i click the card that triggers the event and the promise, this automatically ends the promise when it detects that I clicked something that was not a “ficha”.