JavaScript not working properly on Chrome on one PC, but working flawless on another PC on both Chrome and Firefox

I’m having a weird problem. I’ve been doing some landing page and adding a little bit of JavaScript to it. I have been working on my laptop and everything was working flawless. I’ve tried testing the page on the bigger screen on my PC and some things have been broken. For example:

  1. I have done JS that will change the color of the navbar on scroll. Navbar is vertical position and fixed. That is working good on all occasions.
  2. I have added code that will change the color of the text when this scroll happens. That is the thing that is making problem to my code. On my laptop text appears and changes colors, but on PC on Chrome and Brave browsers text just doesn’t change color to green!

JavaScript code:

var myNav = document.getElementById("nav");
var navItem = document.getElementsByClassName("nav-item");
var contactNavItem = document.querySelector(".contact-nav-item");

window.onscroll = function () {
 if (
   document.body.scrollTop >= 400 ||
   document.documentElement.scrollTop >= 400
 ) {
   myNav.classList.add("scroll");

   for (let i = 0; i < navItem.length; i++) {
     navItem[i].classList.add("nav-item-scroll");
   }

   contactNavItem.style.display = "block";
 } else {
   myNav.classList.remove("scroll");
   for (let i = 0; i < navItem.length; i++) {
     navItem[i].classList.remove("nav-item-scroll");
   }

   contactNavItem.style.display = "none";
 }
};

“Scroll” is the class that changes color of the navbar. “nav-item-scroll” is supposed to change the color of the text inside of the navbar but on certain occasions it fails to do so.

What am I doing wrong?

React dynamic list of React-Draft-Wysiwyg text boxes not updating correctly after remove

Codesandbox link: https://codesandbox.io/s/tender-meadow-un6ny7?file=/src/index.js

I’m creating a basic application where you can dynamically add in text boxes via the react-draft-wysiwyg library.

  return (
    <div className="editor">
      <Editor
        //Update and show text box content
        editorState={editorState}
        onEditorStateChange={(editorState) => {
          let html = stateToHTML(editorState.getCurrentContent());
          console.log(html);
          setHtml(html);
          props.setContent(editorId, html, editorState);
          setEditorState(editorState);
        }}
        //Display toolbar on top
        toolbar={{
          inline: { inDropdown: true },
          list: { inDropdown: true },
          textAlign: { inDropdown: true },
          link: { inDropdown: true },
          history: { inDropdown: true },
        }}
      />
    </div>
  );
};

The textboxes are stored and updated through a React state hook. One controls the actual rendered state of each textbox (editorState) and another stores the raw html of each textbox’s contents (html). The state hooks already have defined behavior for adding, removing, and editing.

const EditorContent = (props) => {
  const [editorState, setEditorState] = useState(props.content);
  const [html, setHtml] = useState("");

  useEffect(() => {
    console.log("loaded number " + props.id);
  });

function App() {
  //Declaration of editorList array and setList setter
  const [editorList, setEditorList] = useState([
    { id: 0, html: "", content: EditorState.createEmpty() },
  ]);
  const [numberofEditors, setNumberOfEditors] = useState(0);

  //Lets you view editorList content in inspect tab
  console.log(editorList);

  //Used to find specific instance, not used in current code
  //Refer to video, forgot what it's used for

  const handleServiceChange = (e, index) => {
    const { name, value } = e.target;
    console.log(name, value);
    const list = [...editorList];
    list[index][name] = value;
    //setEditorList(list);
  };

  //Handles remove function
  const handleEditorRemove = (id) => {
    console.log("Remove id " + id);
    // remove editor with designated id
    let list = editorList.filter((editor) => {
      return editor.id !== id;
    });
    console.log("Updated List: " + list);
    setEditorList(list);
  };

  const handleEditorAdd = (id) => {
    console.log(id);
    setEditorList([
      ...editorList,
      { id: id, html: "", content: EditorState.createEmpty() },
    ]);
    setNumberOfEditors(numberofEditors + 1);
  };

  const setEditorContent = (id, html, editorState) => {
    console.log(id, html);
    // deep copy array
    let editorsCopy = [];
    for (let editor of editorList) {
      editorsCopy.push(editor);
    }
    const index = editorsCopy.findIndex((editor) => {
      return editor.id === id;
    });
    editorsCopy[index].html = html;
    editorsCopy[index].content = editorState;

    setEditorList(editorsCopy);
  };

Each text box is also rendered with two buttons, one that lets you add another box, another to delete that specific component.

  return (
    <form className="App" autoComplete="off">
      <div className="form-field">
        <label htmlFor="editor">Editor(s)</label>
        {editorList.map((editor, index) => (
          <div key={index} className="services">
            <div className="first-division">
              <EditorContent id={editor.id} setContent={setEditorContent} />
              {editorList.length - 1 === index && editorList.length < 4 && (
                <button
                  type="button"
                  onClick={() => {
                    handleEditorAdd(numberofEditors + 1);
                  }}
                  className="add-btn"
                >
                  <span>Add an Editor</span>
                </button>
              )}
            </div>
            <div className="second-division">
              {editorList.length !== 1 && (
                <button
                  type="button"
                  onClick={() => {
                    handleEditorRemove(editor.id);
                  }}
                  className="remove-btn"
                >
                  <span>Remove</span>
                </button>
              )}
            </div>
          </div>
        ))}
      </div>
      <div className="output">
        <h2>Output</h2>
        {editorList &&
          editorList.map((editor, index) => (
            <ul key={index}>{editor.service && <li>{editor.content}</li>}</ul>
          ))}
      </div>
    </form>
  );
}

Adding new textboxes and updating the stored html works perfectly. However, when I attempt to remove a specific text box, no matter which remove button I select, the last row is always removed. I attempted to add id keys for each textbox, and splicing, but nothing seems to properly render the changes, despite the HTML array displaying the correct text.

Am I updating the state incorrectly? Or just rendering incorrectly? Any input would be appreciated.

How to make the next 3 images appear in carousel?

I am trying to make my slider slide to the next 3 slides in my carousel.How it should work is the first 3 images should show, and then when you click the next arrow the next 3 images should show.

I am not sure where I am going wrong. Basically the opacity of the last 3 pictures should be 0 until you click next then the opacity becomes 1 for the next 3 pictures.

This is what I have done so far:

HTML:

 <section>
        <div class="immigration-service">
          <h1>Cross-border financial and immigration services</h1>
          <div class="carousel">
            <ul>
              <li>
                <img
                  class="slide"
                  src="images/British citizenship and Immigration.jpg"
                  alt="British citizenship and Immigration Image"
                />
              </li>
              <li>
                <img
                  class="slide"
                  src="images/Australian Migration.jpg"
                  alt="Australian Migration Image"
                />
              </li>
              <li>
                <img
                  class="slide"
                  src="images/Citizenship by investment.jpg"
                  alt="Citizenship by investment Image"
                />
              </li>
              <li>
                <img
                  class="slide-2"
                  src="images/British citizenship and Immigration.jpg"
                  alt="British citizenship and Immigration Image"
                />
              </li>
              <li>
                <img
                  class="slide-2"
                  src="images/Australian Migration.jpg"
                  alt="Australian Migration Image"
                />
              </li>
              <li>
                <img
                  class="slide-2"
                  src="images/Citizenship by investment.jpg"
                  alt="Citizenship by investment Image"
                />
              </li>
            </ul>

            <button class="button prev" data-carousel-button="prev">
              &#60;
            </button>
            <button class="button next" data-carousel-button="next">
              &#62;
            </button>
          </div>
        </div>
      </section>
        
  

CSS:

.immigration-service
{
  margin-top: 34vh;
}

.immigration-service h1
{
  padding-top: 113px;
  text-align: center;
}

.immigration-service ul 
{
  display: flex;
  margin:0;
  padding:0;
  overflow:hidden;
}

.immigration-service li
{
  display: block;
 list-style-type: none;
}

.button {
  display: flex; 
  font-size: 60px;
  align-items: center; justify-content: center;
  color: #115577;
  width: 30px; 
  height: 50px;
  border: 0px;
}
button.prev {
  position: absolute; 
  left: 0;  
  top: 106vw;
}
button.next {
  position: absolute; 
  right: 55vw;
  top: 106vw;

}

Javascript:

let images = document.querySelectorAll('ul li');
let index = 0;
window.show = function(increase) {
  index = index + increase;
  index = Math.min(Math.max(index,0), images.length-1);
  images[index].scrollIntoView({behavior: 'smooth'});
}

www-form-urlencoded string parameter not recognized in API communication

It is difficult to give a reproducible exemple, I summarise here the main components:

We have a front-end/back-end system on an ubuntu 18.04 server.
The client side is a web plateform where users can create a project with characteristics (like name, date…).
The front-end is coded in javascript, with a mongoDB behind, and communicates with a flask API. The web link is managed by a dedicated web proxy.

We face a very puzzling behavior we don’t understand after days of debugging:

The front-end sends a www-form-urlencoded string parameter X to the API. This parameter is optional and can be empty.

We check that this parameter is in the request body

let X = req.body.X? req.body.X : "";

If the parameter is set, the requests succeed.
However, if the parameter is omitted a weird behavior happens in the API :

  • The HTTP request is received, we can read a few key properties such as requested URL, headers and such
  • When accessing the property request.form, a dict containing the parameters as key-value pairs, the API freezes.
  • After a short time the requests timesout frontEnd side
  • After the timeout, Flask resolves the request with a 400 BAD REQUEST code without raising any exception or calling a set error handler for the 400 code.

How to send my content to a global IPFS node?

To use IPFS in NodeJS, I require ipfs module. To connect a IPFS node I try:

const IPFS=require("ipfs");
const node= await IPFS.create();

When I run my code in PowerShell, The below messages emerge:

Swarm listening on /ip4/192.168.1.100/tcp/4002/p2p/12D3KooWCGvmbySrpdCVKACJPjZeeUiMR6gSQffa7W3gWZLSGBxp
Swarm listening on /ip4/192.168.88.1/tcp/4002/p2p/12D3KooWCGvmbySrpdCVKACJPjZeeUiMR6gSQffa7W3gWZLSGBxp
Swarm listening on /ip4/192.168.49.1/tcp/4002/p2p/12D3KooWCGvmbySrpdCVKACJPjZeeUiMR6gSQffa7W3gWZLSGBxp
Swarm listening on /ip4/127.0.0.1/tcp/4002/p2p/12D3KooWCGvmbySrpdCVKACJPjZeeUiMR6gSQffa7W3gWZLSGBxp
Swarm listening on /ip4/127.0.0.1/tcp/4003/ws/p2p/12D3KooWCGvmbySrpdCVKACJPjZeeUiMR6gSQffa7W3gWZLSGBxp

I think the above message is mentioning that I connected to a local IPFS node. If my thought is true, It can be because of IPFS.create(). So, I should put a gateway as an argument to that to connecting a global node. I saw some IPFS public gateways on Public Gateway Checker but I don’t know how to put one sample in IPFS.create();

Please giude me:

  1. Am I right about the messages on PowerShell?

  2. How to use a global IPFS gateway in my code?

My whole NodeJS code:

const IPFS=require("ipfs");
    async function register(){
        const node=await IPFS.create();
        node.add("Main Content!").then(function(ipfsHash){console.log(ipfsHash)});
    }

Whole result in PowerShell:

Swarm listening on /ip4/192.168.1.100/tcp/4002/p2p/12D3KooWCGvmbySrpdCVKACJPjZeeUiMR6gSQffa7W3gWZLSGBxp
Swarm listening on /ip4/192.168.88.1/tcp/4002/p2p/12D3KooWCGvmbySrpdCVKACJPjZeeUiMR6gSQffa7W3gWZLSGBxp
Swarm listening on /ip4/192.168.49.1/tcp/4002/p2p/12D3KooWCGvmbySrpdCVKACJPjZeeUiMR6gSQffa7W3gWZLSGBxp
Swarm listening on /ip4/127.0.0.1/tcp/4002/p2p/12D3KooWCGvmbySrpdCVKACJPjZeeUiMR6gSQffa7W3gWZLSGBxp
Swarm listening on /ip4/127.0.0.1/tcp/4003/ws/p2p/12D3KooWCGvmbySrpdCVKACJPjZeeUiMR6gSQffa7W3gWZLSGBxp
{
  path: 'QmUaTPt2Uus46Cgo4YMKze8PpHrCKvZ1YXD2zpffNt8U9S',
  cid: CID(QmUaTPt2Uus46Cgo4YMKze8PpHrCKvZ1YXD2zpffNt8U9S),
  size: 21,
  mode: 420,
  mtime: undefined
}

Thanks a lot!

Here API – boundingBox bounds directly at the markers so that the markers aren’t displayed

I have been searching and looking into the here maps API documentation a lot but I can’t seem to find an answer.

What I am doing is displaying a variable route from point a to point b. When the map is initiated the route is fully visible but the map is zoomed in to match exactly the markers with the routeLine.getBoundingBox() method.

What I want to achieve is a slightly zoomed out view, so that the entire route including the markers are visible. I tried to play around with the zoom value but it doesnt seem to do anything. There is probably a pretty easy solution that I am missing?

This is the script that I included:

<script>


  // Instantiate a map and platform object:
  var platform = new H.service.Platform({
  'apikey': {APIKEY}
  });
  // Retrieve the target element for the map:
  var targetElement = document.getElementById('mapContainer');
  
  // Get the default map types from the platform object:
  var defaultLayers = platform.createDefaultLayers();
  
  // Instantiate the map:
  var map = new H.Map(
  document.getElementById('mapContainer'),
  defaultLayers.vector.normal.map,
  {
  zoom: 10,
  center: { lat: 52.51, lng: 13.4 }
  });

  // Create the default UI:
  var ui = H.ui.UI.createDefault(map, defaultLayers);
  
  // Create the parameters for the routing request:
  var routingParameters = {
  'routingMode': 'fast',
  'transportMode': 'car',
  // The start point of the route:
  'origin': '52.503799,13.4533',
  // The end point of the route:
  'destination': '52.501282,13.41133',
  // Include the route shape in the response
  'return': 'polyline'
  };
  
  // Define a callback function to process the routing response:
  var onResult = function(result) {
  // ensure that at least one route was found
  if (result.routes.length) {
  result.routes[0].sections.forEach((section) => {
  // Create a linestring to use as a point source for the route line
  let linestring = H.geo.LineString.fromFlexiblePolyline(section.polyline);
  
  // Create a polyline to display the route:
  let routeLine = new H.map.Polyline(linestring, {
  style: { strokeColor: 'blue', lineWidth: 5 }
  });
  
  // Create a marker for the start point:
  let startMarker = new H.map.Marker(section.departure.place.location);
  
  // Create a marker for the end point:
  let endMarker = new H.map.Marker(section.arrival.place.location);
  
  // Add the route polyline and the two markers to the map:
  map.addObjects([routeLine, startMarker, endMarker]);
  
  // Set the map's viewport to make the whole route visible:
  map.getViewModel().setLookAtData({bounds: routeLine.getBoundingBox()});
  
  // Add traffic to the layer
  map.addLayer(defaultLayers.vector.normal.traffic);
  
  // Create the default UI:
    var ui = H.ui.UI.createDefault(map, defaultLayers, 'de-DE');
  
  });
  }
  };
  
  // Get an instance of the routing service version 8:
  var router = platform.getRoutingService(null, 8);
  
  // Call calculateRoute() with the routing parameters,
  // the callback and an error callback function (called if a
  // communication error occurs):
  router.calculateRoute(routingParameters, onResult,
  function(error) {
  alert(error.message);
  });
  
  </script>

Function can accept character input and the number of loop

i have some question about logic,but i stuck in this question. i dont understand what this question means

Write a function with the following conditions:

  • Function can accept character input and the number of loop
  • Each of the first characters will be taken out from the string and input into a new string
  • Then every the number of inputs loop take out from the string and input into a new string
  • Do this until the characters in the string empty
  • Return the New Of String

Example:

function solution(string, numberOfLoop)
solution("MISTERALADIN",4) Output: MEAIANLTSRID

function Solution(string, numberOfLoop) {
let newString = string[0];
for(let i=0; i<numberOfLoop; i++){
string = string.subs
for(let j=0; j<string.length; j++){
newString += string[j];
}
}
}

// function Solution (string, numberOfLoop) {
//   // console.log(string)
//   let newString = string[0]

// }

console.log(Solution("MISTERALADIN", 4));

Appending multiple vuejs components from ajax html response

I’m trying to append multiple vuejs components with jquery ajax, but it’s not working.
It all works fine, until response returns more than one component, or component within component.

Here’s the code:

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<div id="app">
</div>

<script type="text/x-template" id="template-1">
    <div>
     <h1>Template 1 {{param}}</h1>
    </div>
</script>

<script type="text/x-template" id="template-2">
    <div>
     <h1>Template 2 {{param}}</h1>
    </div>
</script>


<script>
    Vue.component('template-1', {
         template: '#template-1',
         props: ['param']
       });

       Vue.component('template-2', {
         template: '#template-2',
         props: ['param']
       });

       const vm = new Vue({
           el: '#app'
       });
</script>

<script>

    function loadMore(){
        $.get('/home/test', function (response) {
            var MyComponent = Vue.extend({
                template: response
            });

          
            var compiled = new MyComponent().$mount();
            $('#app').append(compiled.$el);
        });
    }

   loadMore();

</script>

If the following response comes from ajax, it works, and renders one component:

<template-1 param="Test"></template-1>

If the following response returns from ajax, it renders only first component:

<template-1 param="Test"></template-1>
<template-2 param="Test"></template-2>

If the following response returns from ajax, it renders both components:

<div>
    <template-1 param="Test"></template-1>
    <template-2 param="Test"></template-2>
</div>

If the following response returns from ajax, it renders only parent component:

<template-1 param="Test">
    <template-2 param="Test"></template-2>
</template-1>

Is there a way to make this work always, without knowing how many components will be returned from the server?

Spinner is not working with ternary operator

import React, { useEffect, useState } from 'react';
import { Spinner } from 'react-bootstrap';
import Country from '../Country/Country'

const Countries = () => {
    const[countries,setCountries]=useState([])
    const [isLoading,setLoading]=useState(true)
    useEffect(()=>{
        fetch('https://restcountries.com/v3.1/all')
           .then(res=>res.json())
           .then(data=>setCountries(data))
        setLoading(false)

    },[])
    return (
        <div className='container'>
            <div className="row row-cols-lg-4 row-cols-md-2 row-cols-sm-1 row-cols-1 g-2 mt-3">
                {
                    isLoading?<Spinner animation='border'/>:countries.map(country=><Country key={Math.random(1,10)} country={country} />)
                }

            </div>
        </div>
    );
};

export default Countries;

Spinner is working Outside { }.But when I am trying this->

{isLoading?<Spinner animation='border'/>:countries.map(country=><Country key={Math.random(1,10)} country={country} />)}.

It is not working.I want to say It did not show any spinner before data showing

Apply CSS ID via JavaScript

I’m going to apply all of these CSS effects to another image via JavaScript code by selecting images that have that CSS effect.

#grayscale { filter: grayscale(1); }

#sepia { filter: sepia(1); }

#invert { filter: invert(1); }

#blur { filter: blur(2px); }

#saturate { filter: saturate(2); }

#contrast { filter: contrast(2); }

With this code, the number of commands increases and I want to write much shorter:

document.getElementById('#yourId').style.property = new style;

Inside the event

const handleFilter = (e) => { const { target } = e; const { id: filter } = target; // filter: "grayscale" | "sepia" | "invert" | "hue-rotate" | "contrast" | "saturate" | "blur"

};

Links not changed after alphabetically sorting

I have a list that is sorted alphabetically, but links from each li are not changing if I verify the elements links after sorting. Can’t figure out what am I missing.

Any help with explanations would be greatly appreciated.

My code in HTML:

<ul class="row list-unstyled" id="testingList">
  <li class="col-sm-6 col-lg-4 col-xl-3 mb-3 top-box"><a class="top-box__content" href="https://www.example.com/info/1" target="_blank">
      <div class="row no-gutters">
        <div class="col">
          <h3 class="top-box__title">Pink</h3>
        </div>
      </div>
    </a>
  </li>
  <li class="col-sm-6 col-lg-4 col-xl-3 mb-3 top-box"><a class="top-box__content" href="https://www.example.com/info/2" target="_blank">
      <div class="row no-gutters">
        <div class="col">
          <h3 class="top-box__title">White</h3>
        </div>
      </div>
    </a>
  </li>
  <li class="col-sm-6 col-lg-4 col-xl-3 mb-3 top-box"><a class="top-box__content" href="https://www.example.com/info/3" target="_blank">
      <div class="row no-gutters">
        <div class="col">
          <h3 class="top-box__title">Brown</h3>
        </div>
      </div>
    </a>
  </li>
</ul>

My JS code:

let pickList = document.querySelector("#testingList");

let li = pickList.querySelectorAll("a");

resultList = [];

for (let i = 0; i < li.length; i++) {
  resultList.push(li[i].innerHTML);
  console.log(resultList);
}

resultList.sort();

for (let j = 0; j < li.length; j++) {
  li[j].innerHTML = resultList[j];
}

remove “?” from all anchor text

i am trying to remove the query string “?” from all anchor text with javascript

for example, there are many URLs like this

<a href="https://example.com/something/?">my anchor</a>

i just want to remove ? from all anchor text. i tried this but getting the error index of is not a function

    var url = jQuery("a");
    var a = url.indexOf("?");
    var b =  url.substring(a);
    var c = url.replace(b,"");
    url = c;

changing a page with delay and eventListener set to click works regardles of the click

im trying to change an html page with a delay of 3 sec when the user clicks on a specific div in the screen.

document.getElementById("specificDiv").addEventListener("click", setTimeout(document.getElementById("linkToAnotherPage").click(), 3000) )

however the eventListener doesnt work. when the page loads up it automatically clicks on the “linkToAnotherPage” after 3 sec have past since loading the page.

would love if someone could help me understand whats wrong here.

Which is the best way to define the type of dynamic data-attributes in a React component?

I need a React prop to deal with all possible html attributes of an HTML div element part of a React component, but I’m having an issue with Typescript strictness vs React possibilities.

Here the component:

import React from 'react'

type DivAttrs = {
  container?: React.HTMLAttributes<HTMLDivElement>
}

...

<div {...divAttributes?.container}>

And here the prop const provided to the component:

const divAttributes: DivAttrs = {
  container: {
    'aria-describedby': 'test',
    'data-custom-attribute': 'test',
    'data-random-attribute': 'test',
    id: 'test'    
  }
}

The props data-custom-attribute and data-random-attribute give these errors

(property) 'data-custom-attribute': string
Type '{ 'aria-describedby': string; 'data-custom-attribute': string; 'data-random-attribute': string; id: string; }' is not assignable to type 'HTMLAttributes<HTMLDivElement>'.
  Object literal may only specify known properties, and ''data-custom-attribute'' does not exist in type 'HTMLAttributes<HTMLDivElement>'.(2322)

What would be the perfect solution to fix this issue? Thanks a lot