What is the difference between `document` and `document.body`?

What is actually the difference between document and document.body?

For example, I have the following code:

document.addEventListener('click',function(){ 
document.write('You click me!') 
})
<div>Click anywhere</div>

What will be the difference if I use document.body instead of document ?

And what is actually the difference between document and document.body?

I tried to search online, but couldn’t find any useful information.

Thanks for any responds!

How does a React application start without explicit references to its JS implementation files?

I’m learning React. In the tic-tac-toe game ( https://reactjs.org/tutorial/tutorial.html ) the index.html file had some event handlers and a div pointing at id=root. But nothing about an index.js file, which has a ReactDOM.render.

What tells the browser to run the index.js code if there is no tag loading it?

This link ( Where’s the connection between index.html and index.js in a Create-React-App application? ) says:

Our configuration specifies that Webpack uses src/index.js as an “entry point”. So that’s the first module it reads, and it follows from it to other modules to compile them into a single bundle.

When webpack compiles the assets, it produces a single (or several if you use code splitting) bundles. It makes their final paths available to all plugins. We are using one such plugin for injecting scripts into HTML.

But if this is the answer, then why should a browser know about webpack, especially as this isn’t mentioned in the minimal index.html file?

Mutation Observer fails to detect original element, does detect its duplicate

I have written a Chrome extension that loads a script with run_at set to document_start.

My script uses Mutation Observer in order to invoke some code upon the addition of an element with id X to a certain webpage.

That element is created when the page first loads, and then recreated when part of the page reloads following some button click.

My mutation observer fails to detect that element in either case.

However, if I duplicate the element (Developer Tools > Elements > element > context menu > Duplicate element), then my mutation observer does detect the duplicate.

I ran a test: I changed the id of some random element to X. It was not detected. That has made me suspect the original element is first created and then has its id assigned or updated. I am not sure how I could prove of refute this theory (the process of generating the webpage code looks very complex, with layers and layers of scripts involved, and I have very little experience).

Does this theory make sense? Can I observe an id change? If the theory does not make sense or if it is impossible to observe an id change, what alternatives do I have?

Thank you!

html5 validation api gives an empty array of messages if a markup is wrong

trying to validate my html5 markup by clicking on a button and using w3c validator
the code source is from here
so my code is like this:

$('.btnw3').on('click', async function(){
    valid()
  .then(data => {
    console.clear();
    console.log(data); // Console was cleared - {messages: Array(0)}
        const error = data.messages.filter(msg => msg.type === 'error');
const warning = data.messages.filter(msg => msg.type === 'info' && msg?.subType === 'warning');

if (warning.length) {
  console.group(`%c${warning.length} validation warnings`, "background-color:#FFFBE5;padding:1px 4px");
  warning.forEach(msg => {
    console.groupCollapsed(`%c${msg.message} (line: ${msg.lastLine})`, "background-color:#FFFBE5");
    console.table(msg)
    console.groupEnd();
  })
  console.groupEnd();
}
if (error.length) {
  console.group(`%c${error.length} validation errors`, "background-color:#D93025;color:#FFF;padding:1px 4px");
  error.forEach(msg => {
    console.groupCollapsed(`%c${msg.message} (line: ${msg.lastLine})`, "color:#D93025");
    console.table(msg)
    console.groupEnd();
  })
  console.groupEnd();  // empty output
}
  })

});

so I intentionally make my markup wrong – write </divx> instead of <div> – for example

problem – I’m getting an empty array of messages on (console.log(data)) line

the same happens if I write this code as a snippet in chrome dev tools

if I copy my markup source and paste it on https://validator.w3.org/nu/#textarea – I’m getting the expecting errors

any help ?

Is it bad practice to accept setState as a function parameter in React?

Basically, before uploading an image to the firebase, I’m trying to control the input as:

export const controlThumbnail = (selectedThumbnail, setThumbnailError) => {
  if (!selectedThumbnail) {
    setThumbnailError('Please select a thumbnail!');

    return;
  }

  if (!selectedThumbnail.type.includes('image')) {
    setThumbnailError('Please select an image!');

    return;
  }

  if (selectedThumbnail.size > 1000000) {
    setThumbnailError('Image size must be less than 1MB!');

    return;
  }

  setThumbnailError(null);
};

which I call the above method from /lib/controlThumbnail.js to:

import { controlThumbnail } from '../../lib/controlThumbnail';
    
const Signup = () => {
  const [userInfo, setUserInfo] = useState({
    name: '',
    email: '',
    password: '',
    thumbnail: null
  });
  const [thumbnailError, setThumbnailError] = useState(null);


  const userInputHandler = (e) => {
    setUserInfo((prevUserInfo) => {
      if (e.target.name === 'thumbnail') {
        const thumbnail = e.target.files[0];
        controlThumbnail(thumbnail, setThumbnailError);

        return { ...prevUserInfo, thumbnail };
      } else {
        return { ...prevUserInfo, [e.target.name]: e.target.value };
      }
    });
  };
...

so, this is now works correctly, but I wonder if this is the good way of doing it? Or should I put the control method inside the component and never give setState as parameter?

Asynchronous Loading – Three.js

How can I properly load objects asynchronously using Three.js? I’ve been having lots of trouble with this. Currently, I have the following (simplified, albeit irreproducible without downloading GTLF models) code:

const loader = new THREE.GLTFLoader();
async function init(){
    obj = await loader.loadAsync("./public/modelo/scene.gltf");
    obj2 = await loader.loadAsync("./public/earth/scene.gltf");
    console.log(obj2.scene.children[0].position);
}
init();

This throws an error in the line with console.log, claiming Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'position'). Can someone explain what is going wrong here and how to fix it? I’m not very familiar with await, but I thought its functionality was to specifically avoid things like this from happening.

My reason for using asynchronous loading is so that I can pass these 3D objects to animation functions, and without asynchronous loading, the objects get passed before they have fully loaded, which throws an error.

Google Map won’t display [closed]

I am farily new to Java Script Programming. I am learing Java Script reading from a book titled Head First HTML5 Programming. There is this step by step exercise that teaches me how to find my location and insert a google map next to my location when it is tested in any browser. However map won’t display in any browser when i test it. This book was published in 2011. Since then google has changed a few things such as requireing an API Key inorder to display the map. So I created an API key using Google Map Console.
Then Commented out the old code from the book and included the one with API_Key. Yet map won’t show in any browser.
There is also no error messages on console log view of any of the browsers. However When i type localhost/My Loction/myLoc.html I get the following message:
enter image description here
Unchechecked runtime last error:The message Port closed before a response was recieved. myLoc.html: 1
Here is the myLoc.html page:
enter image description here
This is chorm browser:
enter image description here
Neither show any error messages. Yet map wont’t display.
What I am missing here. Please help.
Thx.
Shervin

How to identify the browser and redirect the user if that’s not the correct browser?

I have a website to do for university and the teacher wants us to include code that checks what browser the user is using and if the browser isn’t Firefox, they should be redirected elsewhere.

I have this so far:


function fnBrowserDetect(){                            
  let userAgent = navigator.userAgent;          
  let browserName;                    
  if(userAgent.match(/chrome|chromium|crios/i)){              
    browserName = "chrome";            
  }else if(userAgent.match(/firefox|fxios/i)){              
    browserName = "firefox";            
  }  else if(userAgent.match(/safari/i)){
    browserName = "safari";            
  }else if(userAgent.match(/opr//i)){              
    browserName = "opera";            
  } else if(userAgent.match(/edg/i)){              
    browserName = "edge";            
  }else{              
    browserName="No browser detection";            
  }                     
document.querySelector("h1").innerText="You are using "+ browserName +" browser";            
}

function redirect(){
  if(browserName != "firefox"){
    window.location.replace("www.google.com");
  } else {
    window.location.href = "../index.php";
  }
}

Can someone help me out and let me know how can I do this correctly?

Having an issue when using load events on firefox and safari

Both firefox and safari refuses to execute load event when loaded from an external js file. It only works on google chrome.

I can’t really understand the problem.

in my html :

<script src="/assets/js/pages/myFile.js" type="text/javascript"></script>

in myFile.js :

window.addEventListener("load", function(event){
// do someting (only works in chrome browser)
})

My html page is serverd by node.js (ejs page), myFile.js is recognized by the 3 browsers (Firefox, chrome & safari), so I don’t really understand why my load event fail with ff & safari.

I’ve also tried window.unload unsuccessfully.

Any suggestion ?

JS, React: Api requests queue

I’ve implemented a queue of api requests:

class QueueStore {
  private _requests: AxiosRequestConfig[] = [];

  private _loadingState = new LoadingStateStore();

  enqueue = (req: AxiosRequestConfig) => {
    this._requests = [...this._requests, req];
  };

  addEvent = (req: AxiosRequestConfig) => {
    this.enqueue(req);
  };

  processEvents = (() => {
    let isReady = true;

    return async () => {
      if (isReady && this._requests.length > 0) {
        this._loadingState.setLoading(true);

        const response = this.dequeue();

        isReady = false;
        this.retryApiCalls(response as AxiosRequestConfig);

        isReady = true;
        this.processEvents();
      }
    };
  })();

  private retryApiCalls = async (req: AxiosRequestConfig) => {
    try {
      await HttpService.request(req);
    } catch (error) {
      ToastService.onDanger(
        ExceptionsService.errorResolver(error as ServerError)
      );
    } finally {
      this._loadingState.setLoading(false);
    }
  };

  dequeue = () => {
    return this._requests.shift();
  };

  length = () => {
    this._requests.length;
  };

  get isSyncing() {
    return this._loadingState.loading;
  }

  get requests() {
    return toJS(this._requests);
  }
}

Problem: processEvents fires API calls one by one, even if they are failing. As a result, the queue is empty.

Goal:

  • processEvents should be stopped if one of the API calls has
  • only successful requests should be dequeud. Failing requests should be left in the queue

How can I modify the existing solution?

How to edit and modify pdf in react js

I have a scenario that a user logged in to my system and uploaded multiple PDF and save them and he can also see all uploaded documents in one place where he has the option to edit pdf, so he will click on any pdf so I want the PDF viewer should be open and there should be some options to draw on PDF and modify it, I have attached the example of what I’m exactly looking for.

enter image description here

Calculate Height/Depth Of Binary Tree Javascript

I am just a beginner, so if the error is something too obvious, I apologize .

My two questions are:

  1. What is this.root in our school’s provided code;
  2. How can I implement the .height method in order to measure the depth of a Tree.

The explanation:
We were provided with this code in the class:

function BinarySearchTree(value) {
  this.value = value;
  this.right = null;
  this.left = null;
}

BinarySearchTree.prototype.add = function(value) {
  let newLeaf = new BinarySearchTree(value)

  if(value > this.value){
    this.right === null? this.right = newLeaf : this.right.add(value)
  } else {
    this.left === null? this.left = newLeaf : this.left.add(value)
  }
};

And we were supposed to write a method to calculate the height/depth of a binary tree. Now, while practicing, I’ve seen something odd. Upon creation of a new node of an empty binary tree, the first node ends up being completely empty, while it proceeds to create a new node on the left side of the first empty one. Well, not empty, but whose value is undefined. Is this a desired behavior?

let newTree = new BinarySearchTree
>undefined

newTree.add(7)
>undefined

newTree.add(3)
>undefined

newTree.add(5)
>undefined

newTree
>BinarySearchTree {value: undefined, right: null, left: BinarySearchTree}
  left: BinarySearchTree {value: 7, right: null, left: BinarySearchTree}
  right: null
  value: undefined
  [[Prototype]]: Object

Now, considering the tests are passing for .add method, obviously I may be wrong in this situation, since this is the code provided to us by the teacher in the class.
This is the code I keep finding online and the reason I am not getting far with my code for .heigth method is because I am unable to implement this.root:

function Node(val){
  this.value = val;
  this.left = null;
  this.right = null;
}


function BinarySearchTree(){
  this.root = null;
}

How should I proceed with the .height method?
If it helps, here are the tests:

describe('Binary Search Tree', function() {
  var binarySearchTree;

  beforeEach(function() {
    binarySearchTree = new BinarySearchTree(5);
  });

  it('should have methods named "add", "contains", "depthFirstPre", "depthFirstIn", "depthFirstPost", "breadthFirst"', function() {
    expect(binarySearchTree.add).to.be.a("function");
  });

  it('should add values at the correct location in the tree', function(){
    binarySearchTree.add(2);
    binarySearchTree.add(3);
    binarySearchTree.add(7);
    binarySearchTree.add(6);
    expect(binarySearchTree.left.right.value).to.equal(3);
    expect(binarySearchTree.right.left.value).to.equal(6);
  });

  it('height method should return correct height', function() {
    binarySearchTree.left = new BinarySearchTree(3);
    binarySearchTree.left.left = new BinarySearchTree(1);
    expect(binarySearchTree.height()).to.eql(2);

    binarySearchTree.left.left.right = new BinarySearchTree(2);
    expect(binarySearchTree.height()).to.eql(3);

    binarySearchTree.left.left.left = new BinarySearchTree(0);
    expect(binarySearchTree.height()).to.eql(3);

    binarySearchTree.right = new BinarySearchTree(8);
    expect(binarySearchTree.height()).to.eql(3);
  });
}

Again, I apologize for a long question. I was trying to write all the relevant information regarding my problem.
Happy holidays!

JS Object Update + React Reducer

I’m struggling to update all “new” attributes too false. Below is an example object.

const msgdata = {
"1511207758": {
    "userid": "1000015977",
    "text": "hello",
    "new": false,
    "subjecttitle": null,
    "subjectcontent": null,
    "datetime": "2017-11-20T19:55:58.000Z"
},
"1511277428": {
    "userid": "1000000000",
    "text": "hey hi",
    "new": false,
    "subjecttitle": null,
    "subjectcontent": null,
    "datetime": "2017-11-21T15:17:08.000Z"
},
"1640341426": {
    "userid": "1000000000",
    "text": "hellow how are you?",
    "new": false,
    "subjecttitle": null,
    "subjectcontent": null,
    "datetime": "2021-12-24T10:23:45.706Z"
},
"1640342296": {
    "userid": "1000000000",
    "text": "asdfasdf",
    "new": true,
    "subjecttitle": null,
    "subjectcontent": null,
    "datetime": "2021-12-24T10:38:16.089Z"
},
"1640342382": {
    "userid": "1000000000",
    "text": "fxvfv",
    "new": true,
    "subjecttitle": null,
    "subjectcontent": null,
    "datetime": "2021-12-24T10:39:41.910Z"
}

}

when I try the following I mess up the object structure changes to an array but I need to maintain the object/key structure – just change the new value to false.

    let newMessages = {}
    if (payload.length > 0) {
        payload.map((item) => {
            if (messagesData && messagesData[item.userid]) {
                newMessages = Object.keys(messagesData[item.userid].messages).map((key) => ({ ...newMessages[item.userid].messages[key], new: false }))
            }
            return true
        })

        console.dir('newMessages')
        console.dir(newMessages)

the return object is a standard array – map does that… eg: 0,1,2 keys…

How can I maintain the object structure and just change the new attr.

thx