get y-axis value of child element when scroll parent in javascript

To get the Y-axis value of a child element when scrolling the parent element in JavaScript, you can use the scroll event on the parent element and then calculate the position of the child element within the parent’s coordinate system. Here’s a step-by-step guide on how to achieve this:

HTML Structure:
You should have a parent element (e.g., a div) that contains a child element. The parent element should have a specified height and be scrollable if the content overflows.

<div id="parent" style="height: 300px; overflow: auto;">
  <div id="child" style="height: 500px;">
    <!-- Content inside the child element -->
  </div>
</div>

JavaScript Code:
Add JavaScript code to listen for the scroll event on the parent element and calculate the Y-axis value of the child element within the parent’s coordinate system.

const parent = document.getElementById("parent");
const child = document.getElementById("child");

parent.addEventListener("scroll", function() {
  const yRelativeToParent = child.getBoundingClientRect().top;
  console.log("Y-axis value relative to parent:", yRelativeToParent);
});

In this code:

  • We first get references to the parent and child elements using getElementById.

  • We then add a scroll event listener to the parent element.

  • Inside the event handler, we use the getBoundingClientRect() method
    to get the position of the child element relative to the viewport.
    The top property of the returned rectangle represents the Y-axis
    value of the child element within the parent’s coordinate system.

Now, when you scroll the parent element, the Y-axis value of the child element relative to the parent will be logged to the console. You can use this value for various purposes, such as updating the child element’s position based on the scroll offset.

Quill editor and Quill Mention : populating an input field with user id

I am running Quill Mention, and I want to populate an input field with the user id.

The form:

<form>
    <div id="editor"></div>
    <input type="hidden" id="user_id_field">
</form>

The JS:

async function suggestPeople(searchTerm) {
   const allPeople = [
      { id: 1, value: "Fredrik Sundqvist" },
      { id: 2, value: "Patrik Sjölin" }
   ];
   return allPeople.filter(person => person.value.includes(searchTerm));
}

const quill = new Quill("#editor", {
    placeholder: "Enter @",
    modules: {
        mention: {
            allowedChars: /^[A-Za-zsÅÄÖåäö]*$/,
            mentionDenotationChars: ["@"],
            source: async function(searchTerm, renderList) {
                const matchedPeople = await suggestPeople(searchTerm);
                renderList(matchedPeople);
            }
        }
    }
});

window.addEventListener("mention-clicked", function(event) {
    const userId = event.detail.id;
    const userField = document.getElementById("user_id_field");
    userField.value = userId;
});

The list is displayed properly, but the ‘mention-clicked’ event is not triggered.

This shows nothing in the console:

window.addEventListener("mention-clicked", function(event) {
    console.log(event);
});

Check and truncate data being passed as a prop based on the table row width

I am trying to check the width of the table row, In the component I have here, I have defined the interface for what the data looks like, I want to check the div width and also set the data truncated with class property of text overflow eclipse in case it is overflowing and display the data as it is if it is not over flowing, Also I want to show the words with are not being displayed but are there in case the data gets truncated. (I think I can use slice for this to get the sliced array)

input example as array of strings with indexes :0: [“me”, “car”, “image”, “blah”, “blah”, “blah”, “bike”]
1:[“me”]
2:[“me”, “car”, “image”, “blah”]

expected output :

me, car … [5]
me
(based on the width of the element)

Given that the screen is resizable, the tr width will change according to screen

main component structure

<table {...rest}>
      <thead>
        <tr>
          <th>Sender</th>
          <th>Recipients</th>
          <th>Subject</th>
          <th className="align-right">Date</th>
          <th className="align-right">Time</th>
        </tr>
      </thead>
      {Object.entries(emailsByDate).map(([datetime, emailGroup]) => (
        <tbody key={datetime}>
          {emailGroup.map(({ id, from, to: recipients, subject, datetime }) => (
            <tr key={id}>
              <td>{from}</td>
              <td>
                <RecipientsDisplay recipients={recipients} />
              </td>
              <td>{subject}</td>
              <td className="align-right">
                <DateDisplay datetime={datetime} />
              </td>
              <td className="align-right">
                <TimeDisplay datetime={datetime} />
              </td>
            </tr>
          ))}
        </tbody>
      ))}
    </table>

recipients display component


import React, { useLayoutEffect, useState } from 'react'
import styled from 'styled-components'
import { useRef } from 'react'
//todo
// deiplayed the data by interating over the array of object passed

//defining the interface
interface data {
  recipients: string[]
}

const Overflow = styled.span`
  font-size: 16px;
  color: #333333;
  padding-top: 5px;
  padding-bottom: 5px;
  padding-left: 10px;
  padding-right: 10px;
  background-color: red;
  width: 100%;

  white-space: nowrap;

  white-space: nowrap;
`

function RecipientsDisplay(data: data) {
  //logic to handle the displaying of the e
  const classcheck = useRef<HTMLDivElement | null>(null)
  const [truncated, setTruncated] = useState(false)

  useLayoutEffect(() => {
    if (classcheck.current) {
      if (classcheck.current.clientWidth < classcheck.current.scrollWidth) {
        setTruncated(true);
      }
    }
  }, [])

  return (
    <Overflow
      className={`${truncated ? ' text-overflow: ellipsis; ' : ''}`}
      ref={classcheck}
    >
      {truncated ? data.recipients+ ", ": data.recipients}
    </Overflow>
  )
}

export default RecipientsDisplay

however, this sets everything to truncated? I am so confused, I wrote some .join logic and then compared that to the width of the div before, but that didn’t work out, so I refactored and now trying to start from the beginning ..
Also, what topic should I look up in order to understand these problems better since I havnt encountered anything like this before?

career , path , advises

You are a someone who are intersted in back-end, you are shifting career to software industry , you have finished fundamentals of programming , oop , data structure , and algorithms , you learn C# , and SQL database.
You priorty is finding you first job, (.net develpoer) or (full stack engineer) , mentioned that number one important is finding your first job , weather you like back/front -end doesn’t matter, you trying to make chances to find job , higher. thanks for help .

recommendation/ resources to learn from/ other expereince/ lessons to learn from .

Dynamically create Webpack 5 Entries from array

I would like to add additional entries in webpack.config.js from an array with Webpack 5. here is the array:

const unitTest = [ { name: 'bootloader' }, { name: 'levenshtein' } ]

I wrote the following code to append the additional entries from the array.

entry: {
    main: ['./src/js/index.js'],

    ...unitTests.map((test) => {
      let newEntry ={};
      newEntry[`${test.name}`] = [`./src/unit-test/${test.name}/index.js`];
      return newEntry;
    }),
    
  },

The problem is that the map() function returns an array, and my entries become something like:

{
  '0': { bootloader: [ './src/unit-test/bootloader/index.js' ] },
  '1': { levenshtein: [ './src/unit-test/levenshtein/index.js' ] },
  main: [ './src/js/index.js' ],
}

Of course, Webpack isn’t happy. I can’t figure out how the append new fields propertly to the entry object?

I want to divide any different numbers entered by user through prompt method

The thing is i want is the user to enter the limit of the numbers he or she wants to divide and then i can divide them . Like the user says limit is 4 and then enters numbers like 60/2/3/5 to give 2.

case 'division':
    function division(){
        let num = 0;
        let division = 1;
        let div=division
        let i = 0;
        window.ask=prompt('Enter the limit of the numbers to be multiplied');
        while(i<window.ask){
            let num=parseInt(prompt('Enter the numbers one by one '));
            division= num/division;
            if(division=num){
                div=div/num;
            }
            i++;
        }
        alert("The result is "+div);
    }
    division();
    break;

I tried this expecting that after entering the first number it would divide by 1 and if the division was equal to the number stored in the variable ‘num’ then div would divide the division result with the value stored in ‘num’ that is entered in the next round by the user but i got stack as the result of 60/2/3/5 was 0.0005 and in addition i want to be using while loop to be able to calculate any limit the user can enter not just like 3 0r 4 numbers.

I want to give unique id to component when using generic handler

// ...
const AddUser = (props) => {
  // ...
  const submitEventHandler = (event) => {
    event.preventDefault();
    console.log(user);
    if (user.name.trim().length === 0 || user.age.trim().length === 0) {
      setIsValid(false);
    }
    if (+user.age < 1) {
      setIsValid(false);
    } else {
      setIsValid(true);

      setUserList((prev) => {
        return [...prev, user];
      });
      setUser(initialState);
    }
    console.log(user);
  };
  const changeEventHandler = (type, value) => {
    setUser((prev) => {
      return { ...prev, [type]: value };
    });
  };
// ...
};

export default AddUser;

import Card from "./UI/Card";
import classes from "./UserList.module.css";

const UserList = (props) => {
  const userList = props.userList;
  return (
    <Card className={classes.users}>
      <ul>
        {userList.map((user) => {
          return (
            <li key={user.id}>
              {user.name} ({user.age} years old)
            </li>
          );
        })}
      </ul>
    </Card>
  );
};

export default UserList;

I want to give unique id to user state (key in

  • ) when using map method
    but I’m using generic handler (changeEventHandler in AddUser component)
    so when I added id property in generic handler it’ll be repeated whenever changeEvetHandler is triggered
    what is the best way I can add unique id property when using generic handler?
  • Dynamically update object values from html textarea

    Good Day;

    I’m creating bar charts using JavaScript. What i need is the user to input values for the chart.
    At the moment i wrote code (through a tutorial) where the values are hard coded on to the script.I need to amend the hard coded so the value can be entered via a textarea and dynamically the chart changes according to the values (i prefer not to have a button – dynamical changes).

    This is my javascript object:

    const classic = document.getElementById('classic').value;
    
    var myBarchart = new BarChart({
    
    
    canvas: myCanvas,
      seriesName: "Vinyl records",
      padding: 40,
      gridStep: 5,
      gridColor: "black",
      data: {
        Classical_Music: classic,
        "Alternative Rock": 12,
        Pop: 18,
        Jazz: 32
      },
      colors: ["#a55ca5", "#67b6c7", "#bccd7a", "#eb9743"],
      titleOptions: {
        align: "center",
        fill: "black",
        font: {
          weight: "bold",
          size: "18px",
          family: "Lato"
        }
      }
    });
    

    What i need the value from the classic should be used to change the value in the data object.

    HTML Code:

    <body>
    <textarea id="classic"></textarea><br>
    
    <canvas id="myCanvas" style="background: white;"></canvas>
    <legend for="myCanvas"></legend>
    
    
    <script type="text/javascript" src="script.js"></script>
    

    Any guidance will be appreachiated.

    Flatten the object gets the console logged thrice

    When I use the code below to flatten the object, I get the console logged thrice. The object is to return or console ONE object i.e. newObj

    Can someone tell me what I am doing wrong?

    Data Input

        id: 09,
        email: '[email protected]',
        contactInfo: {
            name: 'Test1',
            address: {
                city: 'Berlin',
                country: 'Germany'
            }
        }
    }
    

    Over here I am Flattening the Object through recursive calls.

    const newObj = {}
    
    const getFlattenObj = (data) => {
        Object.keys(data).forEach(key => {
            if (typeof data[key] === 'object') {
                getFlattenObj(data[key]);
            } else {
                newObj[key] = data[key]
            }
        })
    
        console.log(newObj);
    }
    
    getFlattenObj(data);
    
    

    Export 2 Kendo Grids on the same PDF page and a chart on the next page

    I am trying to export 2 Kendo grids with only a few of rows of data on the same PDF page and a chart on the next page. I am able to current export these in 3 different pages.
    Here is how I’m doing it now.

    function OnPdfExport() {
            var grid1 = $('#Grid1').data('kendoGrid');
            var grid2 = $('#Grid2').data('kendoGrid');
    
            var progress = $.Deferred();
            kendo.drawing.drawDOM($("#Chart"), { forcePageBreak: "#Chart", paperSize: "A4", landscape: true, margin: { left: "2cm", top: "2cm", right: "1cm", bottom: "1cm" }}).done(function (chart) {
                grid1._drawPDF(progress).then(function (firstGrid) {
                    grid2._drawPDF(progress).then(function (secondGrid) {
                        secondGrid.children.forEach(function (x) {
                            firstGrid.children.push(x);
                        })
                        firstGrid.children.push(chart);
                        return kendo.drawing.exportPDF(firstGrid, { multiPage: true });
                    }).done(function (dataURI) {
                        kendo.saveAs({
                            dataURI: dataURI,
                            fileName: "Report.pdf"
                        });
                        progress.resolve();
                    })
                })
            })
    }
    
        $("#Grid1").kendoGrid({
                dataSource: gridDataSource,
                pdf: {
                    //allPages: true,
                    paperSize: "A4",
                    margin: { top: "6cm", right: "1cm", bottom: "1cm", left: "1cm" },
                    landscape: true,
                    template: $("#page-template").html()
                },
                columns: [{
                   ... // many columns
                }]
            });
        $("#Grid2").kendoGrid({
                dataSource: gridDataSource2,
                pdf: {
                    paperSize: "A4",
                    margin: { top: "1cm", right: "1cm", bottom: "1cm", left: "1cm" },
                    landscape: true
                },
                columns: [{
                   ... // many columns
                }]
            });
    

    Is there a way I could export the 2 grids with a report header template(#page-template) on first page of the PDF and a chart on the next page in the same PDF?

    How To Get Date Format String from a date? [closed]

    I need to get the date format string as per the browser culture settings.
    Eg: 01-11-2023, output- dd/MM/yyyy
    7/10/23, output- d/MM/yy

    Also, It shall consider MMM or mmm as per the browser culture.

    I tried to look for the solution but did not find anything suitable yet. If anyone has any idea via custom logic or any npm package?

    How to open a popup window when the link is on someone else website

    I want to make a feature in which I have a video player that I want to show on a new popup window with a specified width and height and the video would be playing in it. Now, It works fine if it’s my website, i.e. I had a button that when clicked opens up a new popup window with the video player.
    I want to achieve the same result on my user website, i.e. they would just paste a link on their description of my site URL, and if someone clicks on the link it somehow opens up the popup with the video player that I would render inside it

    <button id="openButton">Click me</button>
    <script>
    document.addEventListener("DOMContentLoaded", function () {
              
                    
    
    openButton.addEventListener("click", function () {
    const htmlFileURL = "problem.html";
    
    // Specify the width and height for the new window
    const windowWidth = 200;
    const windowHeight = 300;
    
    // Calculate the position for the new window (centered on the screen)
    const windowX = (window.innerWidth - windowWidth) / 2;
    const windowY = (window.innerHeight - windowHeight) / 2;
    
    // Open the new window with the specified dimensions and URL
    window.open(
        htmlFileURL,
        "NewWindow",
        `width=${windowWidth}, height=${windowHeight}, left=${windowX}, top=${windowY}`
    );         
    
    });
        </script>