function with parameters not working with onclick and work with console.log only

here is the code

<button id="show">Show</button>
<script>
function sayMessage (fName, lName) {
  let message = `Hello`;
  function concatMsg() {
    message = `${message} ${fName} ${lName}`;
  }
  concatMsg();
  return message;
}

document.getElementById("show").onclick = sayMessage("Moro", "Mero"); // Not Working!!

console.log(sayMessage("Moro", "Mero"));

</script>

It prints Hello Mohamed Shaker in the console. but when I try it using the button to show it in my html it doesn’t work!

I’m trying to get the same result that appeared in the console but in my html page and it didn’t work!

how do i redirect the iframe directory to another html file if it does not work properly

so i was working on my project called “HTML GIZMO” and i realised that switching between html pages makes your search history wayy too clutered so i made an iframe that displays the original project so only one item will be displayed in the search history.with iframe and switched pages multiple times without iframe and switched pages multiple times.

but whenever the iframe encounters a problem like this where the item is either moved, edited, or delted, it shows like this. it doesnt really look good so i wanted for whenever this error shows up i want the iframe to change the link to another html file that says an error occured. so like i want it to show the html file that says error has occured to be inside the iframe if this happens. here is my iframe file code:

<!doctype html>
<html lang="en">
<head>
    <link rel="icon" type="image/x-icon" href="./images/htmlicon.png">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>HTML GIZMO</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
        }
        iframe {
            display: block;
            width: 100%;
            height: 100vh;
            border: none;
        }
    </style>
</head>
<body>
    <iframe id="contentFrame"></iframe>
    <script>
        const targetPageUrl = './main/homes.html';
        const iframe = document.getElementById('contentFrame');
        iframe.src = targetPageUrl;
    </script>
</body>
</html>

Why does my extracted Link bring me an Error 400?

One purpose of my Code is, to get the hyperlink of a cell in google sheets. But when using my code to get the Hyperlink values for the HTML Page, I just get an Error 400 when I click the extracted Link instead of opening the Hyperlink in the cell.

function GrabData() {
  let rng = wsProz.getRange(5, 2, wsProz.getLastRow(), 47).getValues().filter((v) => v[0] !== "");

  let arr = [];

  rng.forEach((el) => {
    let internalId = SplitInternalID(el[4], ".PRO.");

    // Extract the URL from the cell with the hyperlink
    let url = getLink(el[7]);

    arr.push({
      title: el[6],
      status: el[11],
      department: el[9],
      url: url, // Use the extracted URL
      processOwner: el[0],
      subProcess: el[1],
      subProcessId: el[2],
      id: el[4],
      index: el[5],
      responsible: el[10],
      lastCheck: "xx.xx.xxxx",
      dateValidFrom: new Date(el[8]).getDateGER(),
      dateCreated: new Date(el[26]).getDateGER(),
      dateUpdated: new Date(el[27]).getDateGER(),
      withdrawn: el[14],
      internalID: internalId[0] + "%" + internalId[1],
      internalID1: internalId[0],
      internalID2: internalId[1],
    });
  });

  Logger.log(arr);
  return JSON.stringify(arr);
}

// Custom function to extract the link URL from a cell
function getLink() {
  var link = wsForm //the Sheet I use
  return link;
}

Tried changing

let url = getLink(el[7]);

to

let url = el[7] ? el[7].getRichTextValue().getLinkUrl() : "";

to check if the cell has a hyperlink, but I get the error “ScriptError: TypeError: el[7].getRichTextValue is not a function”

Tensor flow Getting started

Ok i’m trying to get my head around TensorFlow so downloaded their Getting started example and it works but the result was nothing to write home about so figured that the perfect place to start was to improve the accuracy by increasing the number of training cases from 6 to 60

except now its incapable of resolving the value

the original code

  const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
  const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

my modified version

  const d = [];
  const r = [];
  for (let x = -50; x < 10; x++) {
    const y = x * 2 - 1;
    d.push(x);
    r.push(y);
  }
  const xs = tf.tensor(d);
  const ys = tf.tensor(r);

i figured ok i’ve increased the dataset by a factor of 10 so maybe the default learning time of 250 wasn’t sufficient so i increases to incrementally to 5000 and no difference every time the result is NaN, if i change the for loop to match the orginal array then the code works again

now given my understanding of AI the more training data the better so surely 60 records isn’t an excessive quanity so i assume the problem lies elsewhare but i have no idea what

any suggestions would be appreciated

edit the orginal script in full

async function run() {
  // Create a simple model.
  const model = tf.sequential();
  model.add(tf.layers.dense({units: 1, inputShape: [1]}));

  // Prepare the model for training: Specify the loss and the optimizer.
  model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

  // Generate some synthetic data for training. (y = 2x - 1)
  const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
  const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

  // Train the model using the data.
  await model.fit(xs, ys, {epochs: 250});

  // Use the model to do inference on a data point the model hasn't seen.
  // Should print approximately 39.
  document.getElementById('micro-out-div').innerText =
      model.predict(tf.tensor2d([20], [1, 1])).dataSync();
}

run();

How to develop a professional Node.js package? [closed]

Right now I am working on a little project called wow-calendar.js.

I feel like there is room for improvement regarding file structure, JSDoc & overall code quality / package development.

Are there any standards i can go by when developing such a package? In which file do i put my JSDoc statements (Do i just put them, where the functions are?)

For example: this is my index.js:

// Dependencies

const moment = require("moment");

// Import the utility functions

let { getEventData } = require("./utils/getEventData.js");
let { scrapeEvents } = require("./utils/scrapeEvents.js");

// Export the functions

module.exports = {
    getActiveEvents,
    getAllEvents,
    getEvent
};

/**
 * A WoW event object.
 * @typedef {Object} Event
 * 
 * @property {String} category The WoWHead category of the event.
 * @property {String} categoryName The name of the WoWHead category of the event.
 * @property {Int8Array} duration0 The minimum duration in hours.
 * @property {Int8Array} duration1 The maximum duration in hours.
 * @property {Date} endDate The end date of the event when it was initially released.
 * @property {Int8Array} id The event ID.
 * @property {String} name The name of the event.
 * @property {Date} startDate The start date of the event when it was initially released.
 * @property {Array<Object<EventOccurence>>} occurrences An array of all occurrences of the event.
 * @property {Int8Array} filtertype The WoWHead filter type of the event.
 * @property {Float32Array} rec The WoWHead rec of the event.
 * @property {Int8Array} popularity The WoWHead popularity of the event.
 * @property {String} description The description of the event.
 * @property {String} descriptionLocale The locale of the description of the event.
 * @property {Boolean} descriptionFallback Whether the description of the event is a fallback to "en".
 * @property {String} eventIconURL The URL to the event icon.
 * 
 */

/**
 * A WoW event occurence object.
 * @typedef {Object} EventOccurence
 * 
 * @property {Date} start The start date of the event.
 * @property {Date} end The end date of the event.
 * 
 */

/**
 * Retrieves all events from the events list from WoWHead
 *
 * @param  {String}     [locale="en"]   The desired locale of the results, e.g. "de", "en", "es".
 * 
 * @return {Promise<Array<Event>>}                    Returns an array of all event objects
 * 
 * @author RootK1d
 * @since  2.0.0
 * @type   {Event}
 */

async function getAllEvents(locale) {
    // If no locale is provided, default to "en"
    if (!locale) locale = "en";

    return scrapeEvents(locale);
}



/**
 * Retrieves all events from the events list from WoWHead
 *
 * @param  {String}     [locale="en"]   The desired locale of the results, e.g. "de", "en", "es".
 * 
 * @return {Promise<Array<Event>>}                    Returns an array of all event objects (+ event descriptions)
 * 
 * @author RootK1d
 * @since  2.2.0
 * @type   {Event}
 */

async function getActiveEvents(locale) {

    // If no locale is provided, default to "en"
    if (!locale) locale = "en";

    let activeEvents = [];

    let result = scrapeEvents(locale).then(async (result) => {
        // Filter out all events that are not active according to the occurrence array

        let filteredResults = result.filter((event) => {
            return event.occurrences.length > 0;
        });

        for (let i = 0; i < filteredResults.length; i++) {

            //Remove all events that have [] or # in their name

            if (!filteredResults[i].name.includes("[]") && !filteredResults[i].name.includes("#")) {

                for (let j = 0; j < filteredResults[i].occurrences.length; j++) {

                    // Convert the start and end dates to ISO strings
                    let start = new Date(filteredResults[i].occurrences[j].start).toISOString();
                    let end = new Date(filteredResults[i].occurrences[j].end).toISOString();

                    // Add active events to the activeEvents array
                    if (moment().isBetween(start, end)) {

                        // Get the event data
                        let event = await getEventData(locale, filteredResults[i].id)

                        // Add the event to the activeEvents array
                        filteredResults[i].description = event.description;
                        filteredResults[i].descriptionLocale = event.descriptionLocale;
                        filteredResults[i].descriptionFallback = event.descriptionFallback;
                        filteredResults[i].eventIconURL = event.eventIconURL;
                        activeEvents.push(filteredResults[i]);
                    }
                }
            }

        }

        return activeEvents;

    });

    return result;

}



/**
 * Fetches a single event by its ID from the events list from WoWHead.
 *
 * @param  {Int8Array}     id          The event ID.
 * @param  {String}        [locale]    The desired locale of the results, e.g. "de", "en", "es".
 * 
 * @return {Promise<Event>}                   Returns an event object.
 * 
 * @author RootK1d
 * @since  2.3.0
 * @type   {Event}
 */

async function getEvent(id, locale) {

    //If no id is provided, throw error

    if (!id) console.throw("No Event ID was provided.")

    // If no locale is provided, default to "en"
    if (!locale) locale = "en";

    let event = scrapeEvents(locale).then(async (result) => {

        //Filter out the event by ID

        let filteredResults = result.filter((event) => {
            return event.id === id;
        });

        // Get the event data
        let event = await getEventData(locale, filteredResults[0].id)

        // Add the event data to the event object
        filteredResults[0].description = event.description;
        filteredResults[0].descriptionLocale = event.descriptionLocale;
        filteredResults[0].descriptionFallback = event.descriptionFallback;
        filteredResults[0].eventIconURL = event.eventIconURL;

        return filteredResults[0];
    });

    return event;

}

I kind of feel like there are things i can do better regarding the things mentioned above and things i can do better to give possible contributors the best possible experience when working on this package source code.

I really hope some of you have great suggestions, i am open to any kind of feedback on how i can make this project “more professional”.

Thanks in advance to anyone investing their time to give me feedback.

Issue in Creating Dynamic URL in custom wordpress plugin

I am facing issues in creating dynamic URLs in my custom plugin, which uses an API to fetch details about each post office by searching through pincodes and location names

Here is the URL: https://local.webrigo.com/pincode/

When it shows the result, the URL will automatically change, but when I use this URL, like https://local.webrigo.com/pincode/110045, separately in my browser, it leads me to a 404 page or redirects me to the homepage.

<?php
// File: shortcode-functions.php

function pincode_search_form() {
    ob_start(); ?>

    <style>
        .pincode-search-form {
            max-width: 600px;
            margin: 0 auto;
        }

        .pincode-results-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
        }

        .pincode-result {
            width: 48%;
            margin: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            color: black;
            box-sizing: border-box;
        }
    </style>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            document.getElementById('pincode-search-form').addEventListener('submit', function (event) {
                event.preventDefault();

                var pincode = document.getElementById('pincode').value;

                var newUrl = '<?php echo esc_url(home_url('/pincode/')); ?>';

                if (pincode) {
                    newUrl += encodeURIComponent(pincode);
                }

                history.pushState({ pincode: pincode }, null, newUrl);

                // Perform AJAX request
                fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'action=handle_pincode_search&pincode=' + encodeURIComponent(pincode),
                })
                    .then(response => response.text())
                    .then(html => {
                        document.querySelector('.pincode-results-container').innerHTML = html;
                    })
                    .catch(error => console.error('Error:', error));
            });

            document.getElementById('post-office-search-form').addEventListener('submit', function (event) {
                event.preventDefault();

                var postOfficeName = document.getElementById('post-office-name').value;

                var newUrl = '<?php echo esc_url(home_url('/postoffice/')); ?>';

                if (postOfficeName) {
                    newUrl += encodeURIComponent(postOfficeName);
                }

                history.pushState({ postOfficeName: postOfficeName }, null, newUrl);

                // Perform AJAX request
                fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'action=handle_post_office_search&postoffice=' + encodeURIComponent(postOfficeName),
                })
                    .then(response => response.text())
                    .then(html => {
                        document.querySelector('.pincode-results-container').innerHTML = html;
                    })
                    .catch(error => console.error('Error:', error));
            });
        });
    </script>

    <div class="pincode-search-form">
        <form id="pincode-search-form">
            <label for="pincode">Enter PINCODE:</label>
            <input type="text" name="pincode" id="pincode">
            <input type="submit" value="Search">
        </form>

        <form id="post-office-search-form">
            <label for="post-office-name">Enter Post Office Name:</label>
            <input type="text" name="post-office-name" id="post-office-name">
            <input type="submit" value="Search">
        </form>

        <div class="pincode-results-container">
            <!-- Results will be displayed here -->
        </div>
    </div>

    <?php
    return ob_get_clean();
}

add_shortcode('pincode_search', 'pincode_search_form');

add_action('wp_ajax_handle_pincode_search', 'handle_pincode_search');
add_action('wp_ajax_nopriv_handle_pincode_search', 'handle_pincode_search');

add_action('wp_ajax_handle_post_office_search', 'handle_post_office_search');
add_action('wp_ajax_nopriv_handle_post_office_search', 'handle_post_office_search');

function handle_pincode_search() {
    if (isset($_POST['pincode'])) {
        $pincode = sanitize_text_field($_POST['pincode']);
        display_pincode_result($pincode);
    }

    wp_die();
}

function handle_post_office_search() {
    if (isset($_POST['postoffice'])) {
        $postOfficeName = sanitize_text_field($_POST['postoffice']);
        display_post_office_result($postOfficeName);
    }

    wp_die();
}

function display_pincode_result($pincode) {
    // Code to fetch and display pincode results
    $api_url = 'https://api.postalpincode.in/pincode/' . rawurlencode($pincode) . '/';
    $response = wp_remote_get($api_url);

    if (!is_wp_error($response) && $response['response']['code'] === 200) {
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if ($data && $data[0]['Status'] === 'Success' && isset($data[0]['PostOffice'])) {
            $post_offices = $data[0]['PostOffice'];

            foreach ($post_offices as $post_office) {
                ?>
                <div class="pincode-result">
                    <h3>Pincode Information for <?php echo esc_html($pincode); ?></h3>
                    <ul>
                        <li>
                            <strong>Post Office Name:</strong> <?php echo esc_html($post_office['Name']); ?><br>
                            <strong>Branch Type:</strong> <?php echo esc_html($post_office['BranchType']); ?><br>
                            <strong>Delivery Status:</strong> <?php echo esc_html($post_office['DeliveryStatus']); ?><br>
                            <!-- Add more fields as needed -->
                        </li>
                    </ul>
                </div>
                <?php
            }
        } else {
            echo '<div class="pincode-results">Error fetching pincode information. Debug info: ' . print_r($data, true) . '</div>';
        }
    } else {
        echo '<div class="pincode-results">Error fetching pincode information. Debug info: ' . print_r($response, true) . '</div>';
    }
}

function display_post_office_result($postOfficeName) {
    // Code to fetch and display post office results based on the API
    $api_url = 'https://api.postalpincode.in/postoffice/' . rawurlencode($postOfficeName) . '/';
    $response = wp_remote_get($api_url);

    if (!is_wp_error($response) && $response['response']['code'] === 200) {
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if ($data && $data[0]['Status'] === 'Success' && isset($data[0]['PostOffice'])) {
            $post_office = $data[0]['PostOffice'][0];

            ?>
            <div class="pincode-result">
                <h3>Post Office Information for <?php echo esc_html($postOfficeName); ?></h3>
                <ul>
                    <li>
                        <strong>Post Office Name:</strong> <?php echo esc_html($post_office['Name']); ?><br>
                        <strong>Branch Type:</strong> <?php echo esc_html($post_office['BranchType']); ?><br>
                        <strong>Delivery Status:</strong> <?php echo esc_html($post_office['DeliveryStatus']); ?><br>
                        <!-- Add more fields as needed -->
                    </li>
                </ul>
            </div>
            <?php
        } else {
            echo '<div class="pincode-results">Error fetching post office information. Debug info: ' . print_r($data, true) . '</div>';
        }
    } else {
        echo '<div class="pincode-results">Error fetching post office information. Debug info: ' . print_r($response, true) . '</div>';
    }
}

I have already verified the .htaccess file and updated permalinks again, but the issue exists. My main objective is to achieve dynamic links for ranking purposes on SERP for each URL separately.

How can I remove lines in html2pdf output caused by rowspan in table?

I have table that uses rowspan and colspan for converting/exporting to PDF. The colspan mostly works, but I have an issue with rowspan that have a line between <td> while exporting.

What should I change in the code to remove lines as below?

line html2pdf rowspan

<tr>
  <td style="letter-spacing:0.2px;font-size: 10px;" width="10%" rowspan="2" class="p-2 text-center fw-bold"> Test </td>
  <td style="letter-spacing:0.2px;font-size: 10px;" width="10%" colspan="2" class="p-2 text-center fw-bold">yes / no</td>
</tr>
<tr>
  <td style="letter-spacing:0.2px;font-size: 10px;" class="p-2 text-center fw-bold">Yes</td>
  <td style="letter-spacing:0.2px;font-size: 10px;" class="p-2 text-center fw-bold">No</td>
</tr>
var opt = {
  margin: [30, 10],
  filename: 'exported.pdf',
  image: {
    type: 'jpeg',
    quality: 0.98
  },
  html2canvas: {
    scale: 2,
    scrollX: 0,
    scrollY: 0,
    useCORS: true,
    dpi: 96,
    letterRendering: true
  },
  jsPDF: {
    unit: 'mm',
    format: 'a4',
    orientation: 'portrait'
  },
  pagebreak: {
    mode: ['avoid-all'],
  }
};

Css colors not loaded and touble making a div visible and invisible

I was taking a FreeCodeCamp project for JavaScript where I had to make a roman numerical converter, but unfortunately I have a couple issues:

  1. Some CSS codes do not load such as margin colors and the background linear-gradient color.
  2. The container that has the expected result that i want to make invisible at first and then invisible after the user input doesn’t work as intended.

I think i made a big logical mistake but I just can’t seem to find it.

Thank you for taking your time reviewing my code, English isn’t my native language so I hope I made myself clear.

Here is all my code so far:

const numberInput = document.getElementById("input");
const convertButton = document.getElementById("convert");
const output = document.getElementById("result");

const romanNumbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const romanLetters = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];

function convertToRoman(number) {

  if (number === 0) {
    output.textContent = "Roman numerals do not represent zero.";
    return;
  }

  if (isNaN(number) || number < 1 || number > 3999) {
    const errorMessage = number < 1 ? "Please enter a number greater than or equal to 1." :
      number > 3999 ? "Please enter a number less than or equal to 3999." :
      "Please enter a valid number.";
    output.textContent = errorMessage;
    return;
  }

  let roman = "";
  for (let i = 0; i < romanNumbers.length; i++) {
    while (number >= romanNumbers[i]) {
      roman += romanLetters[i];
      number -= romanNumbers[i];
    }
  }
  output.textContent = roman;
  output.parentElement.style.visibility = "visible";
}

convertButton.addEventListener("click", function(event) {
  event.preventDefault(); // Prevent form submission (optional)
  const enteredNumber = parseInt(numberInput.value);
  convertToRoman(enteredNumber);
  // Clear previous output on new conversion (optional):
  // output.textContent = ""; // Uncomment if you prefer to clear the output
});
html {
  height: 100%;
  width: 100%;
}

body {
  margin: 0;
  padding: 0;
  font-family: Rubik, Robot, open sans, sans-serif;
  background-color: linear-gradient(to top right, #00AAFF, #00FF6C);
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 10px solid black;
  padding: 10px;
  border-radius: 10px;
}

#numberForm {
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.hidden {
  visibility: invisible;
}
<div class="container">
  <h1>Roman Numeral Converter</h1>
  <h3>Made by Yazzine</h3>
</div>

<div class="container">
  <form id="numberForm">
    <p>Enter a number between 1 and 3999:</p>
    <div>
      <input type="number" id="input" placeholder="Your number">
      <button type="submit" id="convert">Convert</button>
    </div>
  </form>
</div>

<div class="container hidden" id="result-container">
  <p>Roman Numeral: <span id="result"></span></p>
</div>

ReferenceError: sap is not defined, debugger does not start in VS Code

VS Code Version: 1.86.2 (user setup)
Electron: 27.2.3
Chromium: 118.0.5993.159
Node.js: 18.17.1
V8: 11.8.172.18-electron.0
OS: Windows_NT x64 10.0.22631

I am trying to use the node.js debugger in vs code with a sap ui5 project and it does not start.

Debugger attached.
Waiting for the debugger to disconnect…
C:Users…VS ProjectsHello WorldwebappcontrollerHelloPanel.controller.js:1
sap.ui.define([
^

ReferenceError: sap is not defined
at Object. (C:Users…VS ProjectsHello WorldwebappcontrollerHelloPanel.controller.js:1:1)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
at Module.load (node:internal/modules/cjs/loader:1207:32)
at Module._load (node:internal/modules/cjs/loader:1023:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
at node:internal/main/run_main_module:28:49

What would be the problem?

.vscode launch.json:

“version”: “0.2.0”,
“configurations”: [

    {
        "type": "node",
        "request": "launch",
        "name": "Launch Program",
        "console": "integratedTerminal",

        "skipFiles": [
            "<node_internals>/**"
        ],
        "trace": true,
        "program": "${workspaceFolder}\webapp\controller\MainView.controller.js"
    }
]

index.html

    id="sap-ui-bootstrap"
    src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
    data-sap-ui-theme="sap_fiori_3"
    data-sap-ui-libs="sap.m"
    data-sap-ui-resourceroots='{
        ...
    }'
    data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
    data-sap-ui-compatVersion="edge"
    data-sap-ui-async="true"
    data-sap-ui-frameOptions="trusted"

ui5.yaml

framework:
name: OpenUI5
version: 1.108.0
libraries:
– name: sap.ui.core
– name: sap.m
– name: sap.ui.layout
– name: themelib_sap_horizon

manifest.json

“sap.ui”: {
“technology”: “UI5”,

“sap.ui5”: {
“flexEnabled”: true,
“dependencies”: {
“minUI5Version”: “1.102.0”,
“libs”: {
“sap.m”: {},
“sap.ui.core”: {}
}
},

.disabled not working for me when trying to disable a button

First of all I am extremely new to HTML, CSS and Javascript (Literally started yesterday) but I have some programming experience. I have looked everywhere and everyone says to use “objectname.disabled = true;” but in my project it doesn’t work. Even when asking ChatGTP it says “Huh… should work lol”. Pls help me out here!

My Code: (I do have a css file however it should not affect .disabled not working so I will not add it here. I will after the fact if deemed necessary though.)

document.addEventListener('DOMContentLoaded', function() {
    var atom_amount = 0;
    var matter_btn = document.getElementById('matter_btn');
    var matter_amount = 0;
    var matter_cost = 10;

    document.getElementById('atoms_btn').onclick = function() {
        atom_amount++
        document.getElementById('atoms_txt').innerHTML = "Atoms: " + atom_amount
        if (atom_amount < matter_cost) {
            matter_btn.disabled = true;
        }
        else {
            matter_btn.disabled = false;
        }
    };

    document.getElementById('matter_btn').onclick = function() {
        atom_amount = atom_amount - matter_cost
        document.getElementById('atoms_txt').innerHTML = "Atoms: " + atom_amount
        matter_amount++
        matter_cost = matter_cost + (2 * matter_amount)
        document.getElementById('matter_txt').innerHTML = "Matter: " + matter_amount
    };
});
<!DOCTYPE html>
<html>
    <head>
        <title>From Scratch</title>
        <link rel="stylesheet" href="css/Style.css">
        <script src="js/main.js"></script>
    </head>
    <body>
        <game_name class="game_title">From Scratch</game_name>
        <shape class="resource_area"></shape>
        <resources_info class="text resources_text">Resources:</resources_info>
        <shape class="divider"></shape>
        <atoms id="atoms_txt" class="text atoms_amount">Atoms: 0</atoms>
        <atoms_button id="atoms_btn" class="button atoms_button">Create Atoms</atoms_button>
        <matter id="matter_txt" class="text matter_amount">Matter: 0</matter>
        <matter_button id="matter_btn" class="button matter_button">Create Matter</matter_button>
    </body>
</html>

I have created a test file and tried .disabled and lo and behold it worked! However as soon as I went back to my main file it did again not work so I am extremely confused.

All I want is for my button to be disabled when certain conditions are met and to be reenabled when those conditions are not met.

How to properly use IntersectionObserver to track the intersection of multiple targets inside the root

enter image description here

I have two blocks inside the root block as shown in the picture. I can move both of these blocks. How to correctly use IntersectionObserver to track when one block intersects another?

The standard use of IntersectionObserver involves tracking the target’s intersection with the root. I need to track the intersection of targets with each other.

Add options to select in Preline

I have an issue with Preline UI, I am trying to use the advanced select.
I have this html:

<div class="relative">
                    <select multiple data-hs-select='{
                      "placeholder": "Select multiple options...",
                      "toggleTag": "<button type="button"></button>",
                      "toggleClasses": "hs-select-disabled:pointer-events-none hs-select-disabled:opacity-50 relative py-3 px-4 pe-9 flex text-nowrap w-full cursor-pointer bg-white border border-gray-200 rounded-lg text-start text-sm focus:border-blue-500 focus:ring-blue-500 before:absolute before:inset-0 before:z-[1] dark:bg-slate-900 dark:border-gray-700 dark:text-gray-400 dark:focus:outline-none dark:focus:ring-1 dark:focus:ring-gray-600",
                      "dropdownClasses": "mt-2 z-50 w-full max-h-72 p-1 space-y-0.5 bg-white border border-gray-200 rounded-lg overflow-hidden overflow-y-auto dark:bg-slate-900 dark:border-gray-700",
                      "optionClasses": "py-2 px-4 w-full text-sm text-gray-800 cursor-pointer hover:bg-gray-100 rounded-lg focus:outline-none focus:bg-gray-100 dark:bg-slate-900 dark:hover:bg-slate-800 dark:text-gray-200 dark:focus:bg-slate-800",
                      "optionTemplate": "<div class="flex justify-between items-center w-full"><span data-title></span><span class="hidden hs-selected:block"><svg class="flex-shrink-0 size-3.5 text-blue-600 dark:text-blue-500" xmlns="http:.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span></div>"
                    }' class="hidden" id="copyProfileProductSelect">
                        
                    </select>

                    <div class="absolute top-1/2 end-3 -translate-y-1/2">
                        <svg class="flex-shrink-0 size-3.5 text-gray-500 dark:text-gray-500" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 15 5 5 5-5"/><path d="m7 9 5-5 5 5"/></svg>
                    </div>
                </div>

That is the select itself, which seems to be working fine.
But I need to be able to dynamically add options depending on other factors in my code.

So i have this js :

const select = window.HSSelect.getInstance(document.getElementById("copyProfileProductSelect"), true);
            // select.clear();
            console.log("select instance", select);
            // Add products to select
            products.forEach(product => {
                select.addOption([
                {
                    title: product.name,
                    val: product.id
                }]);
            })

Which according to the docs on preline https://preline.co/plugins/html/advanced-select.html
Should add an option to the select.

But I keep getting
‘select.addOption is not a function’

Anybody have any tips or insight?

How to get the mouse pointer position when onScroll is called?

I have handleScroll callback

<div  onScroll={handleScroll} >

And handleScroll is called when mouse whell is touched.

const handleScroll = (e) =>{
    console.log("handlescroll clientX",e.clientX);
    console.log("handlescroll clientY",e.clientY);

However it doesn’t have mouse poitner position.

So, I think there are two methods.

1 Get the mouse pointer position in scroll callback

2 Get the mouse pointer potition by spontaneously (not by callback)

Either way is possible?

ReactJS Select-box optgroup with dynamic data

I want to display JSON data to my select box. My JSON Data is

const myDaya = [
  { mainGroup: '', label: 'My Option1', value: 'DNAC' },
  { mainGroup: '', label: 'My Option2', value: 'DNACNC' },
  { mainGroup: 'Group1', label: 'Group1 Option1', value: 'LICENSE-ENRICHED' },
  { mainGroup: 'Group1', label: 'Group1 Option2', value: 'LICENSE-ENRICHED' },
  { mainGroup: 'Group1', label: 'Group1 Option3', value: 'LICENSE-ENRICHED' },
  { mainGroup: '', label: 'My Option3', value: 'COLLAB' },
  { mainGroup: '', label: 'My Option4', value: 'COLLAB' },
  { mainGroup: '', label: 'My Option5', value: 'COLLAB' },
  { mainGroup: '', label: 'My Option6', value: 'COLLAB' },
  { mainGroup: '', label: 'My Option7', value: 'COLLAB' },
]

From above data I am rendering options in select-box using below code:

<select>   
<option value=''>Please select</option>
{myDaya .map((option: { mainGroup:string; value: string; label: string }) => (
<optgroup label={option.mainGroup}>
    <option key={option.value} value={option.value}>
    {option.label}
    </option>
</optgroup>
))}
</select>

From above code select-box looks like:

enter image description here

But I want to show Group1 Option1, Group1 Option2, Group1 Option3 under Group1 & for other options mainGroup is blank so it should not show blank space in Select-box.