JavaScript SetInterval toggle between Heads and Tails

I am writing a simple coin toss script. I want to animate between Heads and Tails for 1 second before the result is output. I am using a SetInterval. I want the display to change between Heads and Tails every time the SetInterval runs. Here is the code I have

let rollingAnimator = setInterval( ()=> {
    image.src = "heads.png";
    //the next time, it should do
    //image.src = "tails.png";
}, 100);

Thanks in advance.

I am able to use Math.random() to randomly display Heads or Tails. But that’s not what I want. I want it to alternate between Heads and Tails.

Can we manipulate props in React JS Component to create interactions?

I have created an example program for practice using React JS, this program aims to make a component display when the mouse is over this component and when this component is clicked, and this component will disappear when we click on another component and the mouse cursor is. not on it. Can you please check if my code writing complies with React JS writing rules.

To display and remove components, I made modifications to the class which will become a selector in CSS.

import React, { useState } from "react";
import ReactDOM from "react-dom/client";

import Style from "./App01.module.css"

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
);

function App() {
    const [isClicked, setIsClicked] = useState("")

    function onClicked(e) {
        if(e.target.closest("#content")) {
            setIsClicked(Style.ClickOn);
        } else {
            setIsClicked("");
        }
    }

    return (
        <section className={Style.Container} onClick={onClicked}>
            <Content isClicked={isClicked} />
        </section>
    );
}

function Content({isClicked}) {
    const [isHover, setIsHover] = useState("");

    function onMouse(e) {
        switch(e.type) {
            case "mouseover":
                setIsHover(Style.HoverOn);
                break;
            case "mouseout":
                setIsHover("");
                break;
            default:
                console.log("Its Error!");
        }
    }

    return (
        <section id="content" className={`${Style.Content} ${isHover} ${isClicked}`} onMouseOver={onMouse} onMouseOut={onMouse}>
            <p>HiHi!</p>
        </section>
    );
}
* {
    margin: 0;
    padding: 0;
}

.Container {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: cornflowerblue;
    height: 100vh;
}

.Content {
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px solid orange;
    transition: background-color 0.6s, border 0.6s;
    border-radius: 10px;
    width: 800px;
    height: 80px;
}

.Content p {
    opacity: 0;
    font-family: 'Courier New', Courier, monospace;
    font-style: italic;
    font-weight: bold;
    transition: opacity 0.6s;
    font-size: 40px;
}

.HoverOn {
    background-color: orange;
    border: 2px solid black;
}

.HoverOn p {
    opacity: 1;
}

.ClickOn {
    background-color: orange;
    border: 2px solid black;
}

.ClickOn p {
    opacity: 1;
}

Error 404 appear in console browser when execute JS script

I have an issue with my Javascript script that loads data for my website.
My site is hosted on my local PC, as well as the API I use. The website is not intended to be deployed online as it is a study project.

Currently, the site is fully functional, but I have one detail to fix. I’m asked to ensure that no JavaScript errors appear in the browser console. However, among the data I need to load, there are images hosted online. I only retrieve the image URL via the API.

So I load the image via the URL provided by the API to integrate it directly into my website, and this is where I’m stuck. Among these images, some are no longer available via the provided URL, which causes a 404 error in the browser console. I already replace these images with a locally hosted image when this happens. However, the error still appears in the browser because I still make a request to the image URL to determine if it’s valid or not and replace it accordingly.

Do you know of a way to fix this? I’ve tried to handle it using try/catch and other methods like onload and onerror, but nothing works. The error still appears in the browser console.

PS: I’m not allowed to use plugins or modules

Thank you in advance for your help

I tried using try/catch and onload/onerror in different ways. In reality, I think it’s an oversight on the part of those who designed the API four years ago, because the unavailable images have not been so for the past 2 to 3 years (I checked on waybackmachines). So, those working on the project today are faced with an error that cannot be handled when we do everything locally, despite being asked not to have any errors in the browser console (it’s the only error that appears, everything else is perfect)

how to clear part of the dom with react?

that we press the button which activates the delete function sometimes it works sometimes it doesn’t work.
I don’t know where the problem comes from I need help thanks in advance.

import { useState } from "react";

function MyElementDiv() {
  const [value, setValue] = useState("");
  const [element, setElement] = useState([]);

  const effacer = ({ target }) => {
    setElement((prevElements) => prevElements.filter((N) => N !== target.name));
  };

  const MyElementDiv = element.map((elements) => {
    return (
      <li id={elements}>
        <ul>{elements}</ul>
        <button onClick={effacer} name={elements}>
          effacer
        </button>
      </li>
    );
  });

  const Change = ({ target }) => {
    setValue(target.value);
  };
  const submit = (e) => {
    e.preventDefault();
    setElement((prev) => {
      return [...prev, value];
    });
  };

  return (
    <>
      <form>
        <input type="text" onChange={Change} value={value} />
        <button onClick={submit}>submit</button>
      </form>
      <div>{MyElementDiv}</div>
    </>
  );
}

export default MyElementDiv;

I would like when I press the button to delete the <li> tag containing the button to disappear.

How to use Swiper.js in Next.js?

I would like to use the library https://swiperjs.com/ in my Next.js project, but after installing and importing as the “Get started” tutorial instructed, I got the document not defined error.

Then I did some research and it says I need to use dynamic import.

So I tried

import dynamic from "next/dynamic";
import { CSSSelector, SwiperOptions } from 'swiper/types';

type SwiperProps = {
  container: CSSSelector | HTMLElement,
  options?: SwiperOptions
}

const Swiper = dynamic<SwiperProps>(() => import('swiper').then((module) => module.Swiper));

Then I got another error

Argument of type '() => Promise<ComponentClass<SwiperProps, any> | FunctionComponent<SwiperProps> | ComponentModule<SwiperProps> | typeof Swiper>' is not assignable to parameter of type 'DynamicOptions<SwiperProps> | Loader<SwiperProps>'.

I created the SwiperProps type because it is said that I need to use the props of the Swiper module, I don’t know where to find the props so I found the following definition:

enter image description here

Is the parameters in the constructor the props?

Please help. Thanks!

Why is .textContent giving me an Uncaught Typeerror: Cannot set properties of null (setting ‘textContent’)?? [duplicate]

While making a BlackJack game, In line 25 in JS I am trying to tell JavaScript to redeclare the .textContent of the variable messageEl to the variable message whenever the user clicks on the button but it’s giving the error Uncaught Typeerror: Cannot set properties of null (setting ‘textContent’)

HTML:

<h1>Blackjack</h1>
<p>Want to play a round?</p>
<p>Cards: </p>
<p>Sum: </p>
<button onclick="startGame">START GAME</button>

Javascript:

 let firstCard = 2
 let secondCard = 1
let sum = firstCard + secondCard

let isAlive = true
let hasBlackJack = false

let message = ""

let messageEl = document.getElementById("messageEl")


function startGame() {
if (sum <= 20) {
   message = "Do you want a draw?"
} else if (sum === 21) {
hasBlackJack = true
    message = "Whoa! You've won a BlackJack" 
} else {
isAlive = false
message = "You lost"
}
messageEl.textContent = message // this is the line that's making the problem and I have no clue what makes it wrong!
}

Next.js 14 POST – TypeError: Body is unusable at specConsumeBody

I am trying to POST user details to an API route in Next.js 14. It works correctly when only sending the id and firstname, however I am receiving the error (below) once I start adding an additional field, for example “lastname”.

Working code:

export async function POST(
  req: Request,
) {
  try {
    const { getUser } = getKindeServerSession();
    const authuser = await getUser()

    const id = await authuser?.id
    const { firstname } = await req.json();
   
    if (!id) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const user = await db.user.create({
      data: {
        id,
        firstname: firstname,        
       }
    });

   console.log(user);

    return NextResponse.json(user);
  } catch (error) {
    console.log("[USER]", error);
    return new NextResponse("Internal Error", { status: 500 });
  }
}


console.log(user);

{
  id: 'kp_7e90fc74577e46bfb3133eb73ac8ed89',
  firstname: 'Louis2',
  lastname: null,
  grade: null,
  profilepicture: null,
  email: null,
  contactnumber: null,
  isActive: false,
  createdAt: 2024-04-16T19:01:21.871Z,
  updatedAt: 2024-04-16T19:01:21.871Z
}

Code not working (added lastname):

export async function POST(
  req: Request,
) {
  try {
    const { getUser } = getKindeServerSession();
    const authuser = await getUser()

    const id = await authuser?.id
    const { firstname } = await req.json();
    const { lastname } = await req.json();
   
    if (!id) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const user = await db.user.create({
      data: {
        id,
        firstname: firstname,  
        lastname: lastname,
       }
    });

   console.log(user);

    return NextResponse.json(user);
  } catch (error) {
    console.log("[USER]", error);
    return new NextResponse("Internal Error", { status: 500 });
  }
}

Error message:

[USER] TypeError: Body is unusable
    at specConsumeBody (node:internal/deps/undici/undici:5294:15)
    at tl.json (node:internal/deps/undici/undici:5196:18)
    at c (/var/task/.next/server/app/api/user/route.js:1:1075)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /var/task/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:42484
    at async eI.execute (/var/task/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:32486)
    at async eI.handle (/var/task/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:43737)
    at async Y (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:16:24659)
    at async Q.responseCache.get.routeKind (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:17:1025)
    at async r2.renderToResponseWithComponentsImpl (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:17:507)

Getting error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘data’) at handleSubmit. Request is timing out, MERN app

I have a registration page that is supposed to post user input from a form:

// Registration.jsx
import React, { useState } from 'react';
import axios from 'axios';

const Registration = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [successMessage, setSuccessMessage] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      // Validation logic (you can use a library like Yup for form validation)
      if (!email || !password) {
        setError('Email and password are required.');
        return;
      }
      console.log("Test");
      // Registration API call
      const response = await axios.post('http://localhost:5000/api/auth/register', { email, password });
      console.log(response);
      setSuccessMessage(response.data.message);
    } catch (error) {
      setError(error.response.data.message);
    }
  }

  return (
    <div className="container">
      <div className="row">
        <div className="col-md-6 offset-md-3">
          <h2>Registration</h2>
          {error && <div className="alert alert-danger">{error}</div>}
          {successMessage && <div className="alert alert-success">{successMessage}</div>}
          <form onSubmit={handleSubmit}>
            <div className="mb-3">
              <label htmlFor="email" className="form-label">Email address</label>
              <input type="email" className="form-control" id="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
            </div>
            <div className="mb-3">
              <label htmlFor="password" className="form-label">Password</label>
              <input type="password" className="form-control" id="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
            </div>
            <button type="submit" className="btn btn-primary">Register</button>
          </form>
        </div>
      </div>
    </div>
  );
}

export default Registration;

When I submit the form nothing happens, I go to the network tab to see whats going on and after a while of pending the request header eventually says 408 Request time out. Thats when these 3 show up in the console:

Access to XMLHttpRequest at 'http://localhost:5000/api/auth/register' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
POST http://localhost:5000/api/auth/register net::ERR_FAILED 408 (Request Timeout)
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
    at handleSubmit (main.18ffb0dca439882a5d90.hot-update.js:50:31)

I’m not too sure its the first error because I set up proxy middleware for the cross origin access and the proxy request headers seem to be completing just fine every time:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true, // Needed for virtual hosted sites
      ws: true, // Proxy websockets
      pathRewrite: {
        '^/api': '' // remove base path
      }
    })
  );
};
// server.js

const express = require('express');
const connectDB = require('./config/db.js');
var cors = require('cors');
const proxyMiddleware = require('./middleware/Proxy.js');


const app = express();

// Connect to MongoDB
connectDB();

// Middleware
app.use(express.json()); // Parse JSON bodies
proxyMiddleware(app);

// Define CORS options
const corsOptions = {
  origin: 'http://localhost:3000',
  credentials: true, // Access-Control-Allow-Credentials header
  optionSuccessStatus: 200
};
app.use(cors(corsOptions));

// Routes
app.use('/api/auth', require('./routes/auth'));

// Define port
const PORT = process.env.PORT || 5000;

app.get('/', (req, res) => {
  res.send('Hello, welcome to the API server!');
});

// Start server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

module.exports=app;

Proxy response header:

HTTP/1.1 204 No Content
x-powered-by: Express
access-control-allow-origin: http://localhost:3000
vary: Origin, Access-Control-Request-Headers
access-control-allow-credentials: true
access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
access-control-allow-headers: content-type
content-length: 0
date: Wed, 17 Apr 2024 14:20:11 GMT
connection: close

I belive the problem lies in the last error, in an attempt to fix it I consol.log() the problem areas as shown by the registration.jsx page. The console log for test runs fine but the console log after this statement doesnt even run

const response = await axios.post('http://localhost:5000/api/auth/register', { email, password });

Is there something wrong with the statement? I’ll include anything I think you might need bellow, thanks in advance.

//auth.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user.js');
const  registerValidation  = require('../middleware/validation.js');
const { validationResult } = require('express-validator');
//Register Route
router.post('/register', registerValidation, async (req, res) => {
  // Validate request body
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  const { email, password } = req.body;

  try {
    // Check if user already exists
    let user = await User.findOne({ email });
    if (user) {
      return res.status(400).json({ msg: 'User already exists' });
    }

    // Create new user
    user = new User({
      email,
      password
    });

    // Hash password
    const salt = await bcrypt.genSalt(10);
    user.password = await bcrypt.hash(password, salt);

    // Save user to database
    await user.save();

    // Generate JWT token
    const payload = {
      user: {
        id: user.id
      }
    };

    jwt.sign(
      payload,
      process.env.JWT_SECRET,
      { expiresIn: '1d' },
      (err, token) => {
        if (err) throw err;
        res.json({ token });
      }
    );
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

//Email Verification Route
router.get('/verify/:token', async (req, res) => {
    const token = req.params.token;
  
    try {
      // Verify token
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
  
      // Update user's verified status
      await User.findByIdAndUpdate(decoded.user.id, { verified: true });
  
      res.json({ msg: 'Email verified successfully' });
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  });

// Login Route
router.post('/login', async (req, res) => {
    const { email, password } = req.body;
  
    try {
      // Check if user exists
      let user = await User.findOne({ email });
      if (!user) {
        return res.status(400).json({ msg: 'Invalid Credentials' });
      }
  
      // Check if password matches
      const isMatch = await bcrypt.compare(password, user.password);
      if (!isMatch) {
        return res.status(400).json({ msg: 'Invalid Credentials' });
      }
  
      // Check if user is verified
      if (!user.verified) {
        return res.status(400).json({ msg: 'Please verify your email' });
      }
  
      // Generate JWT token
      const payload = {
        user: {
          id: user.id
        }
      };
  
      jwt.sign(
        payload,
        process.env.JWT_SECRET,
        { expiresIn: '1d' },
        (err, token) => {
          if (err) throw err;
          res.json({ token });
        }
      );
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  });

// Forgot password route
router.post('/forgot-password', async (req, res) => {
    const { email } = req.body;
  
    try {
      // Check if user exists
      const user = await User.findOne({ email });
      if (!user) {
        return res.status(400).json({ msg: 'User not found' });
      }
  
      // Generate verification code
      const verificationCode = Math.floor(100000 + Math.random() * 900000);
  
      // Implement logic to send verification code to user's email using SendGrid
  
      res.json({ msg: 'Verification code sent to your email' });
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  });
  
// Verify Code route
router.post('/verify-code', async (req, res) => {
    const { email, verificationCode } = req.body;
  
    try {
      // Check if user exists
      const user = await User.findOne({ email });
      if (!user) {
        return res.status(400).json({ msg: 'User not found' });
      }
  
      // Check if verification code matches
      if (user.verificationCode !== verificationCode) {
        return res.status(400).json({ msg: 'Invalid verification code' });
      }
  
      // If verification code matches, update user's verified status
      user.verified = true;
      // Clear verification code after successful verification
      user.verificationCode = null;
      await user.save();
  
      res.json({ msg: 'Verification code verified' });
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  });
  
  //Rest Password route
  router.post('/reset-password', async (req, res) => {
    const { email, newPassword } = req.body;
  
    try {
      // Check if user exists
      const user = await User.findOne({ email });
      if (!user) {
        return res.status(400).json({ msg: 'User not found' });
      }
  
      // Hash new password
      const salt = await bcrypt.genSalt(10);
      user.password = await bcrypt.hash(newPassword, salt);
  
      // Save new password to database
      await user.save();
  
      res.json({ msg: 'Password reset successful' });
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  });
  
  

module.exports = router;

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "Percy",
  "license": "ISC",
  "dependencies": {
    "@sendgrid/mail": "^8.1.3",
    "axios": "^1.6.8",
    "bcryptjs": "^2.4.3",
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "express-validator": "^7.0.1",
    "http-proxy-middleware": "^3.0.0",
    "jsonwebtoken": "^9.0.2",
    "mongoose": "^8.3.1",
    "nodemailer": "^6.9.13",
    "nodemon": "^3.1.0",
    "sendgrid": "^5.2.3"
  }
}
{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.6.8",
    "bootstrap": "^5.3.3",
    "react": "^18.2.0",
    "react-bootstrap": "^2.10.2",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

How to override property of Palette CommonColors in material ui v5

Im working on migrating Mui4 to Mui5, on our app we have a lot of components that have this styling and colors

const styles = (theme: ThemeModel) => ({
  container: {
    borderColor: theme.palette.common.blueGray,
    backgroundColor: theme.palette.common.calendarCardBlue,
  },
});

notice the colors we are using that comes from palette.common, but now it looks like this approach doesnt work on material ui v5 they are coming as undefined

here is the theme code that was working on material ui v4


export const colors = {
  borderColor: '#4d5b6b',
  blueLink: '#3592f9',
  footerBlue: '#22313f',
  behavorialTraitGraphFooter: '#1c2d3e6d',
  brightTeal: '#06dcbf',
  opaqueButton: '#ffffff66',
  searchBarLightBlue: '#51647a99',
  filterBlue: '#25303E',
  photoGalleryBlue: '#131B23',
  sectionButtonColor: '#3c4a58',
  calendarCardBlue: '#18127',
  blueGray: '#2C3E51',
};

export let theme = createTheme({
  // Colors
  palette: {
    mode: 'dark',
    background: {
      default: colors.darkGray,
    },
    primary: {
      main: colors.teal,
      contrastText: colors.white,
    },
    common: { ...colors },
  },
  // Typography
  ...etc
  },
});

we are passing a colors object to the common property on theme and with that we have access to those colors on the components when styling them, is there a way we can make it work on material ui v5?

Tesseract – Use in Browser Console

I am trying to use Tesseract within the browser console. This is for a site for which is not my own so I cannot embed external scripts for security reasons, hence why I run my code in the browser console. However, it is only for personal use and for intention of reading data from a canvas image.

I embedded the JS from ‘https://cdn.jsdelivr.net/npm/[email protected]/dist/tesseract.min.js’ and then ran the following from the examples page of Tesseract GitHub pages:

(async () => {
const worker = await createWorker('eng');
const ret = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png');
console.log(ret.data.text);
await worker.terminate();
})();

Which produces the following error (also because of security issues.): ‘VM11097:6 Uncaught (in promise) Uncaught NetworkError: Failed to execute ‘importScripts’ on ‘WorkerGlobalScope’: The script at ‘https://cdn.jsdelivr.net/npm/[email protected]/dist/worker.min.js’ failed to load.’

Is it possible to compile the Tesseract JS files into a single block of code? Essentially, I want to bypass anything which involves referencing an external source.

Many thanks, greatly appreciated.

JS function giving inconsistent output

I am trying to implement 2 questions.

// Question 1: Given a greet() function modify it to update its context with an object
// having firstName and lastName properties.

function greet(name) {
  console.log("lalalalaHi " + name + " " + this + " is the original context of the function");
}
greet("Ron");

var obj = {
  firstName: "Alex",
  lastName: "Riley"
}
greet.call(obj, "Ron");


// Question 2: Given a greet() function modify it to update its context with an object 
// having firstName and lastName properties
// and allow it to accept multiple arguments in an array

function greet(name, lastName) {
  console.log("Hi " + name, lastName + ", I am " + this.firstName, this.lastName);
}

myDetails = { "firstName": "Harry", "lastName": "Potter" }
greet.apply(myDetails, ["Ron", "Weasley"]); //Passing object myDetails for this keyword

myDetails = { "firstName": "James", "lastName": "Potter" }
greet.apply(myDetails, ["Ron", "Weasley"]); //Passing object myDetails for this keyword

When I am executing 1st question alone, I am getting output as,

lalalalaHi Ron [object global] is the original context of the function

lalalalaHi Ron [object Object] is the original context of the function

But when I am executing both together, my output for 1st ques is also getting changed

Hi Ron undefined, I am undefined undefined

Hi Ron undefined, I am Alex Riley

Please help me understand, what is happening here.

I ran the questions separately and together in both the cases I am getting different output.
How is this working…

how to code image with popup text and disappear if click again and with a button redirecting to specific site

how to code image with popup text and disappear if click again and with a button redirecting to specific site and manual slideshow. I’m using hostinger web builder.
(I don’t have a laptop/desktop i only use Android phone)

Toggle Text with Responsive Image and Button

/* Start with mobile styles as the default for the responsive image */

img.responsive-image {

width: 100%; /* Make image expand to the width of its container */

height: auto; /* Set image height to auto to maintain aspect ratio */

display: block; /* Eliminate any white space below the image */

margin: 0 auto; /* Center the image within its container */

cursor: pointer; /* Indicates it’s clickable */

}

/* For larger screens, you can set specific styles */

@media only screen and (min-width: 768px) {

img.responsive-image {

width: 50%; /* Adjust the width to fit properly on larger screens */

}

}

#overlay {

display: none;

position: fixed;

width: 100%;

height: 100%;

top: 0;

left: 0;

background-color: rgba(0,0,0,0.5);

z-index: 999;

padding-top: 100px;

}

#overlayContent {

background-color: #fff;

margin: auto;

padding: 20px;

width: 80%;

max-width: 600px;

border-radius: 5px;

text-align: center;

position: relative;

box-sizing: border-box;

}

.redirect-button {

display: block; /* Makes the button a block element */

margin: 20px auto 0 auto; /* Centrally aligns the button */

padding: 10px 20px;

background-color: #007bff;

color: white;

border: none;

border-radius: 5px;

cursor: pointer;

text-decoration: none; /* Removes underline from text */

}

.redirect-button:hover {

background-color: #0056b3;

}

<img src=”https://assets.zyrosite.com/A3QpnXPBg9UDZKKK/images-15-AMqnPq9eRNT44axO.jpeg”

 alt="Toggle Popup" 

 class="responsive-image" 

 onclick="toggleOverlay()"/>
<p>When a Delta Force team is ambushed in enemy territory, a rookie officer refuses to abandon them. Their only hope lies with an Air Force drone pilot as the eyes in the sky during a brutal 48-hour battle for survival.</p>

<a href="https://pastepeso.com/0vynlpjv" 

   target="_blank" 

   class="redirect-button">CLICK HERE TO DOWNLOAD</a>

function toggleOverlay() {

var overlay = document.getElementById(“overlay”);

// Toggle visibility

overlay.style.display = overlay.style.display === ‘block’ ? ‘none’ : ‘block’;

}

vanilla javaScript :: return synchronous text file [duplicate]

I am trying to read and return pure text file with vanilla javaScript.

Now here is the issue.

This is working perfectly!

function getTxtFile(e)
{
    let t=new XMLHttpRequest;
    t.open('GET',e,!0),t.overrideMimeType('text/html'),t.onreadystatechange=function()
    {
        if(4===t.readyState&&(200===t.status||0===t.status))console.log(t.responseText)
    },t.send(null)
}

But when I change the console.log to return it does not returning anything.

function getTxtFile(e)
{
    let t=new XMLHttpRequest;
    t.open('GET',e,!0),t.overrideMimeType('text/html'),t.onreadystatechange=function()
    {
        if(4===t.readyState&&(200===t.status||0===t.status))return t.responseText
    },t.send(null)
}

One more thing to mentioned here is that it must by synchronous.

How can I have a link that executes a command in JQuery Terminal?

I’m trying to have some links to execute commands. For example:

function showMenu(consoleObj) {
consoleObj.echo("t[[!;;]about]      learn more about whatever");
...

I’d like the “about” text be clickable and execute the about function, rather than going to an external link.

For reference, I have anyLinks: true, in here:

$('.terminal').terminal({
anyLinks: true,
menu: function() {
    showMenu(this);
},
...

Just so you know, I’m a big time noob. Thank you!

I’ve tried:

consoleObj.echo("t[[!;#fff;;#about]about]      learn more about whatever");

and

consoleObj.echo("t[[!;#fff;;about]about]      learn more about whatever");

and

consoleObj.echo("t[[!;#fff;;!about]about]      learn more about whatever");

nothing worked (they all took me to an /about page, rather than executing the command).

Creating instance of child class in parent method

I have something similar to the following code for a parent and child class:

const modify = (data) => {
  const newData = data
  // changes newData in some way
  return newData
}

class Parent {
  constructor(data) {
    this.data = data
  }

  modify() {
    return new Parent(modify(this.data))
  }
}

class Child extends parent {
  constructor(data) {
    super(data)
  }
}

Is there a way to change the Parent class’s modify function to return an instance of Child when it is called using an instance of Child?

I know that in a static function, you can use new this() to do that, is there something equivalent for methods? Or would I have to overwrite the Parent method in the Child class?