Not able to see the component in my React app on building it

I am building a cryptotracker app using the CoinGecko API. This is my App component.

import Navbar from "./components/Navbar";
import Home from "./components/Home";
import { Route, Routes } from "react-router-dom";
import Show from "./components/Show";

function App() {
  return (
    <>
      <Navbar />
      <Routes>
        <Route index element={<Home />} />
        <Route path="/show" element={<Show />} />
      </Routes>
    </>
  );
}

export default App;

This is my index.js file:

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

This is my Navbar component:

import React from "react";
import { Link } from "react-router-dom";

function Navbar() {
  return (
    <>
      <div className="nav_container">
        <div className="nav">
          <div className="navigation_menu">
            <Link to="/" className="nav_heading">
              Coiner
            </Link>
            <ul>
              <li>Home</li>
              <li>Pricing</li>
              <li>Features</li>
              <li>About</li>
              <li>Contact</li>
            </ul>
          </div>
          <div className="nav_button">
            <button>Login</button>
          </div>
        </div>
      </div>
    </>
  );
}

export default Navbar;

This is my Home component:

import React, { useEffect, useState } from "react";
import axios from "axios";
import Coin from "./Coin";
import Query from "./Query";

function Home() {
  const [coins, setCoins] = useState();
  const [query, setQuery] = useState("");
  const [components, setComponents] = useState(true);
  const [queryCoins, setQueryCoins] = useState();
  const [heading, setHeading] = useState("Trending Coins");
  useEffect(() => {
    window.scrollTo(0, 0);
    const getCoins = async () => {
      const response = await axios.get(
        "https://api.coingecko.com/api/v3/search/trending"
      );
      const result = response.data.coins;
      setCoins(result);
    };
    getCoins();
  }, []);
  const handleQueryChange = (event) => {
    const new_value = event.target.value;
    if (new_value === "") {
      setComponents(true);
      setHeading("Trending Coins");
    }
    setQuery(event.target.value);
  };
  const handleQuery = async () => {
    const response = await axios.get(
      `https://api.coingecko.com/api/v3/search?query=${query}`
    );
    const result = response.data.coins;
    setQueryCoins(result);
    setComponents(false);
    setHeading("Search Results");
  };
  const handleKeyChange = (event) => {
    if (event.key === "Enter") {
      handleQuery();
    }
  };
  return (
    <>
      <div className="outer_home_container">
        <div className="input_container">
          <input
            type="text"
            className="search_input"
            placeholder="Search for coins..."
            value={query}
            onChange={handleQueryChange}
            onKeyDown={handleKeyChange}
            maxLength={20}
          />
          <button onClick={handleQuery} className="input_button">
            <i className="fa-solid fa-magnifying-glass"></i>
          </button>
        </div>
        <h1>{heading}</h1>
        <div className="container">
          {components ? (
            coins ? (
              coins.map((key) => {
                return <Coin coin={key} key={key.item.id} />;
              })
            ) : (
              <h2>Loading...</h2>
            )
          ) : queryCoins ? (
            queryCoins.map((key) => {
              return <Query coin={key} key={key.id} />;
            })
          ) : (
            <h2>Loading...</h2>
          )}
        </div>
      </div>
    </>
  );
}

export default Home;

The main problem is that when I run my app through npm run start, it successfully renders all the components, that is Navbar and Home. but after I build my app through npm run build and run the website through live server, it only renders the Navbar component, and to render the Home component I have to click the Coiner logo, and then and only then it successfully renders the Home component and my Navbar component together.

Sorry for making any mistakes in the format, I am new to the Stackoverflow Q&As.

I tried editing my package.json file before building the application.

Here is the code:

{
  "name": "app",
  "homepage": "./",
  "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.3",
    "lodash": "^4.17.21",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.21.1",
    "react-scripts": "5.0.1",
    "recharts": "^2.10.3",
    "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"
    ]
  }
}

I changed homepage to “./” but it did not work.

And here is the website’s link.

Any help would be appreciated.

I’m building my first website using an API, not sure why I’m pulling an error

I am using OMDb API to build a movie search platform for some practise in VS Code. I was watching a video and my syntax is almost identical, I am successfully pulling the data in a promise. Now when I go to use .map() to change the innerHTML, I’m pulling an error.

async function main() {
  const movie = await fetch("https://www.omdbapi.com/?i=tt3896198&apikey=ba040381");
  const movieData = await movie.json();
  const movieListEl = document.querySelector(".movie__list");

  console.log(movieData) // to prove data is being pulled

  movieListEl.innerHTML = movieData
    .map(
      (movie) =>
        `<div class="movie__card">
          <div class="movie__card--container">
            <h3>${movie.title}</h3>
            <p><b>Year:</b>0000</p>
            <p><b>Rating:</b>xxxxx</p>
            <p><b>Runtime:</b>xxxxx</p>
            <p><b>Genre:</b>xxxxx</p>
          </div>
        </div>`
    )
    .join("");
}

main();

This is not perfect by any means, but in the video this syntax seemed to work perfectly before cleaning up the code and making it easier to read by creating a separate function to change the HTML

(https://i.stack.imgur.com/mWZOU.png)

I’m very lost and had reached out for some help in this discord channel I’m in with unfortunately no luck. I am very new to JavaScript—and using APIs for that matter. Any feedback is very much appreciated.

Keep Javascript Speech Recognition in Webview run in Background Android

I’m building a WebApp in Java to show this page: https://davidwalsh.name/demo/speech-recognition.php,it’s using Javascript Speech Recognition. However, I want to make my WebApp and its Javascript run in background so it can work even the phone’s screen is turned off. Thanks for any helps!

And here’s my webapp code(I removed some unnecessary part like Permission Request to make it shorter):

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.PermissionRequest;

public class MainActivity extends AppCompatActivity {
    private WebView webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView) findViewById(R.id.webview);
        webview.setWebChromeClient(new WebChromeClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("https://davidwalsh.name/demo/speech-recognition.php");
    }
}

Electron App Shows spawn ENOTDIR at ChildProcess.spawn error After Packaging, but Works Locally

Problem Description:

I’m encountering an issue with my Electron app. After packaging the app and running I am getting the following error,However, when running it locally with npm run electron:serve, everything works fine.
Error

    Uncaught Exception:
    Error: spawn ENOTDIR
    at ChildProcess.spawn (node:internal/child_process:412:11)
    at spawn (node:child_process:707:9)
    at Object.<anonymous> (/Users/avinashkumaranshu/Project/Desktop/advance-notes-working/dist/mac-arm64/advance-notes.app/Contents/Resources/app.asar/electron/main.js:17:23)
    at Module._compile (node:internal/modules/cjs/loader:1116:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Module._load (node:internal/modules/cjs/loader:829:12)
    at Function.c._load (node:electron/js2c/asar_bundle:5:13331)
    at Object.<anonymous> (node:electron/js2c/browser_init:193:3197)
    at Object../lib/browser/init.ts (node:electron/js2c/browser_init:193:3401)

Code Details:

  • main.js: Path: /electron/main.js

    
     const { app, BrowserWindow, ipcMain } = require("electron");
     const path = require("path");
     const isDev = require("electron-is-dev");
     const { spawn } = require("child_process");
     const log = require("electron-log");
    
     log.transports.file.level = "debug"; // Set log level (e.g., debug, info, warn, error)
    
     const serverPath = path.join(__dirname, "../back-end/dist");
    
     ipcMain.on("log-message", (event, message) => {
       log.info(`[Renderer Log] ${message}`);
     });
    
     // Start NestJS server in a separate child process
     const serverProcess = spawn("node", ["main.js"], {
       cwd: serverPath,
       stdio: "inherit", // Redirect server logs to the main process console
     });
    
     // Wait for the server to start before creating the main window
     serverProcess.on("exit", (code, signal) => {
       if (code === 0) {
         // Create the main window only if the server process exits successfully
         createWindow();
       } else {
         // Handle errors or gracefully exit the app
         console.error(
           `Server process exited with code ${code} and signal ${signal}`
         );
         app.quit();
       }
     });
    
     function createWindow() {
       // Create the browser window.
       const win = new BrowserWindow({
         width: 800,
         height: 600,
         webPreferences: {
           nodeIntegration: false,
           enableRemoteModule: true,
         },
       });
    
       win.loadURL(
         isDev
           ? "http://localhost:3000"
           : `file://${path.join(__dirname, "../front-end/build/index.html")}`
       );
     }
    
     app.on("ready", createWindow);
    
     // Quit when all windows are closed.
     app.on("window-all-closed", function () {
       // On OS X it is common for applications and their menu bar
       // to stay active until the user quits explicitly with Cmd + Q
       if (process.platform !== "darwin") {
         app.quit();
       }
     });
    
     app.on("activate", function () {
       // On OS X it's common to re-create a window in the app when the
       // dock icon is clicked and there are no other windows open.
       if (BrowserWindow.getAllWindows().length === 0) createWindow();
     });
    
    
  • package.json: Path: /package.json

     {
       "name": "advance-notes",
       "version": "1.0.0",
       "description": "Main package.json",
       "main": "electron/main.js",
       "homepage": "./",
       "scripts": {
         "start": "cd front-end && react-scripts start",
         "build": "react-scripts build",
         "test": "react-scripts test",
         "eject": "react-scripts eject",
         "electron:serve": "concurrently -k " cd front-end && cross-env BROWSER=none yarn start" " yarn electron:start"",
         "electron:build": "cd front-end && yarn build && cd ../ && electron-builder -c.extraMetadata.main=electron/main.js",
         "electron:start": "wait-on tcp:3000 && electron ."
       },
       "build": {
         "extends": null,
         "appId": "com.example.advance-notes",
         "files": [
           "dist/**/*",
           "front-end/build/**/*",
           "front-end/node_modules/**/*",
           "back-end/dist/**/*",
           "back-end/node_modules/**/*",
           "node_modules/**/*",
           "electron",
           "package.json"
         ],
         "directories": {
           "buildResources": "assets"
         }
       },
       "devDependencies": {
         "@types/draft-js": "^0.11.16",
         "concurrently": "^5.3.0",
         "cross-env": "^7.0.3",
         "electron": "^16.0.0",
         "electron-builder": "^24.9.1",
         "prettier": "^2.2.1",
         "wait-on": "^5.2.1"
       },
       "dependencies": {
         "class-validator": "^0.14.0",
         "electron-is-dev": "^2.0.0",
         "electron-log": "^5.0.3"
       }
     }
    
  • React code path: /front-end

  • Nest code path: /back-end

    Additional Information:

    • Dependencies:

      • electron: 16.0.0

      • electron-builder: 24.9.1

    • Scripts:

      • Run the app locally (npm run electron:serve).

      • Build and package the app (npm run electron:build).

    • Environment:

      • Operating System: macOS

      • Node.js: 14.21.3

Why cannot I show the sum of elements in an array using forEach() in JavaScript?

I encountered a seemingly vague issue in my code.
I tried everything searching for answers online but of no avail.
I am in search on how to depict to the browser via my HTML element the sum of the array elements.

Here is my JavaScript Code below:

//create a counter function using closure method



//it counts the products that gets in the store
let time = Date();
const products = {
        productName: [],
        description: [],
        quantity: [],
        unitOfMeasure: []
    }
    //assigning values input into an array
let countLog = products.quantity;
let counterEl = document.getElementById('counter-el');
let countLogEl = document.getElementById("count-log-el");
let countSumEl = document.getElementById('count-sum-el');
let displaySumEl = document.getElementById('display-sum');

function counterIncrement(productName, description, count, unit) {
    productName = document.querySelector('.text-input-product').value;
    description = document.querySelector('.text-input-description').value;
    unit = document.querySelector('.text-input-unit-measure').value;
    products.productName.push(productName);
    products.description.push(description);
    count = "";
    count = document.getElementById('number-input').value;
    count = count.replace(/([^a-z0-9áéíóúñü_-s.,]|[tnfrv])/gim, "");
    document.getElementById('counter-el').textContent = `Your count is: ${count} ${unit} of ${productName}`;
    products.quantity.push(count);
    count += countLog;
    products.unitOfMeasure.push(unit);
}




function save(count) {
    count = document.getElementById('number-input').value;
    count = document.getElementById('number-input').value = "";
    counterEl.textContent = "Count is set to 0";
    countLogEl.textContent = "Count Log: ";
    for (let i = 0; i < countLog.length; i++) {
        countLogEl.textContent += countLog[i] + " - ";

    }

}

function sumArray(sum) {

    sum = "";
    countLog.forEach(myCount);

    function myCount(item) {
        sum += item;
    }
    displaySumEl.textContent = `Total: `;
    displaySumEl.textContent += `${sum}`;

}

I tried to find the solution online, but I was a kind frustrated.
I am expecting I can display the sum of the array items in my array of counted product quantity, but I was wondering why it only depicts the numbers appended side by side without adding it all up.

Error occurred prerendering page “/Contact”. Read more: https://nextjs.org/docs/messages/prerender-error TypeError: t(…).map is not a function

npm run dev success

npm run build error

Error occurred prerendering page “/Contact”. Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: t(…).map is not a function
at Contact (E:reactbig-power.nextserverchunks736.js:1:1394)
at Wc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:68:44)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:70:253)
at Z (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:76:89)
at $c (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:78:98)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:71:145)
at Z (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:76:89)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:70:481)
at Z (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:76:89)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:74:209)
TypeError: v(…).map is not a function
at Sustanabuty_Sustanabuty (E:reactbig-power.nextserverchunks302.js:1:5909)
at Wc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:68:44)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:70:253)
at Z (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:76:89)
at $c (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:78:98)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:71:145)
at Z (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:76:89)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:70:481)
at Z (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:76:89)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:74:209)

Error occurred prerendering page “/Sustanabuty”. Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: v(…).map is not a function
at Sustanabuty_Sustanabuty (E:reactbig-power.nextserverchunks302.js:1:5909)
at Wc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:68:44)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:70:253)
at Z (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:76:89)
at $c (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:78:98)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:71:145)
at Z (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:76:89)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:70:481)
at Z (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:76:89)
at Zc (E:reactbig-powernode_modulesreact-domcjsreact-dom-server.browser.production.min.js:74:209)
Generating static pages (8/44) [= ]
TypeError: v(…).map is not a function

enter image description here
Error occurred prerendering page “/Sustanabuty”. Read more: https://nextjs.org/docs/messages/prerender-error

React Native Android app crash. app.MainActivity (server)’ ~ Channel is unrecoverably broken and will be disposed?

System:
OS: macOS 14.1.1
CPU: (8) arm64 Apple M1
Memory: 124.52 MB / 16.00 GB
Shell: 5.9 – /bin/zsh
Binaries:
Node: 20.8.1 – /opt/homebrew/bin/node
Yarn: 1.22.19 – /opt/homebrew/bin/yarn
npm: 10.1.0 – /opt/homebrew/bin/npm
Watchman: 2023.10.09.00 – /opt/homebrew/bin/watchman
Managers:
CocoaPods: 1.11.3 – /usr/local/bin/pod
SDKs:
iOS SDK:
Platforms: DriverKit 23.0, iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0
Android SDK:
API Levels: 23, 27, 28, 29, 30, 31, 32, 33
Build Tools: 27.0.3, 28.0.3, 29.0.2, 30.0.2, 30.0.3, 31.0.0, 32.0.0, 32.1.0, 33.0.0, 33.0.2
System Images: android-28 | Google APIs ARM 64 v8a, android-28 | Google ARM64-V8a Play ARM 64 v8a, android-29 | Google APIs ARM 64 v8a, android-30 | Google APIs ARM 64 v8a, android-30 | Google Play ARM 64 v8a, android-31 | Google APIs ARM 64 v8a, android-32 | Google APIs ARM 64 v8a, android-33 | Google APIs ARM 64 v8a, android-34 | Google APIs ARM 64 v8a
Android NDK: 22.1.7171670
IDEs:
Android Studio: 2022.1 AI-221.6008.13.2211.9619390
Xcode: 15.0.1/15A507 – /usr/bin/xcodebuild
Languages:
Java: 18.0.1.1 – /usr/bin/javac
npmPackages:
@react-native-community/cli: Not Found
react: 17.0.1 => 17.0.1
react-native: 0.64.2 => 0.64.2
react-native-macos: Not Found
npmGlobalPackages:
react-native: Not Found

I have already check memory leak issue some logic issue but no any issue for this.

How do I get the anchorNode from a Selection object now?

For at least a year, I’ve been running JavaScript as part of a Mac Automator routine to look up right-clicked links. The URL is then passed to the next automator step to process.

The JavaScript to retrieve the URI was:

function run(input, parameters) {
    var app = Application("Safari");
    app.includeStandardAdditions = true;

    var url = app.doJavaScript('window.getSelection().anchorNode.parentNode.href',{
       in: app.windows[0].currentTab
    });

In the last few weeks, this stopped working, in both Safari and Orion. It looks like I’m still getting back a selection object from getSection(), but that the anchorNode (and the focusNode) are always null.
Did something change in WebKit recently? Is there some other way I should be doing this?

Words are colored after pressing the space key on the keyboard. I would like to color them immediately after the last letter

I have a problem with a Javascript script to color text. There are strings set for coloring, but the word is only colored when I press the “space” key on the keyboard. If i write the word, it doesn’t color. If I write the word and press the space key it becomes colored.

I would like to color the word immediately as i write it, without waiting to press the space button. For example, i set that HELLO should be colored. I would like it to color immediately as soon as I finish pressing the final O, and not when i type HELLO (with a final space).

The problem occurs when you try to manually write something in the code panel, for example if you write Hello. The problem lies in the changeColor() function, there is a Keyup Event and a Space Key Pressed.

I tried to remove the part of the code that concerns the EventListener(“keyup”… and the keycode, but everything breaks and doesn’t work. I am new to Javascript, I can’t solve it.

index.html

  <div id="editor" contenteditable="true" oninput="showPreview();" onchange="changeColor();">&lt;h1>This is a Heading&lt;/h1>
    &lt;p>This is a paragraph.&lt;/p>
  </div>
    
    <h3>PREVIEW</h3>
    <div class="preview-area">
      <iframe id="preview-window"></iframe>
    </div>

style.css

#editor {
  width: 400px;
  height: 100px;
  padding: 10px;
  background-color: #444;
  color: white;
  font-size: 14px;
  font-family: monospace;
  white-space: pre;
}
.statement {
  color: orange;
}

javascript.js

function applyColoring(element) {
    var keywords = ["DIV", "DIV", "H1", "H1", "P", "P", "HELLO", "<", ">", "/"];
  
    var newHTML = "";
    // Loop through words
    str = element.innerText;
    (chunks = str
      .split(new RegExp(keywords.map((w) => `(${w})`).join("|"), "i"))
      .filter(Boolean)),
      (markup = chunks.reduce((acc, chunk) => {
        acc += keywords.includes(chunk.toUpperCase())
          ? `<span class="statement">${chunk}</span>`
          : `<span class='other'>${chunk}</span>`;
        return acc;
      }, ""));
    element.innerHTML = markup;
  }
  


  // CHANGE COLOR 
  function changeColor() {
    // Keyup event
    document.querySelector("#editor").addEventListener("keyup", (e) => {
      // Space key pressed
      if (e.keyCode == 32) {
        applyColoring(e.target);
  
        // Set cursor postion to end of text
        //    document.querySelector('#editor').focus()
        var child = e.target.children;
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(child[child.length - 1], 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        this.focus();
      }
    });
  }
  
changeColor()
applyColoring(document.getElementById('editor'));


//PREVIEW
function showPreview() {
    var editor = document.getElementById("editor").innerText;
  
    // var cssCode =
    //  "<style>" + document.getElementById("cssCode").value + "</style>";
    // var jsCode =
    //  "<scri" + "pt>" + document.getElementById("jsCode").value + "</scri" + "pt>";
    
    var frame = document.getElementById("preview-window").contentWindow.document;
    document.getElementById("preview-window").srcdoc = editor;
    frame.open();
    //frame.write(htmlCode + cssCode + jsCode);
    frame.write(editor);
    frame.close();
  }
  
  showPreview()

trying to create an isogram using javascript (but there’s something i don’t understand)

so i’m fairly new to coding and i’m trying to make an isogram using javascript (without using any built-in methods because i’m still learning the basics) but i’m having difficulty grasping the logic behind this programming language. this is the code i initially used…

const isogram = word => {

  for(let i= 0; i< word.length; i++){ 
    for(let j = i+1; j< word.length; j++){
      if(word[i] === word[j]){
        console.log(`the letter '${word[j]}' is repeated`)
      } 
    }
  }
}

input: console.log(isogram("happy"));

//output: the letter 'p' is repeated

as you can see it worked fine UNITL i added an ‘else-statement’ and it went crazy:

const isogram = word => {

  for(let i= 0; i< word.length; i++){ 
    for(let j = i+1; j< word.length; j++){
      if(word[i] === word[j]){
        console.log(`the letter '${word[j]}' is repeated`)
      } else {
        console.log(`'${word}' is an isogram`)
      }
    }
  }
}

input: console.log(isogram("happy"));
//output: 'happy' is an isogram
'happy' is an isogram
'happy' is an isogram
'happy' is an isogram
'happy' is an isogram
'happy' is an isogram
'happy' is an isogram
the letter 'p' is repeated
'happy' is an isogram
'happy' is an isogram

input: console.log(isogram("cake"))
//output: 'cake' is an isogram
'cake' is an isogram
'cake' is an isogram
'cake' is an isogram
'cake' is an isogram
'cake' is an isogram

there’s two issues with this outcome:

  1. when i input a word that’s NOT and isogram in this case ‘happy’, it prints out the else-statement which states that the word is indeed an isogram (even though happy isn’t an isogram). However, it also points out the letter in the word that’s repeated which in this case is the letter ‘p’ in ‘happy’.

  2. when i input a word that’s an isogram like ‘cake’, it says it’s an isogram (which is good) but it says it multiple times instead of once…

i think it’s something to do with the nested ‘for loops’, so maybe the ‘if’ and the ‘else’ console statements are printing out for each character within the word instead of the word as a whole? for example for ‘happy’ i’m presuming this is what it’s doing:

h ‘happy’ is an isogram //first loop
h ‘happy’ is an isogram //second loop
a ‘happy’ is an isogram //first loop
a ‘happy’ is an isogram //second loop
p ‘happy’ is an isogram //first loop
p ‘happy’ is an isogram //second loop
p ‘happy’ is an isogram //first loop
p the letter ‘p’ is repeated //second loop
y ‘happy’ is an isogram //first loop
y ‘happy’ is an isogram //second loop

i also tried fixing it by replacing the else-statement with the return keyword but i came across another problem; this time when i input an isogram word it prints both statements whereas with a none-isogram word in works fine.

const isogram = word => {

  for(let i= 0; i< word.length; i++){ 
    for(let j = i+1; j< word.length; j++){
      if(word[i] === word[j]){
        console.log(`the letter '${word[j]}' is repeated`)
      } 
    } 
  }
  return `'${word}' is an isogram`
}

input: console.log(isogram("happy"));
//output: the letter 'p' is repeated
'happy' is an isogram

input: console.log(isogram("cake"))
//output: 'cake' is an isogram

overall i’m confused: why did this only start happening once i added the ‘else’ statement? what’s the logic behind this? how can i fix it so that the console statements are only printed once? also how could i efficiently use the return keyword here?

i simply want the console to print “the letter ‘ ‘ is repeated” when it’s NOT and isogram
and to print “‘word’ is an isogram” if the the word is an isogram.

Why does changing the x and y variables of ctx.fillRect(x, y, 100, 100); not change the position of the square?

When I click the arrow keys (37, 38, 39, and 40) the variables of x and y change yet the position of the square given by ctx.fillRect(x, y, 100, 100); does not change. How come? And is there any solution?

<!DOCTYPE html>
<html>
<body>

<canvas id="canvasSpace" width="1460" height="710" style="border:2px solid #000000;"></canvas>

    <script>
        const canvas = document.getElementById("canvasSpace");
        const ctx = canvas.getContext("2d");
        let x = 735, y = 360
        ctx.fillRect(x, y, 100, 100);

        function moveLeft() {x -= 10;}
        function moveUp() {y += 10;}
        function moveRight() {x += 10;}
        function moveDown() {y -= 10;}

        function log() {
        alert("x = " + x)
        alert("y = " + y)
        }

        document.addEventListener('keydown', function(event) {
            if (event.keyCode == 37) {moveLeft();}
            if (event.keyCode == 38) {moveUp();}
            if (event.keyCode == 39) {moveRight();}
            if (event.keyCode == 40) {moveDown();}
            if (event.keyCode == 13) {log();}
        });
    </script>

</body>
</html>

I added the log function to trigger when the enter key (13) was pressed to make sure the variables change. Yet this doesn’t appear to be the problem as the variables do change.

Highlighting specified text with embedded link with Chrome Extension [duplicate]

Here is my content.js which has a function that highlights specified text.

function isElementVisible(element) {
    const style = window.getComputedStyle(element);
    return style.display !== 'none' && style.visibility !== 'hidden';
  }

  function highlightLetter(node, targetLetter, highlightColor, tooltipContent) {
    if (node.nodeType === Node.TEXT_NODE && isElementVisible(node.parentElement)) {
      const textContent = node.textContent;
  
      // Match targetLetter only if it is the first or last character of a word
      const pattern = new RegExp(`\b${targetLetter}|${targetLetter}\b`, 'gi');
  
      const newContent = textContent.replace(pattern, match => `<span class="tooltip"><mark style="background-color: ${highlightColor}">${match}</mark><span class="tooltiptext">${tooltipContent}</span></span>`);
  
      if (newContent !== textContent) {
        const newNode = document.createElement('span');
        newNode.innerHTML = newContent;
        node.replaceWith(newNode);
      }
    } else if (node.nodeType === Node.ELEMENT_NODE && isElementVisible(node)) {
      node.childNodes.forEach(childNode => highlightLetter(childNode, targetLetter, highlightColor, tooltipContent));
    }
  }

Here are the other files for a minimal reproducible example.
Here is my manifest.json

{
    "manifest_version": 3,
    "name": "Text Highlighter",
    "version": "1.0",
    "description": "Highlight text in a web page.",
    "permissions": [
      "activeTab"
    ],
    "background": {
        "service_worker": "background.js"
      },
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "css": ["styles.css"],
        "js": ["content.js"]
      }
    ]
  }

Here is my styles.css

.tooltip {
    position: relative;
    display: inline-block;
    cursor: pointer;
  }

  /* Hide the tooltip by default */
  .tooltip .tooltiptext {
    visibility: hidden;
    width: 120px;
    background-color: #333;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 5px;
    position: absolute;
    z-index: 1;
    bottom: 125%;
    left: 50%;
    margin-left: -60px;
    opacity: 0;
    transition: opacity 0.3s;
  }

  /* Display the tooltip when hovering over the parent span */
  .tooltip:hover .tooltiptext {
    visibility: visible;
    opacity: 1;
  }

I tried to highlight this part of the html, as you can see it has a link embedded within the text. (link to actual page: https://www.cnn.com/2023/12/31/politics/donald-trump-2024-voter-turnout/index.html):
The former president leads the current president in more than his fair share of polls of registered voters, including in a number of <a href="https://www.nytimes.com/2023/11/05/us/politics/biden-trump-2024-poll.html" target="_blank">key swing states</a>

I called the function in content.js
highlightLetter(document.body, 'The former president leads the current president in more than his fair share of polls of registered voters, including in a number of key swing states.', 'red', '[insert tooltip content]');

but it did not highlight anything, I’m thinking its because it extended across multiple nodes because of the embedded link. How can I make this work?

How to create an upsell on the thank you page?

my question is, how do I create an upsell page and link it to a button? For example, a visitor visits my site and makes a purchase, so on the thank you page, I would like another offer to be presented to them. Or after a visitor has subscribed to my newsletter, I want an offer to be presented to them immediately.How do I do the linking thing on the html?

Thank you.

I searched almost everywhere but couldn’t get what I want to know

JS: the text does not automatically color when I open the html file. Problem starting the function

I have problems with the javascript script to color the text. It works correctly, but the text only colors if you click on the panel and press the “space” button on the PC keyboard. If you press any other key (even Enter), the text does not color.

enter image description here

I would like the script to activate automatically as soon as I open the html file, so that the text is automatically colored as soon as I open the file.

In the html i tried using the function as both onchange and oninput. While in the js file i call the changeColor() function after creating it, with the aim of executing it automatically as soon as you open the file, but it doesn’t work. Sorry for the problem, but i’m new. How can i solve it?

index.html

  <div id="editor" contenteditable="true" oninput="showPreview();" onchange="changeColor();">&lt;h1>This is a Heading&lt;/h1>
    &lt;p>This is a paragraph.&lt;/p>
  </div>
    
    <h3>PREVIEW</h3>
    <div class="preview-area">
      <iframe id="preview-window"></iframe>
    </div>

style.css

#editor {
  width: 400px;
  height: 100px;
  padding: 10px;
  background-color: #444;
  color: white;
  font-size: 14px;
  font-family: monospace;
  white-space: pre;
}
.statement {
  color: orange;
}

javascript.js

// CHANGE COLOR TEXT
function changeColor() {

var keywords = ["DIV", "DIV", "H1", "H1", "P", "P", "HELLO", "<", ">", "/"];
// Keyup event
document.querySelector("#editor").addEventListener("keyup", (e) => {
    // Space key pressed
    if (e.keyCode == 32) {
    var newHTML = "";
    // Loop through words
    str = e.target.innerText;
    (chunks = str
        .split(new RegExp(keywords.map((w) => `(${w})`).join("|"), "i"))
        .filter(Boolean)),
        (markup = chunks.reduce((acc, chunk) => {
        acc += keywords.includes(chunk.toUpperCase())
            ? `<span class="statement">${chunk}</span>`
            : `<span class='other'>${chunk}</span>`;
        return acc;
        }, ""));
    e.target.innerHTML = markup;

    // Set cursor postion to end of text
    //    document.querySelector('#editor').focus()
    var child = e.target.children;
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(child[child.length - 1], 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    this.focus();
    }
})
}
    
changeColor()


//PREVIEW
function showPreview() {
    var editor = document.getElementById("editor").innerText;
  
    // var cssCode =
    //  "<style>" + document.getElementById("cssCode").value + "</style>";
    // var jsCode =
    //  "<scri" + "pt>" + document.getElementById("jsCode").value + "</scri" + "pt>";
    
    var frame = document.getElementById("preview-window").contentWindow.document;
    document.getElementById("preview-window").srcdoc = editor;
    frame.open();
    //frame.write(htmlCode + cssCode + jsCode);
    frame.write(editor);
    frame.close();
  }
  
  showPreview()