CSS Scroll Snap Aligns to Second Div on Page Load – How to Prevent This?

I’m currently working with CSS Scroll Snap and I’ve come across an unusual behavior. My page automatically scrolls to the second div when it loads.

Here is the structure of my code:

<div
  style={{
    height: "100vh",
    overflowY: "scroll",
    scrollSnapType: "y mandatory",
  }}
>
  <div
    style={{
      height: "100vh",
      backgroundColor: "red",
    }}
  ></div>
  <div
    style={{
      height: "100vh",
      backgroundColor: "green",
      scrollSnapAlign: "start",
    }}
  ></div>
  <div
    style={{
      height: "100vh",
      backgroundColor: "blue",
      scrollSnapAlign: "start",
    }}
  ></div>
</div>

I’ve observed this behavior across multiple browsers and there’s no other JavaScript or CSS code that should affect the scroll position on load.

My question is, why is the page automatically scrolling to the second div when it loads? Is there a way to prevent this behavior without adding scrollSnapAlign: start; to the first div?

Any help would be greatly appreciated.

Global Scope and module scope difference in React

Despite a topic with loads of resource, i still can’t fully understand the difference between global scope and module scope in the React context. Hoping someone can shed a light on how to understand the concept of scope (or perhaps I should mix the concept with React?).

According to scope docs from mdn, x is in global scope.

const x = "declared outside function"; // x is in global scope

exampleFunction();

function exampleFunction() {
  console.log("Inside function");
  console.log(x);
}

console.log("Outside function");
console.log(x);

But apparently, below code won’t work in React, which according to mdn doc of var, variable declared with var outside a function is globally-scoped.


// a.js
var x = "declared outside function";

export function exampleFunction() {
  console.log("Inside function");
  console.log(x);
}


// b.js
import {exampleFunction} from './a.js'
console.log(x); // x is not defined

If I haven’t misunderstood the definition of module, every .js file in React is considered a module?

Given this context and my understanding, is x variable still considered globally-scoped, or it should be considered belonging to a.js‘s module scope?

What about exampleFunction? Is it still considered module-scoped even though it’s being exported?

What are the practices to declare variables that are truly globally-scoped? What comes to mind is adding it to window object, declaring it inside html file with a <script> tag, adding it in a .env file.

Correction on my understanding or pointing to a solid resource

React Server APIs | renderToReadableStream & renderToPipeableStream reactNode to render

I’m reading the documentation of renderToReadableStream and renderToPipeableStream React Server APIs.

Their shape is the following:

  • renderToReadableStream(reactNode, options?)
  • renderToPipeableStream(reactNode, options?)

My question is: can reactNode be an arbitrary node (for example, a simple <div>...</div> tag with some content) or it should represent the entire document (<html>...</html>) as stated in the documentation?

Thank you!

Facing an issue with removing UI buttons in elements of my downloaded PDF file

I am using JSpdf and html2canvas to download my HTML UI code as a PDF file. However, I want to remove the buttons from the PDF file while keeping it visible in the UI. Currently, I am using the following code to remove the button from the element by making a clone. Still, it is not working and I am getting an error in the console.

**Uncaught (in promise) Unable to find an element in cloned iframe**.

I need to find a solution to remove the buttons from the PDF without removing them from the UI. You can reference the codesandbox link in the UI below.

My task is to remove the UI buttons in my PDF file when I download it.

  pdfDownloadHandler(name, div, removeElement) {
    const input = document.getElementById(div);
    const clone = input.cloneNode(true);
    const removeChildElement = clone.querySelectorAll(removeElement);
    new DocumentFragment().append(...removeChildElement);
    const divHeight = clone.clientHeight;
    const divWidth = clone.clientWidth;
    const ratio = divHeight / divWidth;

    html2canvas(clone).then((canvas) => {
      // Create a new PDF canvas.
      const imgData = canvas.toDataURL('image/jpeg');
      const pdf = new JsPDF('p', 'pt', [canvas.width, canvas.height]);
      // then we get the dimensions from the 'pdf' file itself
      const width = pdf.internal.pageSize.getWidth();
      let height = pdf.internal.pageSize.getHeight();
      height = ratio * width;
      // convert your PDF and save to file
      pdf.addImage(imgData, 'JPEG', 0, 40, width, height);
      pdf.save(`${name}.pdf`); // Download the rendered PDF.
    });
  },
<Grid
container
px={3}
pt={2}
rowSpacing={4}
component="div"
id="downloadDoc"
>
      <Grid item xs={12}>
        <Box display="flex" alignItems="center">
          <Box flexGrow={1}>
            <Typography variant="h3"> Dashboard</Typography>
          </Box>
          <Box display="flex" gap={2}>
            <Button
              id="removeElement"
              variant="contained"
              color="primary"
              title="Download"
              onClick={() => {
                // exportToWord("exportTofile");
              }}
            >
              Other DOWNLOAD
            </Button>
          </Box>
          <Box display="flex" gap={2}>
            <Button
              id="removeElement"
              variant="contained"
              color="primary"
              title="Download Word"
              onClick={() => {
                pdfDownloadHandler(
                  "downloadPdf",
                  "exportTofile",
                  "#removeElement"
                );
              }}
            >
              DOWNLOAD PDF
            </Button>
          </Box>
        </Box>
      </Grid>
  <Typography variant="h4"> summery</Typography>
  <Box
    mt={2}
    display="flex"
    justifyContent="space-between"
    alignItems="center"
  >
    <Box>
      <Typography variant="subtitle2">
        {formikForm.values.summery}
      </Typography>
    </Box>
    <IconButton
      size="small"
      onClick={() => {
        seteditText('summery');
      }}
      title="Edit "
      color="primary"
    >
      <EditIcon />
    </IconButton>
  </Box>
</Grid>
<Grid item xs={12}>
  <Typography variant="h4">purpose and use</Typography>
  <Box
    mt={2}
    display="flex"
    justifyContent="space-between"
    alignItems="center"
  >
    <Box>
      <Typography variant="subtitle2">
        {formikForm.values.purpose}
      </Typography>
    </Box>
    <IconButton
      size="small"
      onClick={() => {
        seteditText('purpose');
      }}
      title="Edit "
      color="primary"
    >
      <EditIcon />
    </IconButton>
  </Box>
</Grid>
<Grid item xs={12}>
  <Typography variant="h4">performance data test</Typography>
  <Box
    mt={2}
    display="flex"
    justifyContent="space-between"
    alignItems="center"
  >
    <Box>
      <Typography variant="subtitle2">
        {formikForm.values.modelData}
      </Typography>
    </Box>
    <IconButton
      size="small"
      onClick={() => {
        seteditText('modelData');
      }}
      title="Edit"
      color="primary"
    >
      <EditIcon />
    </IconButton>
  </Box>
</Grid>

</Grid>

CodeSandBox Link

How can I use BootstrapPersianDateTimePicker in different sections in Angular

I have an Angular page with a number of sections in which I use BootstrapPersianDateTimePicker for bootstrap 5 in some of the sections. It works fine at first, but when I switch between sections, it stops working.

index.html

<body>
  <app-root></app-root>
  
  <link href="assets/vendors/PersianDate/mds.bs.datetimepicker.style.css" rel="stylesheet">
  <script src="assets/vendors/PersianDate/mds.bs.datetimepicker.js" type="text/javascript"></script> 
</body>

—>component.ts

RunDateScript(){      
      import('src/assets/vendors/bootstrap/RunScript.js'); 
    };

—>RunScript.js

new mds.MdsPersianDateTimePicker(document.querySelector('#date-text'), {
  targetTextSelector: '#date-text',
  targetDateSelector: '#date-value'
});

—>component.html

<section *ngIf="isShow=='section1' ">                        
   <div _ngcontent-c15="" class="col-md-4">                                                                        
      <input type="text" class="form-control" id="date-text" >
   </div>
</section>
<section *ngIf="isShow=='section2' ">

<section>

what does console.dir truly return

For example

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

Object.getOwnPropertyNames(Point) // ['length', 'name', 'prototype']
console.dir(Point)
// class Point
// length:2
// name:"Point"
// prototype:{ constructor: ƒ, toString: ƒ }
// arguments:(...)
// caller:(...)

arguments and caller not exits on Point, why console.dir show them, same as HtmlElements

const div = document.createElement('div');
Object.getOwnPropertyNames(div) // []
console.dir(div)
//div
//accessKey: ""
//align: ""
//.......

Object.getOwnPropertyNames shows div does not have its own property,what dose accessKey、align mean

what does console.dir(object) truly return?

String does return as expected [closed]

Intro

It’s really simple. I have two files, ‘Signup.jsx’ and ‘createUser.js’. In the Signup component, I call the createUser function. createUser generates a string response, which I can print in that file, but when I return the response to the Signup component, it prints ‘undefined’.

Signup.jsx createUser.js
console.log(res) console.log(res)
undefined ERROR

Relevant Code

Signup.jsx

const handleSubmit = async () => {
      try {
        const res = await createUser(username, password)
        console.log(res) // PRINTS 'UNDEFINED' (SHOULD PRINT 'ERROR')
      }
      // catch
    }

createUser.js

import axios from "axios";

const createUser = async (name, userpassword) => {

    const data = {
        username: name,
        password: userpassword
    }

    axios.post('http://localhost:3001/register', data)
        .then(function(response) {
            console.log(response.data) // PRINTS 'ERROR
            return response.data; // SHOULD PASS 'ERROR' UP TO SIGNUP.JSX
        })
        .catch(function (error) {
            if (error.response) {
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
            } else if (error.request) {
            console.log(error.request);
            } else {
            console.log('Error', error.message);
            }
            console.log(error.config);
        });
}

export default createUser;

What I’ve Tried

I’ve tried const response = await res as an attempt to wait until the createUser call resolves, but that doesn’t do anything.

Try to run a JavaScript file with Nashorn, failing due to problems with import/const/require

I need to add a new feature to my Java-8-based application (can’t upgrade Java) where it takes an encoded string and decodes it to a JSON. The issue is that that decoding library is written in JavaScript, and the effort to convert the JavaScript code to Java could be consequential.

Looking into alternative solutions, I came across Nashorn, which supposedly is able to run Javascript code from Java. And so I tried to make it work.

First, I created a project with my `index.js” file containing an import statement and a function:

import codec from "some-package"

function decode(a, b) {
   ...
}

I then installed the necessary packages through npm -i and ran my JavaScript code to verify that it worked by itself. Both node index.js and running the code through the right click action of VisualStudio (“Run Code”) worked.

Then, I tried to make it work with Java. I moved all the files from my front project into the resources folder of Java, I created a test project with a main() function, and I wrote the following code:

NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine("--language=es6");

try (Reader reader = new InputStreamReader(Objects.requireNonNull(Pulse4Decoder.class.getClassLoader().getResourceAsStream(DECODER_FILE_NAME)), StandardCharsets.UTF_8))
        {
            engine.eval(reader);
        }
    ```

I then ran this code but got the following error:

Exception in thread “main” javax.script.ScriptException: :2:0 Expected an operand but found import
import codec from “some-package”;
^ in at line number 2 at column number 0
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:537)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:524)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:150)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:249)
at com.edoreld.decoder.Pulse4Decoder.decode(Pulse4Decoder.java:30)
at com.edoreld.decoder.Pulse4Decoder.main(Pulse4Decoder.java:20)


I thought the problem could be due to Nashorn requiring a specific form of the import statement, so I changed it to `const codec = require('@adeunis/codecs');`. However, this failed with the following error:

Exception in thread “main” javax.script.ScriptException: ReferenceError: “require” is not defined in at line number 1
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:454)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:150)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:249)
at com.edoreld.decoder.Pulse4Decoder.decode(Pulse4Decoder.java:30)
at com.edoreld.decoder.Pulse4Decoder.main(Pulse4Decoder.java:20)


I googled both errors (which is how I came to use `--language=es6` in my codeo originally), but I wasn't able to make it work. 

Are import/require statements not supported in Nashorn? How am I supposed to call a function in a JavaScript file that required a specific package if I can't make import/require to work?


How to catch the range picker button click events and apply a simple transformation to the data?

In this Range Selection section and examples it shows how to add range picker (the buttons YtD, 1y, 2y etc.) to the stock plot. See the example from that documentation in the AnyChart Playground STOCK_Range_Selection_01.

In my use-case I am comparing prices for multiple funds and I would like to catch the event when any of the ranges is clicked e.g. YtD, then transform the prices for all active series and re-scale them to start from 1. so that the different prices are comparable performance-wise starting at that new X origin. Basically I would have prices1, prices2 and prices3 and divide each by the starting price so they become a comparable wealth index starting on that range and with price value of 1.0 e.g.

price1.loc[YtD, :] = price1.loc[YtD, :] / price1.loc[YtD] 

How can I do that using AnyChart?

I’m trying to make a custom chatbot from cooper code’s tutorial but i keep getting an error everytime i try to run node server.js in vscode

screenshot of the error note: I am still a newbie when it comes to coding, i have tried searching google for solutions but can’t find any.

(This is the error i keep getting even when i follow everything he says and types in vscode.)

PS C:UsersdabaoVSCODE TEST> node server.js
node:internal/modules/cjs/loader:390
throw e;
^

SyntaxError: Error parsing C:UsersdabaoVSCODE TESTpackage.json: Unexpected string in JSON at position 313
at parse ()
at readPackage (node:internal/modules/cjs/loader:378:42)
at readPackageScope (node:internal/modules/cjs/loader:414:19)
at shouldUseESMLoader (node:internal/modules/run_main:47:15)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:24)
at node:internal/main/run_main_module:23:47 {
path: ‘C:UsersdabaoVSCODE TESTpackage.json’

i tried to redo everything and even copied the code from github to make sure that it’s an experience issue but i still get the same error everytime.

Return JavaScript from Rails Controller Action

In a new Rails 7 application, I’m working on an autosave feature for a form with just a textarea. I use custom JavaScript to handle the form submission, and this works well.

window.addEventListener("load", function () {
  const form = document.querySelector(".form");
  const field = document.querySelector(".field");

  if (!form || !field) return;

  let submitTimeout;
  field.addEventListener("input", () => {
    clearTimeout(submitTimeout);

    submitTimeout = setTimeout(() => {
      form.submit();
    }, 500);
  });
});

The ERB form is as follows (the @resource variable is always a persisted record, since it’s set up that way in the edit action):

<%= form_with scope: :resource, model: @resource, remote: true, class: "form" do |form| %>
  <%= form.hidden_field :id %>
  <%= form.text_area :text, size: "30x10", class: "field" %>
<% end %>

However, when the form is submitted (behind the scenes), it calls the update action in my controller, which looks like so:

class ResourcesController < ApplicationController
  ...

  def update
    resource = current_user.resources.find(resource_params.delete(:id))
    resource.update!(resource_params)
  end

  private

  ...
end

and this works well in most browsers, except when it comes to Safari. In Safari, the lack of response from this action confuses the browser and it shows a download link, which isn’t the desired behaviour.

To get around this, I thought it would be useful to return some JavaScript, which I’ve seen elsewhere (on StackOverflow), so I updated the controller to respond to js and updated the form to use the js request format type:

<%= form_with scope: :resource, model: @resource, remote: true, format: :js, class: "form" do |form| %>
  <%= form.hidden_field :id %>
  <%= form.text_area :text, size: "30x10", class: "field" %>
<% end %>
class ResourcesController < ApplicationController
  ...

  def update
    resource = current_user.resources.find(resource_params.delete(:id))
    resource.update!(resource_params)

    respond_to do |format|
      format.js
    end
  end

  private

  ...
end

and I created a sample JS file to test this setup in /views/resources/update.js.erb:

console.log("hello world");

The issue is that after the response comes back, the browser redirects to /resources/:id.js where :id is the ID of the persisted resource. This is not the desired behaviour and not what I expected based on other questions and answers I’ve seen here. My intenteion, of course, is that the JavaScript is executed on the page. I figure it worked in older versions, but not in Rails 7. I’m on Rails 7.0.5, to be precise.

Is there a Javascript library or an API that turns text to SQL queries?

I’m working on a chatbot that receives the user’s input from the chatbot and turns that input to an SQL query so then I can retrieve some data from the database.
I was wondering if there are any javascript libraries or any API’s that I can use that would convert that input to query by calling the API for example.
I’m using Node.js for my backend but if there’s a python library as well I’d be happy to know. Thank you in advance.

Is there maybe a chatbot library that has the same function. I’ve read about dialogflow, etc. but I didn’t find anything relative to my problem.

Passing return value as function arguments (tuple)

I’m trying to use the return value of my function as arguments for my function, however the fact that it’s a tuple is being problematic. This is further compounded by the fact that it will not always be a tuple.

function foo(initial_state, indexer = 0) {
// does something

return [initial_state, indexer + 1];
}

I want to be able to sometimes use the function as simply

foo(initial_state);

but also I want to call the function with the return, as such..

foo(foo());

Instead of the desired behavior, the tuple is put into initial_state, whereas I would want it deconstructed to match the arguments in the function.

I can obviously do a temporary variable like

let some_state, some_index = foo();
foo(some_state, some_index);

But that seems very ugly. There has to be a better way.