React: trigger an event or value outside the root component

Somebody could help me with this idea? I don’t know if it were possible or should I use any library or skill.

Component (This is usually and common)

import React, { useState } from "react";

export default function App() {
  const [anyVal, setAnyVal] = useState(0);

  return (
    <div className="App">
      <h1>Any Value: {anyVal}</h1>
      <button onClick={() => setAnyVal(anyVal + 1)}>Change value</button>
    </div>
  );
}

Connection HTML + React Dom (This is usually and common)

import { StrictMode } from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);

Here the part that I don’t know if it were possible

  <body>
    <div id="root" onanyvaluechanged="externalFn(v)"></div>
    <script>
      function externalFn(newValue) {
        alert("I've detected the change:" + newValue);
      }
    </script>
  </body>

how do i over put something in css?

I am creating a modal and I need to place the modal above

let buttonOpen = document.querySelector(".button-open");
let buttonClose = document.querySelector(".button-close");
let modal = document.querySelector(".modal");

buttonOpen.addEventListener("click", () => {
  modal.classList.add("show-modal");
});

buttonClose.addEventListener("click", () => {
  modal.classList.remove("show-modal");
});
body {
  padding: 0;
  margin: 0;
}


/* for open the modal*/

#container {
  z-index: -1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.modal {
  display: none;
  width: 100px;
  height: 100px;
  background-color: aqua;
}

.show-modal {
  display: block;
  z-index: 1;
}
<!-- for open the modal -->
<div id="container">
  <button class="button-open">Open Modal</button>
</div>

<div class="modal">
  <div class="modal-content">
    <h3>Title a modal</h3>
    <button class="button-close">Close Modal</button>
  </div>
</div>

photo the result:

Image

and I want the box to be on top of the content
so that it is not below the content but above it, as if it were a layer above my real page content

how do i change the .innerHTML of a html page after a link has been clicked on a different html page?

i have a problem i am trying to solve. i am trying to recreate the music video page (page 1) of Capital dreams pictures here is the page. the issue have now is that, when you click on the play button, it takes you to a different video page (page 2) corresponding to the link clicked here is the link for that. i don’t want to single handedly code that page (page 2) for each of the link on the music video page (page 1). is there a way i can change the content of (page 2) when i click the play button link on (page 1).

here is the code for (Page 1). N.B i render the images using javascript

<body class="body">
    <header>
        <p>your logo</p>
        <nav class="navbar">
            <ul class="nav-menu">
                <li class="nav-item"><a href="video.html" class="nav-link">Home</a></li>
                <li class="nav-item"><a href="musicvid.html" class="nav-link">Music Videos</a></li>
                <li class="nav-item"><a href="film.html" class="nav-link">Film</a></li>
                <li class="nav-item"><a href="showreels.html" class="nav-link">Show Reels</a></li>
                <li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li>
            </ul>
        </nav>
        <div class="burger">
            <div class="line1"></div>
            <div class="line2"></div>
            <div class="line3"></div>
        </div>
    </header>
    <h3>
        <p>music videos</p>
    </h3>
    <main>
        <section  class="dera">
            <!--------------------render images here hopefully -------------->
        </section>
    </main>
    
    <footer>
        <p>
            Copyright Simple <small>2021 - </small>
        <small id="demo"> </small>
        </p>
    </footer>
    <script>
        const d = new Date ();
        document.getElementById("demo").innerHTML = d.getFullYear();
    </script>
    <script src="array.js"></script>
    <script src="video.js"></script>
    </body>

here is the html for (page 2)

<body>
    <header>
        <p>your logo</p>
        <nav class="navbar">
            <ul class="nav-menu">
                <li class="nav-item"><a href="video.html" class="nav-link">Home</a></li>
                <li class="nav-item"><a href="musicvid.html" class="nav-link">Music Videos</a></li>
                <li class="nav-item"><a href="film.html" class="nav-link">Film</a></li>
                <li class="nav-item"><a href="showreels.html" class="nav-link">Show Reels</a></li>
                <li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li>
            </ul>
        </nav>
        <div class="burger">
            <div class="line1"></div>
            <div class="line2"></div>
            <div class="line3"></div>
        </div>
    </header>
    <h3>
        <p>video name here</p>
    </h3>

    <main>
    <div class="container">
        <div class="videocontainer">
            <iframe width="700" height="700" 
            src="https://www.youtube.com/embed/OFKBep95lb4" title="YouTube video player"
            frameborder="0" 
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowfullscreen>
            </iframe>
        </div>

        <div class="cat-container">
            <div class="cart-contain">
                <div class="category">
                    <p><b>category</b>: <span>Music Videos</span></p>
                </div>
                <div class="date">
                    <p><b>date</b>: <span>December 31, 2020</span></p>
                </div>
            </div>
        </div>
    </div>
    </main>
    <section>
        <div class="join">
            <p>previous</p>
            <i class="fab fa-instagram"></i>
            <p>next</p>
        </div>
    </section>
    <footer>
        <p>
            Copyright Simple <small>2021 - </small>
            <small id="demo"> </small>
        </p>
        <a href="music-page.html"><i class="fas fa-play"></i></a>
    </footer>
    <script>
        const d = new Date();
        document.getElementById("demo").innerHTML = d.getFullYear();
    </script>
    <script src="array.js"></script>
    <script src="video.js"></script>

the array

 const images = [
    {
        id: 0,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 1,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 2,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 3,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 4,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 5,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 6,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 7,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 8,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 9,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 10,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 11,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 12,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 13,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 14,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 15,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 16,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 17,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },
]

const images1 = [
    {
        id: 0,
        chidera: "https://www.youtube.com/embed/OFKBep95lb4",
    },

    {
        id: 1,
        chidera: "https://www.youtube.com/embed/JqFrYYIKl_4",
    },

    {
        id: 2,
        chidera: "https://www.youtube.com/embed/OFKBep95lb4"
    },

]

the javascript

// select elements
    const burger =  document.querySelector(".burger");
    const navMenu = document.querySelector(".nav-menu");
    const navLink = document.querySelectorAll(".nav-link")

    burger.addEventListener("click",   function () {
   //toggles the burger
    burger.classList.toggle("is-active");

   //toggles the nav menu
    navMenu.classList.toggle("active");
});
    //removes well, you should know
    navLink.forEach(n =>  n.addEventListener("click", function () {
  burger.classList.remove("is-active");
  navMenu.classList.remove("active");
}))

//wahala dey to render images like this. somebody save me!!!!!!!!!
//this actually worked
    const dera = document.querySelector(".dera");
    const videoContainer = document.querySelector(".videocontainer");

    function renderImages() {
    images.forEach((image) => {
    dera.innerHTML += `<div>
                <!--------render images   here hopefully -->
                <img  src="${image.imgsrc}" alt="">
                <p>${image.videoName}</p>
                <samp> Music Videos </samp>
                <a href="${image.href}" ><i class="fas fa-play fa-3x"></i></a>
            </div>
            `
  })
}
    renderImages();

    //when users click on the play button,
    //i want to change the .innerHTML of the music video page :)
    //for music page thing
    //this is a massive fail tho
    console.log(videoContainer)
    const playButton = document.getElementsByTagName("i");
    const arr = [...playButton];
    console.log(arr)
    arr.forEach((button) => {
  button.addEventListener("click",  function () {
     images1.forEach((_thing) => {
      if (image.id === _thing.id) {
        videoContainer.innerHTML += `
            <iframe width="700"  height="700" 
            src="${_thing.chidera}" title="YouTube video player"
            frameborder="0" 
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowfullscreen>
            </iframe>
    `
      }
      else {
        alert('jdhcodshdioshdioES')
      }
    })
  })
  });

please, how do i go about it? Thank you 🙂

adding parameter from html form to jquery string

I am trying to add to the below async call in javascript which sends parameter q=<query>, the second parameter l=<lquery>, but I don’t see it sent out.

var searchbox = $('input#search');
var langquery = $('input#fav_language');
var timer = 0;

// Executes the search function 250 milliseconds after user stops typing
searchbox.keyup(function () {
  clearTimeout(timer);
  timer = setTimeout(search, 250);
});

async function search() {
  // Clear results before searching
  noresults.hide();
  resultdiv.empty();
  loadingdiv.show();
  // Get the query from the user 
  let query = searchbox.val();
  // Only run a query if the string contains at least three characters
  if (query.length > 2) {
    let lquery = langquery.val();   
    // Make the HTTP request with the query as a parameter and wait for the JSON results
    let response = await $.get(apigatewayendpoint, { q: query, l: lquery, size: 25 }, 'json');

I can’t fix Heroku “Could not find a required file, Name: index.html” error

I am new to Heroku. I tried deleting .gitignore and rearranging my files around, but it still gives me that error. I have a program with React.js as the front end and Node.js as the backend. I need this to deploy to Heroku. The image below shows the error I get.

Image of the error I get

In my Node.js code, I tried specifying where Heroku should in “client” folder for the “index.html” file. This is my node.js code:

//code based off of:
// https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9

const express = require('express');
const request = require('request');

const app = express();
const apiKey = 'api-key-here';

// Have Node serve the files for our built React app
app.use(express.static(path.resolve(__dirname, '../client/build')));

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});



app.get('/getCoinInfo', (req, res) => {
  console.log('The request has been received!!')
  request(
    { url: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=' + apiKey},
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }
      res.json(JSON.parse(body));
    }
  )
});

// All other GET requests not handled before will return our React app
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../client/build', 'index.html'));
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));

Also here is my file structure.

enter image description here

What are your suggestions to fix this problem?

How to deselect a checkbox using two condition/if statements (one a dropdown select and one a radio)

I’m trying to set this condition in a form:

If the #Size (from a dropdown selection) = ‘extra-cab’ AND a radio select button called ‘canopy-14x-select’ (from a group of radio buttons called ‘Canopy’) are both selected, then the checkbox with a class called .rack-kit is deselected.

I’m not sure how to nest these into each other, I’ve attempted it below but it isn’t working.

Any help would be much appreciated.

$('#Size').on('change', function() {
         if (this.value == 'extra-cab') {
                if ($(this).attr("id") == "canopy-14x-select") {
                    $('.rack-kit input[type="checkbox"]:checked').prop('checked', false).trigger('change');
                }
            }

Thank you in advance 🙂

Escaping words in between quotes [closed]

I am working on a small project using yandex translate api for school.
My code has an input field where you type a phrase which will be translated into Russian or other language.
There are words that I would like to escape from translation by adding them in double-quotes.
There are thousands of words that I would like to escape and adding them into an object or array isn’t an option. What I am looking for is to send the phrase to yandex including words in double-quotes and upon return of translated text, to have them words which are still in double-quotes replaced with original words.
I would be easy if in that sentence or phrase would be only one word in double-quotes but there might be more than 5 or 10.
I don’t know if it makes any sense but here’s a small example.

input string: This is Anton, he is my best "friend". We met at a local "club" where we played some "snooker".

output string: Это Антон, он мой лучший "friend". Мы встретились в местном «club», где играли в «snooker».

Apologies for not adding any code as I do not have access to my code at the moment.

JavaScript. Google Chrome Extension. How do I save the page state with javascript execution results and restore it later?

I’m developing a chrome extension for YouTube.
The extension writes alternative subtitles with different behavior.
The subtitle file is taken from YouTube by the link.
In order for me to be able to show subtitles by the time the video starts playing, I have to download the subtitle files before the video loads.
At low Internet speed, JSON files of subtitles are loaded simultaneously with the YouTube page for a very long time.
I use this approach.
To prevent my extension from competing with YouTube scripts, my extension:

  • calls window.stop() at the very beginning of page loading.
  • After stopping the download, I download the files I need.
  • Then the extension reloads the page.

But I would not want to reload the page if there are entries in window.history.
Of course, I would just like to block the page rendering thread for example by window.renderPause() and then resume by window.renderResume(). I would not use window.stop(). But JavaScript does not provide such an opportunity.
How do I save the page state with JavaScript execution results and restore it later?
This code doesn’t work for youtube. JavaScript of YouTube does not start.

let clonedHtml = document.documentElement.cloneNode(true);
let clonedWindow = Object.assign({}, window);
document.documentElement.innerHTML = "";
window = clonedWindow;
document.replaceChild(clonedHtml, document.documentElement);

I can not use window.history.back() or window.history.forward() because window.stop() does not allow to load a page.

window.onscroll from webpage not working on react-native-webview

I’m currently using https://github.com/react-native-webview/react-native-webview for a website to load within the app. The app is essentially a glorified website so everything in implemented on webapp.

Anyway, I’ve bunch of stylings changes based on window.onscroll function in webapp.
Obviously they work just fine when loaded from browser, whether it be mobile or desktop.

My problem is the react native web view doesn’t respond to any of those functions from window.onscroll.
I tried to do something like injectJavaScript inside but there are many on scroll functions and that will basically mean i am replicating same thing from web to ReactNative just to inject JS. Even then, some variables are dynamic so injectJavaScript essentioally woudln’t work unless that injected JS triggers on scroll function somehow.

How can I solve this issue?

TLDR; window.onscroll function on webview is not being triggered when loaded from webview.

How do I group muiltiple record in array to object in Javascript? [duplicate]

hope everyone doing well!

Is there anyone in here who can help how to group the below array to object sort by the second item of each record in Javascript?

i.e: "{first},{second},{third},{fourth}" -> “bob,627,1973,Amsterdam”

Take for example this array:

[
  'bob,627,1973,amsterdam',
  'alice,387,885,bangkok',
  'alice,355,1029,barcelona',
  'alice,587,402,bangkok',
  'charlie,973,830,barcelona',
  'alice,932,86,bangkok',
  'bob,188,989,amsterdam'
];

expected result:

{
  alex: [
    [ 355, '1029', 'barcelona' ],
    [ 387, '885', 'bangkok' ],
    [ 587, '402', 'bangkok' ],
    [ 932, '86', 'bangkok' ],
  ],
  bob: [ 
    [ 188, '989', 'amsterdam' ],
    [ 627, '1973', 'amsterdam' ],
  ],
  charlie: [
    [ 973, '830', 'barcelona' ],
  ],
}

Shopify adding two products to cart with one checkout button

So I have a bundle I created to add two products to cart once those products are selected. I want them to be added to cart at the same time. I’m currently only getting one product being added, with the name=”id”. How can I create the values in input for both to checkout?

Here’s my form:

<form method="post" action="/cart/add" class="col-button ">
                    <input id="idPrice" type="hidden" name="id" value="" />
                    <input id="designPrice" type="hidden" name="id" value="" />
                    <input min="1" max="2" type="hidden" id="quantity" name="quantity" />
                      <button name="checkout"  {%unless product.available %}style='margin-bottom:20px;'{% endunless %}type="{% if settings.cart_action == 'ajax' %}button{% else %}submit{% endif %}" name="add" class="collection-add-to-cart {% if settings.cart_action == 'ajax' %} ajax-submit {% endif %}action_button add_to_cart {% if show_payment_button %} action_button--secondary {% endif %} {% if product.available == false %}disabled{% endif %}" data-label={{ add_to_cart_label | json }}>
                        {{ 'layout.general.checkout' | t }}
                      </button>
                 </form>

Thanks in advance!

How to solve localstorage exeeded the quota error in Reactjs

Regarding redux-localstorage-simple in React.js/Typescript, exceeded the quota error occured when trying to store a huge amount of data(It’s actually an array of objects related to tilemap coordinate data).
I’m sure it is because the local storage limit for a certain host has been exceeded.

Reloading the page initializes the redux storage, so I had to use the redux-localstorage-simple library to avoid data loss.

In this case, which alternative should I use to avoid exceeded the quota error?

How can I get a random item from multiple arrays based on a checkbox?

I want to only show the text from the arrays that are selected with the checkboxes (so, if i only want txt and ran, it only shows options from those arrays)

HTML:

<input type="checkbox"> txt<br>
<input type="checkbox"> test<br>
<input type="checkbox"> ran
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
sum text lol
</p>

Javascript:

 function myFunc() {
     let txt = ["txt1", "txt2", "txt3"];
     let test = ["test1", "test2", "test3"];
     let ran = ["ran1", "ran2", "ran3"];

     let tst = txt[Math.floor(Math.random() * txt.length)] + "<br><br><br>" + test[Math.floor(Math.random() * test.length)] + "<br><br><br>" + ran[Math.floor(Math.random() * ran.length)];
     document.getElementById("tst").innerHTML = tst;
 }

Code: https://jsfiddle.net/RoseLovesGreene/ps17u8yd/6/

I’d also like to be able to show it in a random order so that each array doesn’t have it’s own line.

Refreshing the browser and/or relaunching “npm-start” resets to old CSS

I started building a project where in my src folder I have subfolders, such as Header, Hero, Footer.

Inside each of the subfolders, I have two files, eg.: Hero.js and herostyle.css In Hero.js the stylesheet is imported by the following method:

import './headerstyle.css';

As I start editing the css file, it responds correctly, and the design is changing accordingly, so I am not sure if it’s a linking problem.

When I refresh the browser, the CSS breaks, and the way I get the design back, is by having to go back to the Hero.js file:

First – removing the import ‘./headerstyle.css’; codesnippet
Second – Doing a quicksave
Third – Putting the same codesnippet import ‘./headerstyle.css’; back in Hero.js
Fourth – Saving again, and then I get my design back.

I tried resetting the browser’s cache, disabling the cache in the developer’s console, none of that seems to be working. It is really frustrating, please help.

Thank you

For each await push into global variable returns undefined [duplicate]

My code below loops through a zip file called a global variable zipArray, then adds the file contents into zipFileArray. However, when I console.log(zipFileArray) it returns undefined:

        await zip.forEach(async (relativePath: any, file: any) => {
            zipArray.push(file)
        })
        console.log(zipArray)
        var zipFileArray: any[] = []
        await zipArray.forEach(async (file: any) => {
           console.log("reached")
            const file2 = await zip.file(file.name).async("string")
            zipFileArray.push(file2)
        })
        console.log("zipFileArray:" + zipFileArray)