Using IntersectionObserver to detect scrolling below a target – and keeping it until next target comes into view

Using IntersectionObserver – is it possible to detect scroll intersecting AND past/below every entry – until the next entry comes is scrolled into view (other elements are between the entries.)?

In the example below, I would like to detect scrolling below every element with the class .title, and keep it until the next element with the class .title appears.

I tried with the below, but it doesnt’t work as expected.

Hope my questions makes sense. 🙂

let options = {
    root: null,
    rootMargin: '-50px 0px -50px 0px',
    threshold: [.5]
}

let sectionObserver = new IntersectionObserver((entries, options) => {
    entries.forEach((entry) => {
        if (entry.isIntersecting && window.scrollY >= entry.boundingClientRect.top) {
            // Do something here when scrolling below this entry - until next entry is in view.
            console.log(entry.target);
        }
    });
});

document.querySelectorAll('.title').forEach((section) => {
    sectionObserver.observe(section);
});
<div class="container">
  <div class="title">Title one</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus dolor id ullamcorper tempor. Donec ut
    ullamcorper tellus. Etiam vel rhoncus urna. Aenean augue nulla, congue a orci at, imperdiet vehicula eros. Aenean
    ornare nibh ut leo faucibus fringilla. Quisque varius ut ipsum egestas feugiat. Mauris id nisl ultrices, consectetur
    mauris in, consectetur mi. Sed sit amet dolor urna. Nullam nec enim gravida, pulvinar lacus ut, volutpat nibh.
    Quisque commodo eu tortor ac dictum. Vivamus sodales risus sed blandit vulputate. Proin elit erat, varius non
    tincidunt ut, semper sed erat. Nulla vehicula vitae nisl nec dignissim. Curabitur viverra risus eu est pellentesque
    lobortis. Nullam egestas semper convallis.

    Ut ac blandit risus, sit amet elementum ex. Donec rhoncus augue eu cursus consequat. Duis a sapien sit amet elit
    aliquet molestie. Mauris nec ligula viverra, ornare dolor vel, malesuada nisl. Proin gravida dolor justo, sit amet
    tempus justo consectetur ut. Aenean malesuada iaculis tortor ac varius. Phasellus ultrices purus nisi, eu rutrum
    felis bibendum id. Phasellus enim dui, ultrices sed massa vel, euismod bibendum eros. Duis quis auctor augue, eget
    pellentesque velit. In a est at neque dignissim pellentesque et tempus sem. Nulla et leo diam.
  </p>
  <div class="title">Title two</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus dolor id ullamcorper tempor. Donec ut
    ullamcorper tellus. Etiam vel rhoncus urna. Aenean augue nulla, congue a orci at, imperdiet vehicula eros. Aenean
    ornare nibh ut leo faucibus fringilla. Quisque varius ut ipsum egestas feugiat. Mauris id nisl ultrices, consectetur
    mauris in, consectetur mi. Sed sit amet dolor urna. Nullam nec enim gravida, pulvinar lacus ut, volutpat nibh.
    Quisque commodo eu tortor ac dictum. Vivamus sodales risus sed blandit vulputate. Proin elit erat, varius non
    tincidunt ut, semper sed erat. Nulla vehicula vitae nisl nec dignissim. Curabitur viverra risus eu est pellentesque
    lobortis. Nullam egestas semper convallis.

    Ut ac blandit risus, sit amet elementum ex. Donec rhoncus augue eu cursus consequat. Duis a sapien sit amet elit
    aliquet molestie. Mauris nec ligula viverra, ornare dolor vel, malesuada nisl. Proin gravida dolor justo, sit amet
    tempus justo consectetur ut. Aenean malesuada iaculis tortor ac varius. Phasellus ultrices purus nisi, eu rutrum
    felis bibendum id. Phasellus enim dui, ultrices sed massa vel, euismod bibendum eros. Duis quis auctor augue, eget
    pellentesque velit. In a est at neque dignissim pellentesque et tempus sem. Nulla et leo diam.
  </p>
  <div class="title">Title three</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus dolor id ullamcorper tempor. Donec ut
    ullamcorper tellus. Etiam vel rhoncus urna. Aenean augue nulla, congue a orci at, imperdiet vehicula eros. Aenean
    ornare nibh ut leo faucibus fringilla. Quisque varius ut ipsum egestas feugiat. Mauris id nisl ultrices, consectetur
    mauris in, consectetur mi. Sed sit amet dolor urna. Nullam nec enim gravida, pulvinar lacus ut, volutpat nibh.
    Quisque commodo eu tortor ac dictum. Vivamus sodales risus sed blandit vulputate. Proin elit erat, varius non
    tincidunt ut, semper sed erat. Nulla vehicula vitae nisl nec dignissim. Curabitur viverra risus eu est pellentesque
    lobortis. Nullam egestas semper convallis.

    Ut ac blandit risus, sit amet elementum ex. Donec rhoncus augue eu cursus consequat. Duis a sapien sit amet elit
    aliquet molestie. Mauris nec ligula viverra, ornare dolor vel, malesuada nisl. Proin gravida dolor justo, sit amet
    tempus justo consectetur ut. Aenean malesuada iaculis tortor ac varius. Phasellus ultrices purus nisi, eu rutrum
    felis bibendum id. Phasellus enim dui, ultrices sed massa vel, euismod bibendum eros. Duis quis auctor augue, eget
    pellentesque velit. In a est at neque dignissim pellentesque et tempus sem. Nulla et leo diam.
  </p>
  <div class="title">Title four</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus dolor id ullamcorper tempor. Donec ut
    ullamcorper tellus. Etiam vel rhoncus urna. Aenean augue nulla, congue a orci at, imperdiet vehicula eros. Aenean
    ornare nibh ut leo faucibus fringilla. Quisque varius ut ipsum egestas feugiat. Mauris id nisl ultrices, consectetur
    mauris in, consectetur mi. Sed sit amet dolor urna. Nullam nec enim gravida, pulvinar lacus ut, volutpat nibh.
    Quisque commodo eu tortor ac dictum. Vivamus sodales risus sed blandit vulputate. Proin elit erat, varius non
    tincidunt ut, semper sed erat. Nulla vehicula vitae nisl nec dignissim. Curabitur viverra risus eu est pellentesque
    lobortis. Nullam egestas semper convallis.

    Ut ac blandit risus, sit amet elementum ex. Donec rhoncus augue eu cursus consequat. Duis a sapien sit amet elit
    aliquet molestie. Mauris nec ligula viverra, ornare dolor vel, malesuada nisl. Proin gravida dolor justo, sit amet
    tempus justo consectetur ut. Aenean malesuada iaculis tortor ac varius. Phasellus ultrices purus nisi, eu rutrum
    felis bibendum id. Phasellus enim dui, ultrices sed massa vel, euismod bibendum eros. Duis quis auctor augue, eget
    pellentesque velit. In a est at neque dignissim pellentesque et tempus sem. Nulla et leo diam.
  </p>
  <div class="title">Title five</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus dolor id ullamcorper tempor.`enter code here`
    Donec ut ullamcorper tellus. Etiam vel rhoncus urna. Aenean augue nulla, congue a orci at, imperdiet vehicula eros.
    Aenean ornare nibh ut leo faucibus fringilla. Quisque varius ut ipsum egestas feugiat. Mauris id nisl ultrices,
    consectetur

    mauris in, consectetur mi. Sed sit amet dolor urna. Nullam nec enim gravida, pulvinar lacus ut, volutpat nibh.
    Quisque commodo eu tortor ac dictum. Vivamus sodales risus sed blandit vulputate. Proin elit erat, varius non
    tincidunt ut, semper sed erat. Nulla vehicula vitae nisl nec dignissim. Curabitur viverra risus eu est pellentesque
    lobortis. Nullam egestas semper convallis.

    Ut ac blandit risus, sit amet elementum ex. Donec rhoncus augue eu cursus consequat. Duis a sapien sit amet elit
    aliquet molestie. Mauris nec ligula viverra, ornare dolor vel, malesuada nisl. Proin gravida dolor justo, sit amet
    tempus justo consectetur ut. Aenean malesuada iaculis tortor ac varius. Phasellus ultrices purus nisi, eu rutrum
    felis bibendum id. Phasellus enim dui, ultrices sed massa vel, euismod bibendum eros. Duis quis auctor augue, eget
    pellentesque velit. In a est at neque dignissim pellentesque et tem

    pus sem. Nulla et leo diam.
  </p>
</div>

Can’t link javascript file to HTML

I am working on a new computer and refreshing coding. I’m having some trouble linking my script.js file to the index.html. I’ve tried everything and can’t figure out what the problem is.

I have checked for typos and have placed the script file in different areas of the code.
enter image description here

show video after completing gravity form

I have a page with a button. When the user clicks on the button, a pop-up should open and he should enter his contact number using gravity form and then the video will be shown to him.
Now I have a button on the page and an html element that displays the video through the iframe tag, and the default mode is display: none.

function custom_script() {
        ?>
        <script type="text/javascript">
      document.addEventListener('DOMContentLoaded', function () {
        // Event listener for form submission
        jQuery(document).on('gform_confirmation_loaded', function(event, formId){
            // Check if the submitted form is the one with ID 1
            if (formId == 1) {
                // Show the video element with ID 'wb-video'
                document.getElementById('wb-video').style.display = 'block';
            }
        });
    });
    
        </script>
        <?php
    }
    add_action('wp_footer', 'custom_script');

I put this code at the end of the functions.php file. But after the user completes the form, nothing happens on the page. The video is not displayed.
Thank you if you guide me.

Retrieving Variable Values with AJAX

I want to create a feature on a specific section of my custom template’s category page that allows users to sort the displayed cards in any order they prefer.

To achieve this, I’ve started by placing the following simple HTML code on the category.php page:

   <select id="bodyBTN_select_sort">
     <option id="Newest_mode_sort" value="selectNewest">Newest</option>
     <option id="Oldest_mode_sort" value="selectOldest">Oldest</option>
     <option id="MostViewed_mode_sort" value="selectMostViewed">Most Viewed</option>
     <option id="LeastViewed_mode_sort" value="selectLeastViewed">Least Viewed</option>
     <option id="Random_mode_sort" value="selectRandom">Random!</option>
   </select>

Now, I want the following paths to load on the page whenever a user selects one of the options:

<?php get_template_part('templates/archive-category-tag/sort-by_card/newest_theme'); ?>;

<?php get_template_part('templates/archive-category-tag/sort-by_card/oldest_theme'); ?>;

<?php get_template_part('templates/archive-category-tag/sort-by_card/most-viewed_theme'); ?>;

<?php get_template_part('templates/archive-category-tag/sort-by_card/least-viewed_theme'); ?>;

<?php get_template_part('templates/archive-category-tag/sort-by_card/random_theme'); ?>;

The only thing left to do is to use jQuery to get the user’s selected options and insert the corresponding path into the page.
Since my paths are in PHP and follow WordPress functions, I can’t directly insert them into the page using JavaScript. Therefore, I need to send the selected items to the server and a specific file for processing using AJAX.

For this purpose, I wrote the following jQuery code in a separate file:

$(document).ready(function() {
  let value_result = "selectNewest"; // The default value

  // Function to send data to PHP file
  function sendDataToPHP(value) {
    console.log('Request sent : ' + value);
      $.ajax({
          url: '/site/wp-content/themes/theme-pro/templates/functions/template/category_functions.php',
          type: 'POST',
          data: { sort_by: value },
          success: function(response) {
            // Check the content of the answer
            console.log('Server response :', response);

            // Replace element content with response
            $('#card_path_category').html(response);

             // Check for errors
            // if ($('#HNSC_card_path_category').html() === '') {
            //     console.error('The content of the element was not updated.');
            // }
          }
      });
  }

  // Change event function
  $('#bodyBTN_select_sort').change(function() {
      value_result = $(this).val();
      sendDataToPHP(value_result);
      console.log('Selected value :' + value_result);
  });

  // Send initial data
  sendDataToPHP(value_result);

  // Set the default option
  $('#Newest_mode_sort').prop('selected', true);
});

Now, I need to create a file named category_functions.php in the specified path (this file is essentially the separated codes from the functions.php file); and then receive the value sent from AJAX and insert the appropriate path into the page based on the user’s selection.

For this purpose, I placed the following code inside the category_functions.php file:

  function get_template_part_by_sort() {

    // Get the value sent via AJAX
      $sort_by = isset($_POST['sort_by']) ? $_POST['sort_by'] : 'selectNewest';
    
     // Check and display the received value for debugging
      var_dump($sort_by);
    
    
         // Check the value and determine the address
         switch ($sort_by) {
          case 'selectNewest':
              get_template_part('templates/archive-category-tag/sort-by_card/newest_theme');
              break;
          case 'selectOldest':
              get_template_part('templates/archive-category-tag/sort-by_card/oldest_theme');
              break;
          case 'selectMostViewed':
              get_template_part('templates/archive-category-tag/sort-by_card/most-viewed_theme');
              break;
          case 'selectLeastViewed':
              get_template_part('templates/archive-category-tag/sort-by_card/least-viewed_theme');
              break;
          case 'selectRandom':
              get_template_part('templates/archive-category-tag/sort_by_card/random_theme');
              break;
          default:
              // If the value passed is invalid, the default path is inserted.
              get_template_part('templates/archive-category-tag/sort-by_card/newest_theme');
      }
    }

After completing all the above steps, it’s time to get the output.

In the output, I can successfully receive the default value and the path that should be received in case of missing or problematic input, and the cards are sorted accordingly.

However, when I select other options, I still receive the same default path!

To find the error, I first printed the output values of the script file in the browser console as follows:

When selecting the Random! option:

Selected value :selectRandom
Request sent : selectRandom
Server response : <empty string>

By displaying the above output, I realized that the PHP processing file is not sending anything!

To do this, I used var_dump($sort_by); to get an output from my PHP codes and it printed the following text on the page for me:

string(12) "selectNewest"

The above value is the default value and remains constant when changing the select box and does not react to the output at all!?

I don’t have much control over AJAX and this is the first time I’ve written such an AJAX code.

My main goal is just to put the specified paths on the page based on the user’s selection and I couldn’t think of any other solution except AJAX.

Please help me complete the code and get the correct response from the server if my solution to this problem is correct.
And if my solution is not good, please guide me on what I should do to achieve my goal.

Thank you in advance for any help.

Argument type match with rest parameter in type alias and its implementation

Newbie to TypeScript, and I’m confused about the folowing snippet:

type Fn = (...args: number[]) => void

const fn1: Fn = (x) => console.log(x);
const fn2: Fn = (x1, x2) => console.log(x1, x2);

fn1(2);
fn2(2, 4);

In my understanding, ...args is a rest parameter where indefinite number of arguments is allowed and you can access args as array, but its implementations fn1 and fn2 doesn’t implement with rest parameter or access it as array. fn1 only accept 1 argument, and fn2accept 2 arguments only.

Is this a specific feature of rest parameter in type keyword? If so, where can I find the specfication?

Please feel free to tell me if there’s anything unclear to you.

I expected the implementaion of Fn should be something like

const fn: Fn = (...x: number[]) => console.log(x);

having problems in very simple and basic typescript program

the code is look like this:

const num1: number[] = [12, 14, 18, 22, 24];
const findNum: number | undefined = num1.find(elem => elem === 12);
console.log(findNum);

and the error I’m facing is:

1.ts:2:42 - error TS2550: Property 'find' does not exist on type 'number[]'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.

2 const findNum: number | undefined = num1.find(elem => elem === 12);
                                           ~~~~

Found 1 error in 1.ts:2

the tsconfig:

{
  "compilerOptions": {
    "target": "es2016",
    "lib": ["es2015"],
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

I’m using typescript version 5.5.4 and I tried it in the online typescript playground there it’s working without error.

but in my mutcin, it’s not working I tried uninstall typescript and after install but it’s still not working.

bad habbit of using chatGpt? [closed]

Am I developing a bad habit of learning with ChatGpt?
Primarely I’m using ChatGpt for learning how something works, let’s say “what are the methods of defense that developer use from preventing the cyber attacks on his web site, and which dev role exactly should do that”…. “how does the web hosting work, what are CDN’s and in which cases there are better then some local hosting.” and so on.
I usually always tell him I don’t want to see code, just explanation of how something work and why is that better decision, lets say we are talking about the fetch and axios in js.

So I’m wondering do I developing a bad habit of making that so much simpler and quicker for me instead of just searching on the others forums and web articles on my own. The main problem with forums and web articles is there is soo much different opinions and sometimes its hard to me decide what is better, because I don’t have soo much experience at the moment.

How to Correctly Reset and Re-generate a Math Quiz in JavaScript?

I’m working on a simple math quiz application using JavaScript, where users have to solve randomly generated math problems. I’ve written a function to handle the quiz logic and user interactions, but I’m encountering a few issues with resetting and re-generating the quiz.

const randomQuiz = (function() {
const firstPara = document.querySelector(".firstNumber");
const operatorPara = document.querySelector(".operator");
const secondPara = document.querySelector(".secondNumber");
const buttonIt = document.querySelector(".answer");
const inputAnswer = document.querySelector(".textanswer");
const container = document.querySelector(".container");
const answerGet = document.querySelector(".asnwerGet");
const didit = document.querySelector(".didit");
let randomOperator = ["*", "+", "-", "/"];

const quastion = {
    firstNumber: Math.floor(Math.random() * 100),
    operator: randomOperator[Math.floor(Math.random() * randomOperator.length)],
    secondNumber: Math.floor(Math.random() * 100),
};

buttonIt.addEventListener("click", () => {
    firstPara.textContent = quastion.firstNumber;
    operatorPara.textContent = quastion.operator;
    secondPara.textContent = quastion.secondNumber;
    container.append(firstPara);
    container.append(operatorPara);
    container.append(secondPara);
});

answerGet.addEventListener("click", () => {
    const answer = calculation();
    if (inputAnswer.value == answer) {
        console.log(`You did it`);
        didit.textContent = `You did it! The answer is ${calculation()} !!!!!`;
        resetGame();
    } else {
        console.log(`Nice try`);
        console.log(`Answer is ${calculation()}`);
    }
});

function calculation() {
    if (quastion.operator === "-") {
        return quastion.firstNumber - quastion.secondNumber;
    } else if (quastion.operator === "*") {
        return quastion.firstNumber * quastion.secondNumber;
    } else if (quastion.operator === "+") {
        return quastion.firstNumber + quastion.secondNumber;
    } else if (quastion.operator === "/") {
        return +(quastion.firstNumber / quastion.secondNumber).toFixed(2);
    }
}
    
function resetGame() {
    firstPara.textContent = "";
    operatorPara.textContent = "";
    secondPara.textContent = "";    
    // Here should be a mechanism to generate a new question
}
})();

My goal is everytime i get correct answer quastion will reset automatically.
but i am always getting same quastion for some reason i think problem is at buttonIt function always appending same value but how will i converting them into random ones ?
I’m also using querySelector to select DOM elements and append them to the container, but I’d like to know if there’s a more efficient approach.
The calculation function correctly computes the result based on the operator, so I believe the core logic is functioning as expected.
Thank you!
I’ve cleared the text content of the display elements, but this does not automatically generate new question values.
I tried adding new random values directly inside the resetGame function but need advice on integrating this properly.
Any suggestions or improvements to address these issues would be greatly appreciated!

How to use a string in javascript function

I have a button

onclick="click(' . $item . ');"

then the javascript function is supposed to pass $item to another page. It works fine if $item is a number, but not if it’s a string, and sometimes it’s a mix of characters and numbers which I can’t control.

function click(c)
{
var u = "items.php?serial=" + c;
document.location.href = u;
}

Is there a way to do this in JS?

After Register Confirmation Popup Script with RegisterStartupScript, Multiple Times Method Calling

The below picture shows the page developed in C#, This page contains some form elements text box, data table and buttons.

Error Case:
The user goes the another page (mostly time this is a classing list page) and redirect again to this form page. After that, user filling the form again and click any button.

In this scenario, GetStateFromUI trigger multiple times(with old form values and current filled form values therefore API trigger two times )

-> In addition to that, If user send forms one time(everything works), and again a second(current form and old form send to getstatefromui) and again third times multiple api calling(old forms and current form sending to the same getstatefromui method.).

Note: The users authenticate to application and filling form elements,after that click the any buttons. In this case everything works fine. API trigger one times.

I debugged it but I couldn’t catch error case when I try everytime api trigger one times. Everything works fine. Why this error happens? Somehow, users register more than one script and when one is triggered, the others are triggered as well but I can not prove it because I can not catch this error.

I am suspicious, this error’s reason is script registration. but I can not sure. I am thinking changing popup structure with no using script registration.

enter image description here

In Demo.aspx:

// Panel & TextBox & Datatable definitions and then buttons ...
<asp:button id="btn1" runat="server" Text="btn1" OnClick="btn1_Click" />
<asp:button id="btn2" runat="server" Text="btn1" OnClick="btn2_Click" />
<asp:button id="btn3" runat="server" Text="btn1" OnClick="btn3_Click" />
<asp:HiddenField ID="hdnButton1ConfirmCheck" />
<asp:HiddenField ID="hdnButton2ConfirmCheck" />
<asp:HiddenField ID="hdnButton3ConfirmCheck" />

<script type="text/javascript"> 
    ...
    if(data == 'Button1StartPopup') {
      $hdnButton1ConfirmCheck.setValue('Button1Confirm');
      __doPostBack('Button1StartPopup', '');
    }
    if(data == 'Button2StartPopup') {
      $hdnButton2ConfirmCheck.setValue('Button2Confirm');
      __doPostBack('Button2StartPopup', '');
    }
    if(data == 'Button3StartPopup') {
      $hdnButton3ConfirmCheck.setValue('Button3Confirm');
      __doPostBack('Button3StartPopup', '');
    }
    ...
</script>

In Demo.aspx.cs

public override void GetStateFromUI() {

string eventTarget = Request.Form["__EVENTTARGET"];
 if(eventTarget == "Button1StartPopup") {
      MyButton1Method();
 }

 if(eventTarget == "Button2StartPopup") {
      MyButton2Method();
 }

 if(eventTarget == "Button3StartPopup") {
       MyButton3Method();
 } 
}

privte void Button1Method(){
   if(!string.Equals(hdnButton1ConfirmCheck.Value, "Button1Confirm")) return;
   hdnButton1ConfirmCheck.Value = string.Empty;

   var request = new DemoRequestForButton1();
   var response = DemoServer.demoApi(request);
   if(response?.header != null && response?.header.Success) {
     ClientScript.RegisterStartupScript(Page.GetType(),"SuccessScript", "alert("Operation 
     Success");", true);
   } else {
      ClientScript.RegisterStartupScript(Page.GetType(),"FailedScript", "alert("Operation 
    Failed");", true);
    }
 }

 private void Button2Method(){
    if(!string.Equals(hdnButton2ConfirmCheck.Value, "Button2Confirm")) return;
    hdnButton2ConfirmCheck.Value = string.Empty;

    var request = new DemoRequestForButton2();
    var response = DemoServer.demoApi(request);
    if(response?.header != null && response?.header.Success) {
    ClientScript.RegisterStartupScript(Page.GetType(),"SuccessScript", "alert("Operation 
     Success");", true);
  } else {
   ClientScript.RegisterStartupScript(Page.GetType(),"FailedScript", "alert("Operation 
   Failed");", true);
  }
 }

  private void Button3Method(){
      if(!string.Equals(hdnButton3ConfirmCheck.Value, "Button3Confirm")) return;
      hdnButton3ConfirmCheck.Value = string.Empty;

       var request = new DemoRequestForButton3();
       var response = DemoServer.demoApi(request);
       if(response?.header != null && response?.header.Success) {
       ClientScript.RegisterStartupScript(Page.GetType(),"SuccessScript", "alert("Operation 
       Success");", true);
   } else {
     ClientScript.RegisterStartupScript(Page.GetType(),"FailedScript", "alert("Operation 
     Failed");", true);
   }
  }

    protected void Btn1_Click(object sender, EventArgs e) {
        RegisterScriptForButtons("Is Buttons1 Operation Work Ok", "Button1StartPopup");
    }

    protected void Btn2_Click(object sender, EventArgs e) {
        RegisterScriptForButtons("Is Buttons2 Operation Work Ok", "Button2StartPopup");
    }


    protected void Btn3_Click(object sender, EventArgs e) {
        RegisterScriptForButtons("Is Buttons3 Operation Work Ok", "Button3StartPopup");
    }


    protected void RegisterScriptForButtons(string popupMessage, string data) {
       string script = string.Format("$(document).ready(function(){ -- small confirmation popup code in different framework   });", "Operation Result", popupMessage );
       ClientScript.RegisterStartupScript(Page.GetType(),"ButtonOperation",script, true);
    }

Why is the value returning undefined?

I’m trying to a chrome extension to track tweets that I type out and store them into a variable that can be displayed in the html code. However, each time I do a tweet there is just an undefined value.
Here is the code:

script.js

document.addEventListener('DOMContentLoaded', function() {
  const tweetButtonSelector   = 'div[data-testid="tweetButtonInline"]';
  const tweetTextareaSelector = 'div[aria-label="Tweet text"]';

  function trackTweet() {
    setTimeout(() => {
      const tweetTextarea = document.querySelector(tweetTextareaSelector);
      if (tweetTextarea) {
        const tweetInput = tweetTextarea.innerText;
        console.log('User is tweeting:', tweetInput);
        chrome.storage.local.set({
          tweetInput: tweetInput
        }, function() {
          console.log('Tweet content saved:', tweetInput);
        });
      }
    }, 500);
  }

  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
        mutation.addedNodes.forEach((node) => {
          if (node.querySelector && node.querySelector(tweetButtonSelector)) {
            const tweetButton = node.querySelector(tweetButtonSelector);
            tweetButton.addEventListener('click', trackTweet);
          }
        });
      }
    });
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true,
  });

  const tweetButton = document.querySelector(tweetButtonSelector);
  if (tweetButton) {
    tweetButton.addEventListener('click', trackTweet);
  }
});

popup.js

document.addEventListener('DOMContentLoaded', function () {
  chrome.storage.local.get(['tweetInput'], function (result) {
    console.log('Retrieved tweet content:', result.tweetInput);
    const tweetContent = document.getElementById('tweetContent');
    tweetContent.textContent = result.tweetInput || 'No tweet tracked yet.';
  });
});

hello.html

<!DOCTYPE html> 
<html> 
<head> 
    <title>Tweet Tracker</title> 
    <script src="script.js"></script>
    <script src="popup.js"></script>
</head> 
<body> 
    <p>Tweet Tracker</p>
    <input type="text" id="InputText" placeholder="Input Text">
    <button id="SubmitButton">Submit</button>
    <p id="output">a</p>
    <p id="tweetContent">No tweet tracked yet.</p> 
</body> 
</html>

manifest.json

{
  "manifest_version": 3,
  "name": "Tweet Tracker",
  "description": ".",
  "version": "1.0",
  "permissions": [
        "activeTab",
        "background",
    "scripting",
    "storage"
],
  "content_scripts": [
    {
      "matches": ["https://x.com/*"],
      "js": ["script.js"]
    }
  ],
  "host_permissions": [
    "https://x.com/*"
  ],
  "action": {
    "default_popup": "hello.html",
    "default_icon": "hello_extensions.png"
  }
}

I tried testing the code by putting in

chrome.storage.local.get('tweetInput', function(result) {
  console.log(result.tweetInput); 
});

and

chrome.storage.local.get(null, console.log)

in the console, but that also returned undefined.

how to add Polyfills in next js project

When I created a project in NestJS, I encountered different errors in different browsers. For example, I implemented a button that uses the microphone, and it works perfectly in Chrome but not in Brave. Can someone help me resolve this issue, possibly using polyfills?

Brython’s ‘set_loop_timeout’ not working within asynchronous code—any solutions?

While developing my code, I encountered an issue where the webpage becomes unresponsive and irrecoverable when an infinite loop is executed in async mode. While searching for a solution, I found a related discussion here. I tried applying the suggestions to my code, but it didn’t work as expected.

Here’s my code:

from browser import document, window, aio, console, timer

# Set loop timeout
timer.set_loop_timeout(10)

...

def processInput(event=None):
    global input_values
    # Clear previous output
    document["mainConsole"].innerHTML = ""
    # Execute the script
    aio.run(exec_script())

async def exec_script():
    try:
        ${solutiontext}  # This may include an infinite loop
    except BrythonNotRunningError:
        on_compile_done()
        return
    except Exception as e:
        print(f"Error: {e}")
    finally:
        on_compile_done()

processInput()

The problem is that when the solutiontext variable contains an infinite loop like while(1):, the entire webpage freezes. It seems that the set_loop_timeout(10) option doesn’t work within the asynchronous function exec_script().

Has anyone encountered this issue before? How can I prevent or handle infinite loops in asynchronous Brython code?