Why doesn’t rootMargin of IntersectionObserver seem to be respected when evaluating a sticky element?

Looking at the IntersectionObserver API, it sounds like you can use rootMargin to specify offsets for the container to coerce the API to fire when an element is either near or some number of pixels inside a target container. But with the below example, it seems to not fire. I’ve set the ‘rootMargin’ to have an 11px top margin, so the sticky element (which sticks 10px from the top) should be partially overlapping, thus causing the observer to report a change in visibility.

This logic works fine if I have top: -1px instead of top: 10px, but from all the documentation I can find, this should work as well. I’ve tried a few variations of margins, negative values, etc to try to make this work, without success, but randomly guessing shouldn’t be the solution.

Any idea what I’m doing wrong?

HTML:

<div class="container">
 <div class="before-content">This content should scroll off the screen</div>
 <div class="sticky">Sticky content</div>
 <div class="after-content">This is some extra content after</div>
</div>

CSS:

* {
  color: #b58900;
}

.container {
  background-color: #002b36;
}

.before-content {
  height: 50px;
}

.sticky {
  height: 30px;
  background-color: #073642;
  position: sticky;
  top: 10px;
}

.after-content {
  height: 200px;
}

JS:

const sticky = document.getElementsByClassName("sticky")[0];

const observer = new IntersectionObserver(
  ([e]) => {
    console.log(e.intersectionRatio)
    const stuck = e.intersectionRatio < 1.0;
    sticky.innerHTML  = "Sticky content (" + String(stuck) + ")"
  }, {
    threshold: [1],
    // This doesn't work; changing the css ".sticky { top : -1 }" does cause the intersect logic
    // to fire and "stuck == true", but according to mdn docs it sounds like setting rootMargin
    // this way should have the same effect.
    rootMargin: '11px 0px 0px 0px',
  }
)


observer.observe(sticky)

JSFiddle Example

Is there any problem by using custom server in nextjs?

I want to use node-cron in nextjs. But, it only needs to initialize at the beginning of the server, and no need for recalling in every render. The one way I found it is by using a custom server. But, if I use the custom server, will it affect performance or is there any other issue with that?

Encoding & Decoding of japanese characters stored in local storage

I was trying to save the name of logged in user in the localstorage of browser.
Check the code below.

Encoding :

localStorage.setItem('currentUser',btoa(JSON.stringify(user.name)))

Decoding :

this.userName = JSON.parse(atob(localStorage.getItem('currentUser')))

Now the problem is that, If there is japanese character in the user.name, Encoding works but, While decoding the name i didnt get the correct text.
Is there any solution for this?

Javascript cant get my value and calculate in html

Im trying to do simple calculation for the fee ,but its doesn’t work ,there’s no error in the code. Did I miss something in the script ?

    <script type="text/javascript">
        var bwm = 7.9;
        var bswk = 14;
        var bsbh = 15;
        var wm = 2;
        var swk = 11;
        var sbh = 12;
        var kilo, overkilo, f;
        var s = document.getElementById('place');
        var place = s.options[s.selectedIndex].value;
        var k = document.getElementById('kilo').value;
        var tot;

        function quote() {
            f = document.getElementById('theform');
            f.reset();

            document.getElementById('calc').onclick = function() {
                if (place == 'swk') {
                    (k * swk) + bswk = tot;

                } else if (place == 'sbh') {
                    (k * sbh) + bsbh = tot;

                } else {
                    (k * wm) + bwm = tot;

                }
                document.getElementById('tot').value = 'RM  ' + parseFloat;
            }

        }
    </script>

    <form id="theform" action="#">
        <div>
            <label for="place">Choose Destination :</label>
            <select id="place" onChange="quote()">
                <option value="swk">Sarawak</option>
                <option value="sbh">Sabah</option>
                <option value="wm">WestMalaysia</option>
            </select>
        </div>
        <div>
            <label for="kilo">Amount of KG :</label>
            <input id="kilo" type="text">
        </div>
        <div>
            <label>Total :</label>
            <input id="tot" type="text" readonly="readonly">
        </div>
        <div>
            <label></label>
            <input id="calc" type="button" value="calculate">
            <input id="r" type="reset" value="clear">
        </div>
    </form>

The clear works fine ,but the calculate button won’t work even i have input the KG and select a option to calculate .

Show product of my form inputs before submiting

I have a form that I would like to show the total before submitting would like to get a realtime product of the price and quantity as the user inputs the quantity so that they can see their total before submitting. Here is my form

 <form method="post" action="">
               <div class="number-input">
                
                <p>Quantity:</p><input class="quantity" min="25" name="quantity" value="1" type="number">
                
               </div>  <br>

          <input type="hidden" name="item"  value="<?php echo $name ?>">
              <input type="hidden" name="price"  value="<?php echo number_format($price,2); ?>">
              <label>Name</label><br><input type="text" name="name" required><br>
              <label>Delivery Address</label><br><input type="text" name="address" required><br>
              <label>Email</label><br><input type="mail" name="email" required><br>


               <!--show the product of quantity and price here-->

             
              <button type="submit" name="submit">Submit Order</button>
         
            </form>

How can I Archieve this with js

React Material UI Textfield onChange

I would like to ask help on how to manage multiple fields in Textfield onChange area? Currently, if I am going to input a value there are no changes that is happening.

Here’s my code.

Tried the approach of using e.target.value however it would still stay the same.

enter image description here
enter image description here

babylon.js: reloaded code for disabling rotation of CharacterController not being reflected

I am trying to run the code at https://github.com/ssatguru/BabylonJS-CharacterController-Samples/tree/master/sample-nodejs and I’m not sure if I am doing this right because when I make the following change in src/index.js, the change is not reflected.

In fact I had to run npm run build, wait a few minutes and then run http-server to see the changes. This is far too slow, is there a way to speed this up?

In particular I modified the ArcRotateCamera from Babylon.js but the turning off of rotation does not occur as desired.

    var camera = new BABYLON.ArcRotateCamera("ArcRotateCamera",alpha,beta,5,target,scene);

    cc.setTurningOff(true);

adding that cc.setTurningOff did not reload the browser. In fact, it was only after I did an npm build it seem to load the modified script. Even then, the rotation turning off feature discussed over at https://github.com/ssatguru/BabylonJS-CharacterController doesn’t seem to work.

I’m very new to Babylon.js and nodejs so any help here is appreciated. Basically I want the third person character to rotate indepdently of the camera. Currently pressing backward moves the player back. I want it to face the camera when i press back, i want it to keep its own sense of rotation.

pass data between pages react

I have eventData which I need to pass from page A to B. Here’s my code:

function eCE(eventData) {

    history.push({
      pathname: '/ece',
      state: eventData
   })

})

This function gets triggered on button click, so it passed eventData through to the function. Now I need to send eventData through to the next page, in which I would get to by calling /ece. However, I am trying to grab the state on the other page like so:

const { state } = this.props.location
console.log(state)

it isn’t working, and the error I get is:

TypeError: undefined has no properties

not to sure what to do here. appreciate the help !

Access JavaScript variable from a URL using php and regex [closed]

I have a link say https://example.com

and the link contents html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">

</head>
<body>
  <br><hr><br>
  <header>
    <h1>Title</h1>
  </header>
<script>
var abc = "https://example2.com/sample.mp4";
</script>

<script>
var poster = "https://example2.com/sample.png";
</script>

</body>
</html>

and I want the value of variable abc. That will give me “https://example2.com/sample.mp4” this value.
By grabbing it using file_get_contents('https://example.com') php and getting script data using regex…


And then I will redirect My php page to the variable abc value URL ‘https://example2.com/sample.mp4’ (here)

Particle Slider logo not coming. (WordPress)

I’m trying to make a particle slider in WordPress. I’m trying to test the code here as an example. HTML also works fine. But WP also created problems.

I changed the code to div and the logo disappears. This time the logo in my work in HTML is gone.

Codes:
HTML5 – (It Works Seamlessly.)

<html lang="en">
    <head>
      <title>Particle</title>
      <style>
canvas {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
@media (min-width: 1000px) {
  body {
    background: #ffffff;
    background-repeat: no-repeat;
  }
  body > .dg {
    display: block;
  }
}
.dg ul {
  display: none;
}
.close-button {
  display: none;
}

      </style>
    </head>
    <body>
      <html>
        <head>
          <meta name="viewport" content="width=device-width" />
          <title>ParticleSlider</title>
        </head>
        <body id="particle-slider">
            <div class="slides">
                <div id="first-slide" class="slide" data-noise="100" data-src=".....">
              </div>
            </div>
            <canvas class="draw"></canvas>
          
        </body>
      </html>
      


      <footer>
        <script src="js/script.js"></script>
      </footer>
    </body>
</html>

Js Code. (It Works Seamlessly.)


// script settings

var init = function(){
    var isMobile = navigator.userAgent &&
      navigator.userAgent.toLowerCase().indexOf('mobile') >= 1;
    var isSmall = window.innerWidth < 50000;
    
    var ps = new ParticleSlider({
      pxlGap: isMobile || isSmall ? 0 : 1,
      ptlSize: isMobile || isSmall ? 2 : 1,
      width: 1000,
      height: 1000,
      showArrowControls: true,
      gravity: 1,
      mouseForce: 5e4,
      renderer: 'webgl',
    });

      
    var gui = new dat.GUI();
    gui.add(ps, 'ptlGap').min(0).max(0).step(0).onChange(function(){
      ps.init(true);
    });
    gui.add(ps, 'ptlSize').min(0).max(0).step(0).onChange(function(){
      ps.init(true);
    });
    gui.add(ps, 'restless');
    gui.addColor(ps, 'color').onChange(function(value){
      ps.monochrome = true;
      ps.setColor(value);
        ps.init(true);
    });
    
    
    (window.addEventListener
     ? window.addEventListener('click', function(){ps.init(true)}, false)
     : window.onclick = function(){ps.init(true)});
  }
  
  var initParticleSlider = function(){
    var psScript = document.createElement('script');
    (psScript.addEventListener
      ? psScript.addEventListener('load', init, false)
      : psScript.onload = init);
    psScript.src = 'http://particleslider.com/js/particleslider/current/particleslider.js';
      psScript.setAttribute('type', 'text/javascript');
    document.div.appendChild(psScript);
  }
      
  (window.addEventListener
    ? window.addEventListener('load', initParticleSlider, false)
    : window.onload = initParticleSlider);

WP Front Page HTML (Code Not Working)

<div id="particle-slider">
                <div class="slides">
                    <div id="first-slide" class="slide" data-noise="100" data-src="...
">
                </div>
                <canvas class="draw" style="width: 100%; height: 100%;"></canvas>
            </div>
        </div>

I am attempting to create a sum function in a JS calculator

Can some help correct my logic or syntax… Don’t I need to create an array from the parameters the function receives then use the reduce method to sum them up with an initial value of 0 so there is an accurate running total. Everytime log the function I get 0.

const sum = function(numbers) {
  let summed = Array.from(numbers)
  return summed.reduce((cur, prev) => cur + prev, 0)
};

Why does axios.get(url).data not work? (axios GET requests and property accessors; JavaScript)

I have an async function that is requesting an object with a name and id property. I understand that you can’t return await axios.get(url).data.name without getting kicked into the catch statement.

My question though is what is the reason that it doesn’t work?

async function getConstellationNameById(id) {
  const url = `${BASE_URL}/constellations/${id}`;

  try {
    return await axios.get(url).data.name;
  } catch (error) {
    throw `Constellation with id of ${id} could not be found.`;
  }

}

If I store the GET request in a variable instead and then use dot notation to access the name property it works:

try {    
    //return axios.get(url).data.name;
    const constellation = await axios.get(url);
    return constellation.data.name;
  }

Is it because dot notation has a timing to it? Therefore, while the GET request is in the event queue, the “.data.name” portion is considered sync code and fails to get anything? I had thought since it’s being executed all in one line, property accessors would execute along with the GET request?

Or is it because of another reason?

I also thought you could only access a Promise object’s properties within .then() and .catch() statements; is that not the case?

Apologize in advance if I’m misusing any terminology as I’m still learning! Just really want to make sure I understand the reasoning before continuing.

Unable to access res.send() data via jQuery/AJAX

I am trying to create a language converter app. It will take a string from one textarea, convert all string values via a stored dictionary on a DB, and append this converted string into a second textarea. All of this conversion will be happening on the same index.ejs page (no refreshing/redirecting/etc.) via jQuery/AJAX.

What works: I am able to POST the string data from my first textarea to my POST route and retrieve all matching dictionary entries in my app.js. The values are stored in an array called “convertArrOfArrs”. The DB is successfully queried and the data is being sent back.

What doesn’t work: When I use res.send(), this array of converted values (“convertArrOfArrs”) opens up a new blank HTML file displaying the data. This data should be dynamically added to my second text box on my current EJS file.

This is my main.js which makes the AJAX request and attempts to add the response to a 2nd textarea:

// Submits form on spacebar press
$(formPhonetic).keyup(function (event) {
  // Executes code if 'Space' is detected in the phonetic box
  if (event.code === "Space") {
// Submits form
    $(formPhonetic).submit();
    $(formPhonetic).on("submit", function (event) {
// prevents redirection
      event.preventDefault();
// store the string value of textbox 1
      let value1 = $(firstTextarea).val();
      $.ajax({
        url: "http://localhost:3000/",
        data: value1,
        method: "POST",
      })
        .then(function (response) {
          $(textarea2).append(response);
        })
        .catch(function (err) {
          console.error(err);
        });
    });
  }
});

This is my app.js which deals with the POST request.

app.post("/", async (req, res) => {
  // entire textarea string
  const txtareaStr = await req.body.txtArea1;
  // puts string into an array, lowercases it, and removes whitespaces
  const txtareaArr = txtareaStr.trim().toLowerCase().split(" ");

  let convertArrOfArrs = [];
  try {
    for (let i = 0; i < txtareaArr.length; i++) {
      // this retrieves the word object based on the DB match
      let word = await Word.findOne({ value: txtareaArr[i] });
      // stores array of conversions for each word in sequence
      convertArrOfArrs.push(word.converted);
    }
    // THIS SENDS DATA BUT RETURNS IT IN A BLANK HTML FILE
    res.send(convertArrOfArrs.join(" "));
  } catch (e) {
    console.log("ERROR", e);
  }
});

Thanks for the help!

Matched leaf route at location “/” does not have an element react-router

My app.js component code is given below
I am using the render syntax for components with props in
I have checked the syntax for calling component with props using render method, it is exactly the same
plus i am following a video tutorial he is also using the same syntax
what am i missing?
what went wrong?

import React,{useState,useEffect} from 'react';
import { v4 as uuid } from 'uuid';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import  './App.css';
import Header from "./Header";
import AddContact from "./AddContact";
import ContactList from "./ContactList";

function App() {
  const LOCAL_STORAGE_KEY ="contacts";
  const [contacts, setContacts]=useState([]);
  const addContactHandler = (contact)=>{
    console.log(contact);
    setContacts([...contacts,{id: uuid(), ...contact}]);
  };

  const removeContactHandler =(id)=>{
    const newContactList = contacts.filter((contact)=>{
      return contact.id !== id;
    });

    setContacts(newContactList);
  };

  useEffect(()=>{

    const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
    if (retriveContacts)  setContacts(retriveContacts);
  },[]);
  useEffect(()=>{
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
  },[contacts]);
  return (
    <div className='ui container'>
      <Router>
        <Header/>
        <Routes>
        
          <Route path="/" render={(props)=> (<ContactList {...props} contacts={contacts} getContactId = {removeContactHandler}/>) } />
          <Route path="/add" render={(props)=>(<AddContact {...props} addContactHandler={addContactHandler}/>)} />
        </Routes>
      </Router>
      
      
      
      {/*<AddContact addContactHandler={addContactHandler}/>
      <ContactList contacts={contacts} getContactId = {removeContactHandler}/> */}
    </div>
    
  );
}

export default App;