How to write HTML tags without string declaration in vanilla js

If you want to use an HTML element in vanilla JavaScript without using a function like Document.createElement(), you need to use it like this:

const App = `<h1>Hello, world</h1>`;

But is there a way to do this in vanilla JavaScript, just HTML tags without a string declaration (signs like “)? For example:

const App = <h1>Hello, world</h1>;

Where to add a p tag in line of code React

I have two component where I am rendering images and links from a data js file. I would also like to generate a paragraph but am unsure where I can call the paragraph tag to generate it on both my ProjectList.js and Project.js components.
I’d like it to be just under the image.

Project.js

import "./project.css";

const Project = ({ img, link }) => {
  return (
    <div className="p">
      <div className="p-browser">
        <div className="p-circle">Tick</div>
        <div className="p-circle"></div>
        <div className="p-circle"></div>
      </div>
      <a href={link} target="_blank">
        <img src={img} alt="" className="p-img" />
        <p>kscjksnkdjs</p>
      </a>
      <div className="p-right">
        <div className="p-bg"></div>
      </div>
    </div>
  );
};

export default Project;

ProjectList.js

import "./projectList.css";
import Project from "../project/Project";
import { projects } from "../../data";

const ProjectList = () => {
  //   console.log(projects);
  return (
    <div className="pl">
      <div className="pl-texts">
        <h1 className="pl-title">Projects</h1>
        <p className="pl-description">
          {/* Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum sunt ad
          vitae. Quo maxime quos odit? Fuga omnis suscipit numquam adipisci unde
          aliquid vel deleniti ex eos excepturi. Atque, nostrum. */}
        </p>
      </div>
      <div className="pl-list">
        {projects.map((project) => (
          <Project key={project.id} img={project.img} link={project.link} />
        ))}
      </div>
      <div className="text">thsisihsjihih</div>
      <div className="pl-right">
        <div className="pl-bg"></div>
      </div>
    </div>
  );
};

export default ProjectList;

firestore updateDoc removes other fields in array

 async function editBackEnd() {
        const entryRef = doc(db, "accounts", user.uid)
        
        await updateDoc(entryRef, {
                "entry.0.payment": "League"
         })
     }

I’m trying to update certain fields in an array in firestore. I know there is no direct way to do so but with this code i am able to access the field but it removes all the other entries/fields.

How do I make sure it only updates the field that i want. in this cause im just trying to update payment of index 0

Im having issues uploading pics to stackoverlow so here’s a couple url

https://imgur.com/a/1hqNgsn firestore database before updateDoc

https://imgur.com/a/Egzofvz firestore database after updateDoc

What does the FeedbackSlot size(length) mean?

Some questions about Feedback:

  1. as the title asked

  2. A slot site that only encounters objects of a single hidden class is called monomorphic; if it encounters objects of two hidden classes, it is called polymorphic; if it is greater than 2, it is called megamorphic. Is that right? Then does the slot size have anything to do with polymorphic?

Spring Boot & React App: getting a (Failed to convert value of type ‘java.lang.String’ to required type ‘long’) error?

Before starting, sorry if this is a very elemental question and if I’m missing something basic. I’m trying to create a three tier app in which users can create and consult purchase orders. So far everything is working, except for some methods that I have to update information on orders. When I click the “Update”, “Delete” or “Complete Status” buttons in the front end, I should get a message saying “The order was successfully updated!”, but instead, nothing happens and I get this error in my Java back end:

Failed to convert value of type 'java.lang.String' to required type 'long'; nested exception is java.lang.NumberFormatException: For input string: "undefined"]

Here is all the relevant code that I have for the back end:

Order Model

package com.backend.springjwt.models;

import javax.persistence.*;
@Entity
@Table(name = "orders")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ordid_generator")
    @SequenceGenerator(name = "ordid_generator", initialValue = 10000, allocationSize = 1, sequenceName = "ordid_seq")
    private long id;

    @Column(name = "title")
    private String title;

    @Column(name = "description")
    private String description;

    @Column(name = "completed")
    private boolean completed;

    @Column(name = "userid")
    private String userId;

    public Order() {
    }

    public Order(String title, String description, boolean completed, String userId) {
        this.title = title;
        this.description = description;
        this.completed = completed;
        this.userId = userId;
    }

Order Controller

 @PutMapping("/orders/update/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Order> updateOrder(@PathVariable("id") long id, @RequestBody Order order) {
        Optional<Order> orderData = orderRepository.findById(id);
        if (orderData.isPresent()) {
            Order _order = orderData.get();
            _order.setTitle(order.getTitle());
            _order.setDescription(order.getDescription());
            _order.setCompleted(order.isCompleted());
            _order.setUserId(order.getUserId());
            System.out.println(order.getId());
            System.out.println(order.getDescription());
            System.out.println(order.getUserId());
            return new ResponseEntity<>(orderRepository.save(_order), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

Here is all the relevant code that I have for the front end:

Order Component

import React, { Component } from "react";
import OrderDataService from "../services/order.service";

export default class Order extends Component {
  constructor(props) {
    super(props);
    this.onChangeTitle = this.onChangeTitle.bind(this);
    this.onChangeDescription = this.onChangeDescription.bind(this);
    this.onChangeUserId = this.onChangeUserId.bind(this);
    this.getOrder = this.getOrder.bind(this);
    this.updatecompleted = this.updatecompleted.bind(this);
    this.updateOrder = this.updateOrder.bind(this);
    this.deleteOrder = this.deleteOrder.bind(this);
    this.state = {
      currentOrder: {
        id: null,
        title: "",
        description: "",
        completed: false,
        userId: ""
      },
      message: ""
    };
  }
  componentDidMount() {
    this.getOrder(this.props.match.params.id);
  }
  onChangeTitle(e) {
    const title = e.target.value;
    this.setState(function(prevState) {
      return {
        currentOrder: {
          ...prevState.currentOrder,
          title: title
        }
      };
    });
  }
  onChangeDescription(e) {
    const description = e.target.value;   
    this.setState(prevState => ({
      currentOrder: {
        ...prevState.currentOrder,
        description: description
      }
    }));
  }
  onChangeUserId(e) {
    const userId = e.target.value;   
    this.setState(prevState => ({
      currentOrder: {
        ...prevState.currentOrder,
        userId: userId
      }
    }));
  }
  getOrder(id) {
    OrderDataService.getById(id)
      .then(response => {
        this.setState({
          currentOrder: response.data
        });
        console.log(response.data);
      })
      .catch(e => {
        console.log(e);
      });
  }
  updatecompleted(status) {
    var data = {
      id: this.state.currentOrder.id,
      title: this.state.currentOrder.title,
      description: this.state.currentOrder.description,
      completed: status,
      userId: this.state.currentOrder.userId
    };
    OrderDataService.update(this.state.currentOrder.id, data)
      .then(response => {
        this.setState(prevState => ({
          currentOrder: {
            ...prevState.currentOrder,
            completed: status
          }
        }));
        console.log(response.data);
      })
      .catch(e => {
        console.log(e);
      });
  }
  updateOrder() {
    OrderDataService.update(
      this.state.currentOrder.id,
      this.state.currentOrder
    )
      .then(response => {
        console.log(response.data);
        this.setState({
          message: "The order was updated successfully!"
        });
      })
      .catch(e => {
        console.log(e);
      });
  }
  deleteOrder() {    
    OrderDataService.delete(this.state.currentOrder.id)
      .then(response => {
        console.log(response.data);
        this.props.history.push('/orders')
      })
      .catch(e => {
        console.log(e);
      });
  }
  render() {
    const { currentOrder } = this.state;
    return (
      <div>
        {currentOrder ? (
          <div className="edit-form">
            <h4>Order</h4>
            <form>
              <div className="form-group">
                <label htmlFor="title">Title</label>
                <input
                  type="text"
                  className="form-control"
                  id="title"
                  value={currentOrder.title}
                  onChange={this.onChangeTitle}
                />
              </div>
              <div className="form-group">
                <label htmlFor="description">Description</label>
                <input
                  type="text"
                  className="form-control"
                  id="description"
                  value={currentOrder.description}
                  onChange={this.onChangeDescription}
                />
              </div>
              <div className="form-group">
                <label htmlFor="userId">User ID</label>
                <input
                  type="text"
                  className="form-control"
                  id="userId"
                  value={currentOrder.userId}
                  onChange={this.onChangeUserId}
                />
              </div>
              <div className="form-group">
                <label>
                  <strong>Status:</strong>
                </label>
                {currentOrder.completed ? "completed" : "Pending"}
              </div>
            </form>
            {currentOrder.completed ? (
              <button
                className="badge badge-primary mr-2"
                onClick={() => this.updatecompleted(false)}
              >
                Change Status
              </button>
            ) : (
              <button
                className="badge badge-primary mr-2"
                onClick={() => this.updatecompleted(true)}
              >
                Complete Status
              </button>
            )}
            <button
              className="badge badge-danger mr-2"
              onClick={this.deleteOrder}
            >
              Delete
            </button>
            <button
              type="submit"
              className="badge badge-success"
              onClick={this.updateOrder}
            >
              Update
            </button>
            <p>{this.state.message}</p>
          </div>
        ) : (
          <div>
            <br />
            <p>Please click on an Order...</p>
          </div>
        )}
      </div>
    );
  }
}

Order Service

import authHeader from './auth-header';
import http from "../http-common";

class OrderDataService {
  getAll() {
    return http.get(`/orders/getAll`, { headers: authHeader() });
  }
  getById(id) {
    return http.get(`/orders/get/id/${id}`, { headers: authHeader() });
  }
  getByUserId(id) {
    return http.get(`/orders/get/userid/${id}`, { headers: authHeader() });
  }
  getByTitle(title) {
    return http.get(`/orders/get/title/${title}`, { headers: authHeader() });
  }
  getByCompleted() {
    return http.get(`/orders/get/completed/`, { headers: authHeader() });
  }
  create(data) {
    return http.post(`/orders/create`, data, { headers: authHeader() });
  }
  update(id, data) {
    return http.put(`/orders/update/${id}`, data, { headers: authHeader() });
  }
  delete(id) {
    return http.delete(`/orders/delete/${id}`, { headers: authHeader() });
  }
  deleteAll() {
    return http.delete(`/orders/deleteAll`, { headers: authHeader() });
  }
 
}
export default new OrderDataService();

I’ve been looking at everything for hours and I can’t quite figure out what’s wrong. Since the only long value in the orders table is the id for the order, that must be the issue, but I’ve tried to get the id as a String and then parse it to be long, but I get the same error. Any insight is appreciated.

I want to pause/play CSS animation using one button with Javascript. The sun and sky colors should be controlled with the button. But I am not getting

HTML CODE:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset = "utf-8">
        <title>Keyframe Animations</title>
        <link rel="stylesheet" href="SunLabcss.css" type="text/css"/>
        <script src="scriptSun.js"></script>


    </head>
    <body>
        <button id = "sunButton" onclick="sunPausePlayToggle()">PLAY/PAUSE</button

sunPausePlayToggle() is a function in JS which will control the animation .

        <div id = "sunSky"

this is a div which i am using as a background sky

            <div id = "sun"></div

the upper div is a sun which rise from right and dawn in the left

        </div>
    </body>
</html>


CSS code:

I am using keyframe animations to animate the sun and sky.

@keyframes risesky {
    0% {
        top: 100%;
        left : 100%;
        background-color: red;
    }
    50% {
        left:50%;
        top: 10%;
        background-color: yellow;

    }
    100% {
        background-color: orangered;
        top: 100%;
        left: 0%;
    }
}

@keyframes sky {
    0% , 100% {
        background-color: #1c1341;

    }
    10% {
        background-color: darkorange;
    }
    50% {
        background-color: skyblue;

    }
    80% {
        background-color: crimson;

    }
}

#sunButton{
    animation-play-state: running;
}

#sun {
    position: relative;
    border-radius: 50%;
    width: 80px;
    height: 80px;
    animation: risesky 11s infinite;

}

#sunSky {
    height: 500px;
    overflow: hidden;
    animation:  sky 11s infinite both;
    
}


Javascript code:

here is the problem I am getting, I can only pause the animation in JS ,but can’t play.

function sunPausePlayToggle(){
    document.getElementById("sunSky").style.animationPlayState = "paused";
    document.getElementById("sun").style.animationPlayState = "running";
    
}

How can I use Prompt, if and else in Javascript function to select arithmetic symbol and do some calculation with the user inputs

I am a novice in this and it is really making me to lose my hair; I can find what I’m doing wrong, please help. I am doing this in javascript. It doesn’t show any error, nor display any result either. This is what I have:

    var sumIt;
    var subtractIt;
    var multiplyIt;
    var divideIt;
    var operatorOpt = prompt("Select operator");
    
    function showResult(whatResult) {
        document.write(whatResult);
        document.write("<br>");
    }
    
    var doSomething = function(num1, num2) {
        if (operatorOpt == sumIt) {
            showResult("The result is: " + (num1 + num2));
    
    
        } else if (operatorOpt == subtractIt) {
            showResult("The result is: " + (num1 - num2));
    
        }  else if (operatorOpt == multiplyIt) {
            showResult("The result is: " + (num1 * num2));
    
    
    }  else if (operatorOpt == divideIt) {
            showResult("The result is: " + (num1 / num2));
    
    doSomething(parseInt (prompt("Enter first number: ")) ,  parseInt (prompt("Enter second number: ")))

Un attachement of JWT token [duplicate]

import React from 'react'
import styles from './LoginForm.module.css'
import ReactDOM from 'react-dom';
import { useRef } from 'react';


const Backdrop = () => {
    return (
        <div className={styles.backdrop} />

    )
}
const Login_Card = ({ showFormHandeler }) => {

    const emailRef = useRef();
    const passwordRef = useRef();

    // const C_passwordRef=useRef()
    const onLoginHandeler = async () => {
    const email =emailRef.current.value;
    const password =passwordRef.current.value;

        const user_data = {
            email:email,
            password:password,

        }
   const url = 'http://localhost:5000/login'
        
        const response = await fetch(url, {
            method: 'POST',
            body: JSON.stringify(user_data),
            headers: {
                "Content-type": "application/json; charset=UTF-8"
            }

        })
        const data= await response.json();
        console.log(data);
    }
    return (
        <div className={styles.overlay_container}>
            <div className={styles.form_card}>
                <h1>
                    This is the Login card
                </h1>
                <form>
                    <div className={styles.form_item_group}>
                        <label className={styles.label} ref={emailRef}>Email </label>
                        <input ref={emailRef} />
                    </div>

                    <div className={styles.form_item_group}>
                        <label className={styles.label}>Password  </label>
                        <input ref={passwordRef} />
                    </div>



                    <div  className={styles.form_item_group_btn_container}>
                        <span onClick={onLoginHandeler} className={styles.signup_form_button}>
                            Login
                        </span>
                        <span onClick={showFormHandeler} className={styles.signup_form_button}>
                            cancel
                        </span>
                    </div>


                </form>

            </div>

        </div>
    )
}
function LoginForm({ showFormHandeler }) {
    const overlayRoot = document.getElementById('overlay');
    return (
        <React.Fragment>
            {
                ReactDOM.createPortal(<Backdrop />, overlayRoot)
            }
            {
                ReactDOM.createPortal(<Login_Card showFormHandeler={showFormHandeler} />, overlayRoot)
            }

        </React.Fragment>
    )
}
export default LoginForm

**FRONT OF WEB APP **

I am Supposed to log in the user using React JS front end and Using my Own Node js backed API with JWT token,
Now whenever User clicks the the LOGIN Button , our API( ‘http://localhost:5000/login’ )
will pe called , Which will be POST request , .

On Backend , i will compare email id and password with the encrybted password and get the user if it exsists with given credentials, and attched jwt token with userid .

exports.loginUser = async (req, resp) => {
    console.log("login Req body : ", req.body);

    //  user login
  try {
      const email=req.body.email;
      const password=req.body.password;
      const user= await User.login(email,password);
      const token=createToken(user._id)

      resp.cookie('jwt',token);
      
      resp.status('200').json({id:user._id})



  } catch (error) {
     if(error)
     {
         console.log(error.message);
        resp.status('400').json({message:error.message})
     }
  }

}

But I login user with my front end I didn’t receive any JWT token But when i test my
API using POSTMAN it shows JWT token
Differences in the output of Front end and POSTMAN request

can anyone help me out with this why is this happening?

Uncaught (in promise) TypeError: Object(…)(…).once is not a function

Hi I need some help with these it says that

Uncaught (in promise) TypeError: Object(…)(…).once is not a function
at eval (store.js?07a4:42:1)
at eval (index-6de4cbb9.js?4d2d:2453:1)

Here’s my code:

onAuthStateChanged(firebaseAuth, user => {
      if (user) {
        // User is signed in, see docs for a list of available properties
        // https://firebase.google.com/docs/reference/js/firebase.User
        const userId = firebaseAuth.currentUser.uid
        ref(firebaseDb, 'users/' + userId).once('value', snapshot => {
          console.log('snapshot: ', snapshot)
        })
        // ...
      } else {
        // User is signed out
        // ...
      }
    })

error

full-code

Editing dropdown values without having to create a new dropdown every time

Within the code.org javascript editor for the applab, there is the ability to create a dropdown by creating a dropdown by:

dropdown('id', 'option1', 'option2', ...);

I would like to know if there is a way to edit the list, treating it something like an array:

remove('id', 'position');

and:

insert('id', 'position', 'item1', 'item2'...);

any help would be appreciated, as I can’t find any way to do this in other places.

Auto-scroll down does not work after modal run

I have a boostrap 5.1.3 modal with some content, by default if the content is biger of 400px for the modal, a scrollbar should appear.
But this does not happen and only works after clicking the scroll down button.
If someone has an idea of the problem ?

refreshScroll();
const exampleModal = document.getElementById('exampleModal')
if(exampleModal){
  exampleModal.addEventListener('show.bs.modal',refreshScroll )
}   
var objDiv = document.getElementById("pmbox");
objDiv.scrollTop = objDiv.scrollHeight;
document.querySelector('#pmsend').addEventListener('click', function (e) {
  e.preventDefault();
  refreshScroll();
});
function refreshScroll(){
  var objDiv = document.getElementById("pmbox");
  if(objDiv)
  objDiv.scrollTop = objDiv.scrollHeight;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Launch demo modal</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
                <div class="card-body text-dark" id="pmbox" style="position: relative; height: 100px; overflow-y: scroll; verflow-x: hidden;">
                    <div class="bg-info" style="height: 200px;"> most scroll down auto </div>
                </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="pmsend">scroll down</button>
      </div>
    </div>
  </div>
</div>