var variable reassignment within function

I don’t understand why a var variable can be reassigned within a function, but the change also applies outside of the function. Why/How?

var c = 1;

function Fn() {
c = 2;
}
Fn();
c; // 2

Why isn’t the value 2 limited to the scope of the function?
When I write c = 2 within a function, does the javascript engine automatically hoist a new var c outside of the function and assigns it the value undefined, which is then changed to 2 once Fn() is called?

How does ES2022 approval effect everyday developer?

22.06.2022 – Ecma International approves new standards

I get it that new features are being added and must reach certain stage to be approved. But this features can be used way before the Ecma approval.

What changes can a student/developer/hobbyist expect when, for example, ES2022 is approved?

  • Is it just so that we know we are writing our code using the newest standard?
  • Does Google wait for the approval to include full support for this new features in Google Chrome? Or does it MUST support this features after the approval?

First time asking a question, hope it makes sense.


Source: https://www.ecma-international.org/news/ecma-international-approves-new-standards-6/

View,Update and delete itmes . I don’t know how to change so i can do that

How i can use that to select,show,update and delete the items i added in Microsoft SQL Server Management Studio ? I used MVC to get the data. I tried several things but none worked. To add and save new items it works.

    $(document).ready(function() {
        $("#btnSave").click(function() {
            SaveItem();
        });
    });
    function ResetItem() {
        $("#CategoryId").val("1");
        $("#ItemName").val("");
        $("#Description").val("");
        $("#ItemPrice").val("");
        $("#ImagePath").val("");
    }
    function SaveItem() {
        var formData = new FormData();
        formData.append("CategoryId", $("#CategoryId").val());
        formData.append("ItemName", $("#ItemName").val());
        formData.append("Description", $("#Description").val());
        formData.append("ItemPrice", $("#ItemPrice").val());
        formData.append("ImagePath", $("#ImagePath").get(0).files[0]);
        $.ajax({
            async: true,
            dataType: 'JSON',
            type: 'POST',
            contentType: false,
            processData: false,
            url: '/Item/Index',
            data: formData,
            success: function (data) {
                if (data.Success)
                {
                    alert(data.Message);
                    ResetItem();
                }
            },
            error: function() {
                alert("There is some problem to add Item.");
            }
        });
    }
</script>

Terminatable recurring background tasks

I need to implement a self-refreshing fragment using JS on my page. The catch is I need to be able to terminate the process when some action is performed and start again after.

Let’s say I have:

$( document ).ready( function() {
    pageInit()
} )

function pageInit() {
    executeRefresh()
    doSomeOtherInitStuff() // refresh must be non-blocking!
}

function someAction() {
    stopRefresh() // stop refresh somehow??
    doSomething() // execute my action
    executeRefresh() // restart refresh
}

function executeRefresh() {
    setTimeout( function () {
        refreshFragment() // some function that refreshes my fragment
    }, 1000 )
}

So I need to have such order of things:

  1. pageInit() executes automatically on page render
  2. automatic refreshes start in background
  3. some other initialization is performed (thus refresh is not blocking further execution)
  4. user clicks a button that calls someAction()
  5. automatic refreshes stop
  6. action is executed (including some extensive DOM manipulation)
  7. automatic refreshes start anew

This is needed due to actions reloading significant parts of page with server-side rendered fragments and in many cases the refreshes will not be applicable anymore.

I have read about requestIdleCallback() but am yet to understand how to stop such background tasks without fully reloading my page.

Any suggestions are greatly appreciated!

P.s. this is going to be a part of my common framework js that is included in all pages but only executes if elements with given attributes are present on page. So I cannot just plainly write the refresh as there might be multiple or none of such refreshable fragments on any page.

Running into issue using Google login with Expo Auth Session

I’m getting this error the first time I open the app and I call the sign in function. It works the second time though.

Cannot prompt to authenticate until the request has finished loading.

Here is my code for Google login:

import React, { useEffect, useState, createContext, useContext, useMemo } from "react"
import * as Google from "expo-auth-session/providers/google"
import * as WebBrowser from "expo-web-browser"
import { GoogleAuthProvider, signInWithCredential, auth, onAuthStateChanged, signOut } from "../firebase"

WebBrowser.maybeCompleteAuthSession()

const config = {
  expoClientId: xxxx
  webClientId: xxxx
  iosClientId: xxxx
  androidClientId: xxxx
}

const AuthContext = createContext({});

export const AuthProvider = ({children}) => {
  const [user,setUser] = useState(null)
  const [error,setError] = useState(null)
  const [req, res, login] = Google.useAuthRequest(config)

  const [loading, setLoading] = useState(true)
  useEffect(
    () =>
      onAuthStateChanged(auth, user => {
        setLoading(true)
        if (user) {
          setUser(user)
          setLoading(false)
        } else {
          setUser(null)
        }
        setLoading(false)
      }),
    []
  )
  const signInWithGoogle = () => {
    setLoading(true)
    login({ showInRecents: true })
      .then(async response => {
        if (response && response.type === "success") {
          const { accessToken, idToken } = response.authentication
          const credential = GoogleAuthProvider.credential(idToken, accessToken)
          await signInWithCredential(auth, credential)
          setLoading(false)
        }
      })
      .catch(error => console.error(error))
      .finally(() => setLoading(false))
  }

React Native switch the text when user press the item

i’m building React Native with Expo, trying to make custom dropdown without using liberals,

the purpose of the component able the user select their birth day
how can i save the value of the item(the user click on) and make the value upper on the label place ?

const Dropdown = ({ label } ,{data} ) => {
  const [days , setDays] = useState([
    {num: 1 ,key: '1'},
    {num: 2 , key: '2'},
    {num: 3 , key: '3'},
    {num: 4 , key: '4'},
    {num: 5 , key: '5'},
  ]) ;
  const [onSelect, setOnselect] = useState({ label: ''});

  const DropdownButton = useRef();
 const [visible ,  setVisible] =  useState(false);
 
 const [selected, setSelected] = useState(undefined);
 const [dropdownTop, setDropdownTop] = useState(0);


 const toggleFunction = () => {
  visible ? setVisible(false) : openDropdown();
};

const openDropdown = ()=> {
  DropdownButton.current.measure((_fx, _fy, _w, h, _px, py) => {
    setDropdownTop(py + h);
  });
  setVisible(true);
};

const onItemPress = (item) => {
  setSelecte(item);
  onSelect(item);
  setVisible(false);
};

const renderItem = ({ item }) => (
  <TouchableOpacity style={styles.item} onPress={() => onItemPress(item)}>
    <Text>{item.label}</Text>
  </TouchableOpacity>
);
const renderDropdown = () =>{
  return (
    <Modal 
    visible={visible} 
    transparent animationType="none">
      <TouchableOpacity
       style={styles.overlay}
       onPress={() => setVisible(false) }
      >
        <View style={[styles.dropdown, { top: dropdownTop }]}>
        <FlatList
          data={days}
          showsVerticalScrollIndicator = {true}
          renderItem={({item}) => (
            <Text style={styles.item} > {item.num}</Text>
          )}
          
        />
        </View>
        </TouchableOpacity>
      </Modal  > 
  )
}
    return (
    <TouchableOpacity 
    onPress={() => toggleFunction()}
    ref={DropdownButton}
    style={styles.button}>
      <Text> {(onSelect.label) || label}</Text>
      <MaterialCommunityIcons
                  name="chevron-down"
                  color={'#58abc8'}
                  size={16}
                />
     { visible  == true ? ( renderDropdown ()) :null}
    </TouchableOpacity>
    );
  
     }
  

if can i ask about styling how can make each dropdown upper on different place (where belongs to parent View),now all the drop now upper belongs to day on UI

My active class is overriding my scroll to top function in JavaScript

I have coded a smooth scroll to top button JS shown here:

mybutton = document.getElementById("btnTop");
// When the user scrolls down 20px from the top of the document, show the button. 
// This can be modified!
window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    mybutton.style.display = "block";
  } else {
    mybutton.style.display = "none";
  }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
    //   document.body.scrollTop = 0; // For Safari
    //   document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
    window.scrollTo({ top: 0, behavior: 'smooth' });
    }

with the rest of the code being CSS for visuals and an HTML callout and it was working just fine until I had to use a getBoundingClientRect to get the DOM to detect the active state of the current section on the page.
Code Shown here

window.onscroll = function() {
      document.querySelectorAll("section").forEach(function(active) {
        let activeLink = navBar.querySelector(`[data-nav=${active.id}]`);
      if(active.getBoundingClientRect().top >= -400 && active.getBoundingClientRect().top <= 150){
    
        active.classList.add("your-active-class");
        activeLink.classList.add("active-link");
    
        }
        else{
             active.classList.remove("your-active-class");
             activeLink.classList.remove("active-link");
        }
      });
    }

and since then my button disappeared, i would say it has something to do with the window.onscroll function. how do i fix this while keeping both codes?

Can JavaScript extend an object to use another class’ member methods?

A bit of background for my current issue: I’ve been using Adobe Animate to generate HTML5 canvas and create my front-end canvas elements: labels, text fields, and MovieClip objects as well. These are acting as my multipurpose objects. Reason being is that if I use traditional buttons any pop up dialog gets drawn behind my buttons. I’ve tried a number of ways to get around this issue but in the end I ended up replacing my buttons objects with MovieClip objects and that solved the layering issue I was having.

Now onto my current issue: I still need some of my MovieClip objects to act as buttons. I created a class in my project file and called it BasicButton. Its got some core functionalities that my MovieClip objects will need in order for any object to act like a button.

class BasicButton {
  constructor(obj){
    this.obj = obj;
  }
}
function onMouseHover() {
  console.log('Hovering over' + this.obj);
}
function onMouseDown() {
  console.log('MouseDown on' + this.obj);
}

In my main .html file I managed to get access to my MovieClip item which is named FakeButton_1 and is of type MovieClip.

<html>
..head
..body

<script .. create.js />
<script src="./BasicButton.js" />
<script>
funtion onLoad(){
    extractRoot('canvas').FakeButton_1.text = "Hello World"; //testing I can change the text of this object and it works!
    //TODO: now make FakeButton_1 extend or make it of type BasicButton
}
</script>
</html>

My question is how, then, can I say FakeButton_1 extends BasicButton? Ideally I would have to pass it FakeButton_1 object into BasicButton constructor so then it knows which object it is manipulating.

I also started looking into this article but I cant seem to find a way to get BasicButton to acknowledge FakeButton_1.

Any help would be greatly appreciated.

Deleting unnecessary spaces in a html string

Hi I was trying to delete all unnecessary spaces in a html string.
I tried :

const myHtml ='<h1> Hello &nbsp; world &nbsp; ! </h1>'
const spacelessHtml = myHtml.replaceAll(' ','')
console.log(spacelessHtml)

For the above example this works just fine. Since the html comes from a text editor it can also includes cases like the following :

const myHtml ='<img src="https://i.pinimg.com/736x/65/71/58/657158c974c69f6e7b2a7090bcced6b2--computer-science-linux.jpg"> <h1> Hello &nbsp; world &nbsp; ! </h1>'
const spacelessHtml = myHtml.replaceAll(' ','')
console.log(spacelessHtml)

This ofcourse introduces a problem ‘<img src’ will become ‘<imgsrc’. An the html becomes wortheless. I however still need to delete all spaces between html-tags that include text. Why? All the html is inputed in a parser (used to convert html to a custom document format) that relies on html that only uses &nbs_p; (_ to prevent it from converting into a space) when space is required. The extra “&nbsp” spaces that the javascript text editor adds and that don’t appear on screen will cause issues. Altering the parser is not a viable option please don’t suggest it, see it as part of the problem.

Html from text editor => clean spaces => the parser => output

I tried some html-sanitizer libraries, I found none that satisfied my need. Does anyone know a solution or a library that could help me? Thanks in advance.

Declaring a CSS Module Class as a Variable in NextJS

Please excuse me if I forget anything – this is my first post on Stack Overflow.

The function’s purpose is to open and close my hamburger menu.
I have attached a snapshot of the JSX file where this issue is: NavbarLinks.jsx.
The lines of code that I am struggling with are 15 and 18 where I am trying to declare a CSS module class as a variable.

const [navLinkOpen, navLinkToggle] = useState(false);
  const handleNavLinksToggle = () => {
    navLinkToggle(!navLinkOpen);
  };

  const renderClasses = () => {
    let classes = {`${styles.navLinks}`};

    if (navLinkOpen) {
      classes += {`${styles.active}`};
    }

    return classes;
  };

I then call the returned class inside the ul tag on line 27.

<ul className={renderClasses}>

I have tried several variations of declaring this class as a variable, what I am showing you here is just my last attempt. I am aware that the attempt I am using has broken the code. – I am fairly new to JavaScript and instead of simply following YouTube guides, I learn better by trying things myself.

Please try and answer the question I have instead of suggesting an alternative method, purely because I just want to learn more about this! – but if you do have alternative methods of what I am trying to achieve here, I would very much like to see them too.

I’ll also include a snapshot of the CSS Module file that I am working with just incase you may find it useful: NavbarLinksStyle.module.css

Thanks in advance for any help – will be around to answer any questions.

Javascript return more than once?

please can you help me understand when and under what conditions should I be returning more than once in a statement block?
for example, my code:

function checkPositive(arr) {
    return arr.every(function(element) {
        return element > 0;
   });
}

why does this only work if I return twice?

I’m confused about how to follow this structure and when to know I should be using them.

Thanks

How to reset a website media permissions from a chrome extension

I’m working on developing a chrome extension that adds the ability to users to stream videos from any website they want by using Agora SKD. What the extension supposed to do is showing the streaming video screen inside the opened tab. I’m using Agora library to stream the videos.

Agora library requests media permissions(camera and microphone) for the opened website; If the user was on w3schools.com website, then media permissions will be granted to w3schools.com website.

enter image description here

Granting media permission to every website I need to inject my javascript code in and start video streaming on is not something very wise, because those websites can run scripts in the future that will access user’s camera and microphone. That’s why I’m looking for a way to limit websites access to those permissions.

The first way I thought in to show the video stream inside the tab without granting w3schools website media permission is embedding the video stream code in another website owned by my chrome extension mywebsite.com, grant my website the media permission and display my website within w3schools.com. I tried to put my website mywebsite.com inside a frame within w3schools.com website and ask for permission from my website. This doesn’t work cause Chrome grants the permission to w3schools.com website and passed the permission to the frame that running my website.

<!--Allow camera and microphone access within the context of this iframe-->
<iframe src="https://mywebsite.com" allow="camera;microphone"></iframe>
<!--Other content of w3schools.com goes here-->

I tried to also look for a way to grant w3schools.com website media permissions temporarily and revoke the permissions after the video streaming is over but I couldn’t find any way to do that.

I didn’t find any way to revoke/reset the permissions using JS.
I didn’t find any way to revoke/reset the permissions using chrome extension api interface.
I didn’t find anyway to temporarily grant the media permission to a tab(until it’s closed or for a certain time).
I didn’t find anyway to access chrome://settings/content/siteDetails?site=https%3A%2F%2Fwww.w3schools.com and change the website permission from there.

So my questions are:

  • How can I revoke the media permissions access for a website using chrome extensions?
  • Is there a way where I can load my website https://mywebsite.com within w3schools.com and request the media permissions to https://mywebsite.com instead of w3schools.com?

How to get asynchronous data into a global array in React.js?

I want to insert asynchronous data from Firestore into React elements. I have a couple of functions that handle the flow.

getEvents() is an asynchronous function that returns an array of objects that is my data from Firestore.

const getEvents = async() => {
    try {
        const data = query(collection(db, id));
        const events = [];
        const snapshot = await getDocs(data);
        snapshot.forEach((doc) => events.push(doc.data()));
        return events;
    } catch(error) {
        console.error(error);
    }
}

This function is referenced in receiveEvents() where I take the returned data and put it into a global array in order to use it in the DOM.

let userEvents = [];
const receiveEvents = () => {
    getEvents()
        .then(result => userEvents = result)
        .catch(error => console.error(error));

This function is used in displayEvents() to paste the returned data into the desired element. The function is called upon a button click.

const displayEvents = () => {
    try {
        const btnContainer = document.querySelector(".btn-container");
        ReactDOM.render(<AppNavigation />, btnContainer);
        receiveEvents().then(() => { return userEvents }); 
    } catch(error) {
        console.error(error);
    }
}

I get an error index.js:1 TypeError: Cannot read properties of undefined (reading 'then') @ displayEvents.

These functions use the logged user ID to access the right directory in the database. I retrieve the ID in a given function declared at the top of the file.

let id = null;
const getUserId = () => {
    try {
        console.log("getUserId()");

        return auth.currentUser.uid;
    } catch(error) {
        console.error(error);
    }
}

The <AppNavigation/> component returns a div, namely:

<div className="arrow-navigation-container">
      <button className="arrow-btn"><span className="icon arrow">arrow_back</span></button> 
      <button className="arrow-btn"><span className="icon arrow">arrow_forward</span></button>
</div>

What can I do to get the asynchronous data into the userEvents array, so I can show it to the user upon request?