I need to set line-height dynamically based on the font size which is controlled from backend

.heading {
  font-size: 6rem;
  line-height: 4rem;
}
<div class="heading">
  <p> Hero
  <br>
  <span style="font-size:20px">Banner</span>
  <br>
  Text
  </p>
</div>

Here the gap between the text “banner” and Hero is too much as the line height is constant here. How to manage this by adjusting the line height dynamically so that the text doesn’t have too much spacing involved. Also suggest any other best way to achieve this

How to get image data from a file input in react.js

I want to get the data from an input file in react. I have created a class with the data as a state. The idea is that the data should be updated every time the input changes. As this happens, an image should load with the input data.

The code below is what I have created, but it does not work.


class ImagePicker extends React.Component {
    constructor(props){
        super(props);

        this.state = {
            data: null
        }
    }

    handleDataChange = e => {
        this.setState({
            data: e.target.value
        })
    }

    render(){
        return(
            <div>
                <input type='file' onChange={this.handleDataChange} />
                <img src={this.state.data}></img>
            </div>
        )
    }
}

I don’t know what the problem is, could you help?

why validate both the post request and the database schema in the backend?

Abstract: should I use express-validator if I can validate data using mongoose schema?

I’m a front end developer, and I usually do some validation on the form before submitting. Now, I’ve started studying express.

One of the first things I did was receive a form and validate it using a library called express-validator, then the database operations were done. very simple, no big deal. However, after doing a project by myself I realized that mongoose itself could handle the errors, not only that, but it was quite easy to return these errors on the front, especially in the case of an api.

So that is my doubt, why validate this data so many times? I know that database schemas is not only to do that, but doing theses things once in front and twice in backend cause too many
repetition and may be a little hard to maintain.

Here goes a few lines of code only to illustrate the case. Don’t judge me, I’m still learning.

import mongoose from "mongoose";

const TaskSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
    maxlength: 20,
  },

  description: {
    type: String,
    required: false,
  },

  completed: {
    type: Boolean,
    default: false,
  },

  date: {
    type: Date,
    default: Date.now,
  },
});

export default mongoose.model("Task", TaskSchema);
import taskModel from "../models/tasksModel";

export function createTask(req: express.Request, res: express.Response) {
  taskModel
    .create(req.body)
    .then((task) => res.status(201).send(task))
    .catch((err) => res.status(400).send(err));
}

How to close the side bar automatically when the li item is clicked

How do I close the side bar when someone clicks on the any of the li element. I have tried the code menuSidebar.display = "none" in the event listener, but this doesn’t seem to work

Thank you in advance

const menuButton = document.querySelectorAll("li");
const menuSidebar = document.getElementById("mySidebar");



/* Set the width of the sidebar to 250px and the left margin of the page content to 250px */
function openNav() {
  document.getElementById("mySidebar").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
}

/* Set the width of the sidebar to 0 and the left margin of the page content to 0 */
function closeNav() {
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft = "0";
}

// console.log(menuButton)
// console.log(mySidebar)
menuButton.addEventListener("click", ()=>{

  menuSidebar.display = "none";
  
  

});
:root {
  --title-font: "Titillium Web", sans-serif;
  --color-primary: #16e0bd;
  --color-secondary: #303030;
  --color-tertiary: #e0860b;
  --color-complimentary: #fc5817;
  --color-darkblack: #141414;
  --default: #ffffff;
}

.sidebar {
  height: 100%; /* 100% Full-height */
  width: 0; /* 0 width - change this with JavaScript */
  position: fixed; /* Stay in place */
  z-index: 1; /* Stay on top */
  top: 0;
  left: 0;
  background-color: var(--color-secondary); /* Black*/
  overflow-x: hidden; /* Disable horizontal scroll */
  padding-top: 60px; /* Place content 60px from the top */
  transition: 0.5s; /* 0.5 second transition effect to slide in the sidebar */
}

/* The sidebar links */
.sidebar a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: var(--default);
  display: block;
  transition: 0.3s;
}

/* When you mouse over the navigation links, change their color */
.sidebar a:hover {
  color: var(--color-primary);
}

/* Position and style the close button (top right corner) */
.sidebar .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

/* The button used to open the sidebar */
.openbtn {
  font-size: 20px;
  cursor: pointer;
  padding: 10px 15px;
  border: none;

  box-shadow: 3px 3px var(--color-complimentary),
    -0.1em -0.1em 0.4em var(--color-complimentary);
  background: linear-gradient(var(--default), var(--color-primary));
  color: var(--color-secondary);
}

/* Style page content - use this if you want to push the page content to the right when you open the side navigation */
#main {
  transition: margin-left 0.5s; /* If you want a transition effect */
  padding: 20px;
}
   <div id="mySidebar" class="sidebar">
        <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
    <ul>
        <li><a href="#about-me">About Me</a></li>
        <li><a href="#skills">Skills</a></li>
        <li><a href="#projects">Projects</a></li>
        <li><a href="#experience">Experience</a></li>
        <li><a href="#education"> Education </a></li>
        <li> <a href="#contact">Contact</a></li>
    </ul>
      </div>
      
      <div id="main">
        <button class="openbtn" onclick="openNav()">&#9776; Open Menu</button>
      </div>   

How to wait for multiple API calls to reutrn?

I have an array of APIs to query. For example var urls = ['example.org?x=1', 'example.org?x=2,3'] How can I have ReactJS wait for all the responses to come back before responding to the client?

I’ve tried a modification @Shanoor’s answer from Promises with http.get node.js but the result to the client is empty ("").

var http = require('http');
var urls = ['example.org', 'example2.org', '...'];

var done = 0;
var result = [];

function callback(index, data) {
  result[index] = data;
  done++;
  if (done == urls.length) {
    result.forEach(console.log);
    //I tried using the resp object here to return result[] but the data seemed corrupt 
  }
}

function processUrl(url, index) {
  var finalData = '';
  http.get(url, function(response) {
    response.setEncoding('utf8');
    response.on('data', function(data) {
      finalData += data;
    });
    response.on('error', console.error);
    response.on('end', function() {
      callback(index, finalData);
    })
  });
}

app.get("/api/blah", (resp) => {
  urls.forEach(processUrl);
  //resp(result); this would result in an empty response
}

How to Delete Image from Firebase cloud Storage – REACT

I have the following structure in my Storage, Post/ID/image.jpg . Post and ID are folders that can be found easily but ID may contain multiple images. How could I possibly delete all of them ?
Inside my code, I have a function that should delete Posts inside firestore database and delete the images reference from the firebase storage

The error thrown is :

TypeError: Cannot read properties of undefined (reading ‘_throwIfRoot’)

Delete Function

const DeletePost = async (e) => {
    e.preventDefault();
    const querySnapshot = await getDocs(collection(db, `${category}Posts`));
    querySnapshot.forEach((docx) => {
        if (post.AdTitle === docx.data().AdTitle) {
            try {
                deleteObject(ref(storage, `${category}Posts`, docx.id).child);
                deleteDoc(doc(db, `${category}Posts`, docx.id));
            } catch (error) {
                console.log("error in delete image, " + error);
            }
            // router.reload();
        }
    });
};

discord.js Can’t add a role to member

I wan’t my bot to give a certain role to people when they join the server. But I get some weird error I don’t really understand.
This is the code

const { GuildMember, MessageEmbed } = require("discord.js");

module.exports = {
    name: "guildMemberAdd",
    /**
     * @param {GuildMember} member
     */
    async execute(member){
        let role = member.guild.roles.cache.some(role => role.name === 'Member')
        member.roles.add(role)

        member.guild.channels.cache.get(process.env.WELCOME_MESSAGE_CHANNEL_ID).send({ 
            embeds: [
                new MessageEmbed()
                .setTitle("Welcome! :smiley:")
                .setDescription(`${member.toString()} has joined the server!n
                                Thanks for joining. Head over to <#${process.env.RULE_CHANNEL_ID}> and verify yourself in <#${process.env.VERIFY_CHANNEL_ID}> to get access to all other channels.`)
                .setThumbnail(member.user.displayAvatarURL())
                .setColor("GREEN")
            ]
        }) 
    }
}

And after someone joins I get this error message
TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.

Return function failing to return in catch function using Discord.JS

I’m working on a react command to make the bot react to the given message ID, but the problem is that it works fine if it’s an emoji, but if it’s not an emoji, it says Please use a valid emoji! and then says Reacted with (emoji), despite the fact that I made the catch function return after saying Please use a valid emoji!, so I’m pretty confused, is there any way around it?

The code:

const { MessageEmbed } = require('discord.js')

module.exports = {
    name: 'react',
    category: 'Staff',
    aliases: [],
    description: 'Reacts to a message.',
    usage: 'react <messageID> <emoji>',
    userperms: [],
    botperms: [],
    run: async (client, message, args) => {
    if (message.author.bot) return;

    let emoji = args[1];
    let messageID = args[0];

    if (!messageID) return message.reply('Please state the messageID!')
    if (!emoji) return message.reply('Please state the emoji')

  if (messageID && emoji) {

    message.channel.messages.fetch(messageID)
      .catch(err => {
        if (err.code === 10008){
            message.channel.send('I cannot find this message!');
            return;
        }
        if (err.code === 50035){
            message.channel.send('Please state a valid Message ID!');
            return;
        }
      });
      message.channel.messages.fetch(messageID)
      .then(msg => {
        msg.react(emoji)
        .catch(() => {
          message.channel.send('Please use a valid emoji!')
          return
        })
        setTimeout(function(){
          message.channel.send('Please wait...').then(m =>
            setTimeout(function(){
              m.edit('Reacted with ' + emoji)
              return
            }, 1500)
          )
        }, 2000)
      })
    }
  }
}

Thanks 😀

javascrupt- ho do i check diagonal win in TIC Tac Toe?

i created a Tic Tac Toe game on javascript and HTML. in the game the user can choose on how many columes and rows he wants to play. i was abble to check win in a row and a colum but i don’t have any idea for a diagonal. I need to make it as simple as posible, and i will be very thenkfull if someone can help.
here is the javascript code:

var rows;
var cols;
var Array;
var tor = 0;
function XO() {
    rows = +prompt("Enter rows : ");
    cols = +prompt("Enter cols : ");

    intBoard = new Array(rows);
    var r, c;
    for (r = 0; r < intBoard.length; r++) {
        intBoard[r] = new Array(cols);
        for (c = 0; c < cols; c++) {
            intBoard[r][c] = 0;
        }
    }

    var idNum = 0;
    var strToShow = "<table border='1'>";
    for (var r = 0; r < rows; r++) {
        strToShow = strToShow + "<tr>";
        for (var c = 0; c < cols; c++) {
            strToShow = strToShow + "<td id='" + idNum.toString() +
                " ' onclick='TdClicked(this)' width='80px' height='80px' >";
            //strToShow = strToShow + idNum.toString();
            strToShow = strToShow + "<img src='background.jpg' width='80px' height='80px' />";
            strToShow = strToShow + "</td>";
            idNum++;
        }
        strToShow = strToShow + "</tr>";
    }
    strToShow = strToShow + "</table>";
    document.write(strToShow);
}


var showfirst = 0;
function TdClicked(tdClickedThis) {
    var idClicked = tdClickedThis.id;
    var rowClicked = Math.floor(idClicked / cols);
    var colClicked = idClicked % cols;

    if (showfirst == 0) {
        document.getElementById(idClicked).innerHTML = "<img width='80px' height='80px' src='wolf.jpg'/>";
        showfirst++;
        intBoard[rowClicked][colClicked] = 1;

        for (c = 0; c < cols; c++) {           // check win in column
            if (intBoard[rowClicked][c] != 1)
                c = cols + 111;   //break;
        }
        if (c == cols)
            alert("PLAYER X WIN!!")


        for (r = 0; r < rows; r++) {           // check win in row
            if (intBoard[r][colClicked] != 1)
                r = rows + 111;   //break;
        }
        if (r == rows)
            alert("PLAYER X WIN!!")


        
    }

    else {
        document.getElementById(idClicked).innerHTML = "<img width='80px' height='80px' src='fox.png'/>";
        showfirst--;
        intBoard[rowClicked][colClicked] = 2;

        for (c = 0; c < cols; c++) {            //check win in column
            if (intBoard[rowClicked][c] != 2)
                c = cols + 111;   //break;
        }
        if (c == cols)
            alert("PLAYER O WIN!!")


        for (r = 0; r < rows; r++) {            // check win in row
            if (intBoard[r][colClicked] != 2)
                r = rows + 111;   //break;
        }
        if (r == rows)
            alert("PLAYER O WIN!!")

    }
}

connect a servise worker to a contect script

In short, I want that when you press my extension button from the context menu, the content script (contect-script) will be added to the web page temporarily. I tried to use sendMessage() but it just didn’t work.

Any help will be appreciated:)

//This is the servise worker (eventPage)

chrome.runtime.onInstalled.addListener(() => {
 chrome.contextMenus.create({
   id: 'select',
   title: 'select',
   type: 'normal',
   contexts: ['all']
 });

})
chrome.contextMenus.onClicked.addListener(function (clickDate) {
 if (clickDate.menuItemId == 'select') {
   //send massege to make content-script start operate
  chrome.runtime.sendMessage('start');

 }
});



-------------------------------------------------------------------------


//lets say that this is the content-script
chrome.runtime.onMessage.addListener(function(response,sender,sendResponse){

if(response == 'start'){

// js code that is inserted into the site
}
});
{
"manifest_version": 3,

"name": "SendFast",
"description": "This extension makes it easier to send information",
"version": "1.0",
"icons": {
  "128": "16-nahum.png",
  "48": "64-nahum.png",
  "16": "16-nahum.png"
},

"action": {
  "default_icon": "16-nahum.png",
  "default_popup": "popup.html"
},
"permissions":["contextMenus","activeTab"],


"background":{
  "service_worker": "eventPage.js"
},
"content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content-script.js"]
  }
]

}

change day by clicking on buttom

i want each time that im clickig on button that show me the Next day from day array list , can some one help me ?( the only way that i could get a answer is Math.random() to have difference result each time i am clicking on button , but i want that show me the next day each time i am clicking on it .


<button onclick='day()'>Click to see</button>
<script>
    function day(){
       var days =['Monday','Thuesady','Wensday','Thursday','Friday','Saturday','Sunday']
        document.getElementById("demo").innerHTML = days[Math.floor(Math.random() *7)];} 
        
    }
</script>