Table only appears for a split second on button click

I have a button and a table on my webpage. I want to view the table when I click that button. I have tried it using javascript but the table only appears for a split second and then disappears. following is the code for my table:

var button = document.getElementById('BtnNextInsured'); // Assumes element with id='button'

button.onclick = function() {
  var div = document.getElementById('tblContact');
  if (div.style.display !== 'none') {
    div.style.display = 'none';
  } else {
    div.style.display = 'block';
  }
};
<button id="BtnNextInsured" class="btn btn-md btn-primary">Next</button> Table to show:

<table id="tblContact" class="table table-light table-borderless" style="display:none;">
  <tr>
    <td class="cellContent">
      <input id="txtEmail" class="txt" placeholder="Email" />
    </td>
    <td class="cellContent">
      <input id="txtCell" class="txt" placeholder="Cell Phone" />
    </td>
    <td class="cellContent">
      <input id="txtLandline" class="txt" placeholder="Landline" />
    </td>
  </tr>

  <tr>
    <td colspan="3" style="text-align: right">
      <button id="BtnNextContact" class="btn btn-md btn-primary">Next</button>
    </td>
  </tr>
</table>

I don’t understand wha’ts wrong with my code, I am a beginner to javascript. Kindly help, thank you.

add clickable element on react js

id like to create on click on react js but it seems probably wrong, the code i copy from google below

const Movies = () => {
    const getMovies = () => {
        return [{
                desc: "A tale of some people watching over a large portion of space.",
                id: 1,
                icon: "fa-solid fa-galaxy",
                image: "https://images.unsplash.com/photo-1596727147705-61a532a659bd?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8bWFydmVsfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60",
                title: "Protectors of the Milky Way",
                href: "https://www.wikipedia.com"
            }

the href is not working when i click it, can u guys help me out?

Rotate a rectangle in

I am making a geometry dash game. I am now trying to rotate the rectangle I am constantly drawing. I need to make it so it does a full 180 on a basic jump. Everything I tried just broke everything and the canvas was 5 times smaller. How do I do that?

The code below is from different files and the order might not be right

//player class

class Player {
  constructor() {
    this.position = {
      x: 280,
      y: 100,
    }

    this.velocity = {
      x: 0,
      y: 0,
    }

    this.width = 50
    this.height = 50
    this.sides = {
      bottom: this.position.y + this.height,
      left: this.position.x,
      right: this.position.x + this.width,
      top: this.position.y,
    }
    this.gravity = 1
  }

  draw() {
    c.fillStyle = 'red'
    c.fillRect(this.position.x, this.position.y, this.width, this.height)
  }

  update() {
    this.position.x += this.velocity.x
    this.position.y += this.velocity.y
    this.sides.bottom = this.position.y + this.height
    if (this.sides.bottom + this.velocity.y < canvas.height - this.height) {
      this.velocity.y += 1

    } else this.velocity.y = 0
  }
}

//index file

const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')

canvas.width = 1024
canvas.height = 576

const background = {
  position: {
    x: 0,
    y: 0,
  }
}



const player = new Player()

const keys = {
  w: {
    pressed: false,
  },
}

function animate() {
  window.requestAnimationFrame(animate)
  c.clearRect(background.position.x, background.position.y, canvas.width, canvas.height)

  player.velocity.x = 0
  player.draw()
  player.update()
}

animate()

//events file

window.addEventListener('keydown', (event) => {
  switch (event.key) {
    case 'w':
      if (player.velocity.y === 0 || jumps > 0) {
        player.velocity.y = -17.5;
        rotate = true;
        angle += Math.PI;
      }
  }
});

function update() {
  player.velocity.y += gravityAcceleration;

  player.position.x += player.velocity.x;
  player.position.y += player.velocity.y;

  if (player.position.y >= canvas.height - player.height) {
    player.position.y = canvas.height - player.height;
    player.velocity.y = 0;
  }

}
body {
  background: black;
}

canvas {
  background-color: white;
}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="style.css">

<head></head>

<body>
  <canvas></canvas>
</body>

<script src="js/classes/Player.js"></script>
<script src="js/classes/events.js"></script>
<script src="index.js"></script>

</html>

How to keep current page number active when i click Go Back in my other component in React JS

How to keep current page number active when i click Go Back in my other component in React JS.
I have Three components first is Design Component, second is Pagination Component and third is Item Details component. When i click on data coming from API , it uses ID and take me to the ItemDetails component of that specific ID. In ItemDetails component, i created a button which is ‘Go Back’. I want to come back on my current page where i clicked the ID but when i click on Go Back button it takes me to the first Page.

Here is my Design Component where i want to use localStorage concept but how to use it?, i don’t know.

    // /* eslint-disable react/prop-types */ // TODO: upgrade to latest eslint tooling
import "../src/App.css";
import axios from "axios";
import { useEffect, useState, useMemo } from "react";
import Pagination from "./Pagination";
import { Link } from "react-router-dom";

let PageSize = 2;

export default function Design() {
  const [search, setSearchTerm] = useState("all");
  const [records, setRecords] = useState([]);
  const [suggestions, setSuggestions] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);

useEffect(() => {
  const data = window.localStorage.getItem('pnum');
  console.log(`data is: ${data}`)
  if(data !== null) setCurrentPage(JSON.parse(data))
},[])

useEffect(() => {
window.localStorage.setItem('pnum', JSON.stringify(currentPage))
},[currentPage])

  const currentTableData = useMemo(() => {
    const firstPageIndex = (currentPage - 1) * PageSize;
    const lastPageIndex = firstPageIndex + PageSize;
    return records.slice(firstPageIndex, lastPageIndex);
  }, [currentPage, records]);

  useEffect(() => {
    searchRecords();
  }, []);

  const searchRecords = async () => {
    try {
      const res = await axios.get(`https://fruityvice.com/api/fruit/${search}`);
      setRecords(search === "all" ? res.data : [res.data]);
    } catch (error) {
      console.error("Error searching record:", error);
      setRecords([]);
    }
  };

  const fetchSuggestions = async (input) => {
    try {
      const res = await axios.get(`https://fruityvice.com/api/fruit/all`);
      const fruits = res.data.map((fruit) => fruit.name);
      const filteredSuggestions = fruits.filter((fruit) =>
        fruit.toLowerCase().includes(input.toLowerCase())
      );
      setSuggestions(filteredSuggestions);
    } catch (error) {
      console.error("Error fetching suggestions:", error);
      setSuggestions([]);
    }
  };

  const handleInputChange = (e) => {
    const inputValue = e.target.value;
    setSearchTerm(inputValue);
    fetchSuggestions(inputValue);
  };

  const getTotalNutritions = (item) => {
    return Object.values(item.nutritions).reduce(
      (total, value) => total + Math.trunc(value),
      0
    );
  };

  return (
    <>
      <h1 className="main--heading">Fruit Project</h1>
      <div className="main">
        <input
          className="input"
          onChange={handleInputChange}
          list="suggestions"
          placeholder="Search Fruit"
        />
        <datalist id="suggestions">
          {suggestions.map((fruit, index) => (
            <option key={index} value={fruit} />
          ))}
        </datalist>
        <button className="btn" onClick={searchRecords}>
          Search Fruit
        </button>
      </div>
      <div>
        <table>
          <thead>
            <tr>
              <th>Sr No</th>
              <th>Name</th>
              <th>Family</th>
              <th>Order</th>
              <th>Nutritions</th>
              <th>Genus</th>
            </tr>
          </thead>
          <tbody>
            {Array.isArray(currentTableData) && currentTableData.length > 0 ? (
              currentTableData
                .sort((a, b) => a.id - b.id)
                .map((item) => (
                  <tr key={item.id}>
                    <td>{item.id}</td>
                    {/* <td>{item.name}</td> */}
                    <td>
                <Link to={`/details/${item.id}`}>View Details</Link>
                    </td>
                    <td>{item.family}</td>
                    <td>{item.order}</td>
                    <td>{getTotalNutritions(item)}</td>
                    <td>{item.genus}</td>
                  </tr>
                ))
            ) : (
              <tr>
                <td>No data available</td>
              </tr>
            )}
          </tbody>
        </table>
        <Pagination
          className="pagination-bar"
          currentPage={currentPage}
          totalCount={records.length}
          pageSize={PageSize}
          onPageChange={(page) => {setCurrentPage(page)}
          }
        />
      </div>
    </>
  );
}

and my itemDetails component is :

import { useParams } from 'react-router-dom';
import { Link } from 'react-router-dom';

const ItemDetails = () => {
  const { id } = useParams();   

  return (
    <div>
      <h2>Item Details</h2>
      <p>{`${id}:I am stuck there.`}</p>
      <Link  to={`/`} style={{ textDecoration: 'none' }}>Go Back</Link>

    </div>
  );
};

export default ItemDetails;

Jerky horizontal scroll with javascript wheel event

I am working on an application that allows the user to scroll horizontally in 2 ways:

  • click and drag
  • using the mouse wheel event

The problem is that I can’t get a smooth scroll in the second case.

When I use the mouse wheel the container moves in units of 100 pixels at once, which gives a jerky scroll. Do you know how I could improve this in javascript? Thank you

const scrollContainer = document.querySelector("main");

        let isDown = false;
        let startX;
        let scrollLeft;

        scrollContainer.addEventListener('mousedown', (e) => {
            isDown = true;
            startX = e.pageX - scrollContainer.offsetLeft;
            scrollLeft = scrollContainer.scrollLeft;
        });

        scrollContainer.addEventListener('mouseleave', () => {
            isDown = false;
        });

        scrollContainer.addEventListener('mouseup', () => {
            isDown = false;
        });

        scrollContainer.addEventListener('mousemove', (e) => {
            if(!isDown) return;
            e.preventDefault();
            const x = e.pageX - scrollContainer.offsetLeft;
            const walk = (x - startX) * 2; //scroll-fast
            scrollContainer.scrollLeft = scrollLeft - walk;
        });

        // jerky scroll with wheel
        scrollContainer.addEventListener("wheel", (evt) => {
            evt.preventDefault();
            scrollContainer.scrollLeft += evt.deltaY;
        });

Bot doesn’t check if the channel with a specific name already exists! || Discord.JS V.14

This is my code:

const {
  EmbedBuilder,
  ChannelType,
} = require("discord.js");

const serverId = "1110927555693924659";
const categoryId = "1114273709084191765";

client.on("messageCreate", async (message) => {
  if (message.channel.type === ChannelType.DM && !message.author.bot) {
    const guild = client.guilds.cache.get(serverId);
    const category = guild.channels.cache.get(categoryId);

    const channel = guild.channels.cache.find(
      (channel) =>
        channel.name === message.author.id.toString() &&
        channel.parentID === category.id
    );

    const embed = new EmbedBuilder()
      .setColor("#0099ff")
      .setTitle("New Message")
      .setDescription(message.content)
      .setAuthor({
        name: message.author.tag,
        iconURL: message.author.displayAvatarURL(),
      });

    if (channel) {
      await channel.send({ embeds:  });
    } else {
      const channel = await guild.channels.create({
        name: message.author.id.toString(),
        type: ChannelType.GuildText,
        parent: category,
      });

      await channel.send({ embeds:  });
    }
  }
});

I try to log messages that are sent to my bot via DMs to a channel. This code creates a channel with the ID of the user as a name when someone sends a message to my bot’s DM and sends the message there as an Embed Message. The bot must search in the categoryId if there is a channel with the same User ID as the user who sent the message then the bot must send the new User message there. If the bot doesn’t have a channel created with the User’s ID then the bot must create a new channel and send the User’s message there. The problem is when I send a message a second time it creates a second channel with my ID instead of sending my message in the channel that was previously created! Any answer is accepted.

My Intents & Partials:

Intents:
Guilds,
GuildMembers,
GuildMessages,
MessageContent,
DirectMessages,
GuildVoiceStates

Partials:
User,
Message,
GuildMember,
ThreadMember,
Channel

NOTE:

Both of these articles 1) & 2) are outdated and doesn’t resolve my problem.

Cant loop through array of object in Vue#

Cant loop trough array of object in Vue3

<template>
  <div
    class="shadow-xl w-96 h-96 md:h-[600px] md:w-[600px] lg:my-12 lg:w-[700px] lg:h-[700px] rounded-md"
  >
    <button @click="getData">Get data</button>
    <ul v-for="question in questions" :key="question.answer">
      <li>{{ question.answer }}</li>
    </ul>
  </div>
</template> 

and the data looks like this:

questions: [
        { "answer": "Paris", "correct": true },
        { "answer": "Tokio", "correct": false },
        { "correct": false, "answer": "Dubai" },
        { "answer": "London", "correct": false }
      ]

they are in databse and i fetch them correcty; if i use

<ul v-for="question in questions" :key="question.answers">
      <li>{{ question.answers }}</li>

i get an array of an object that looks like this:

[ { "answer": "Paris", "correct": true }, { "answer": "Tokio", "correct": false }, { "answer": "Dubai", "correct": false }, { "answer": "London", "correct": false } ]

but if i want to show only cities name so i change the code to :

<ul v-for="question in questions" :key="question.answers">
      <li>{{ question.answer }}</li>

or even

   <ul v-for="question in questions" :key="question.answers">
      <li>{{ question.answers.answer }}</li>

but it doesnt work, where do i make a mistake?
i have 2 questions as a document in firestore. I thoght maybe i should you v-for two times…

<ul v-for="question in questions" :key="question.answers">
      <li>{{ question.answer }}</li>

or even

   <ul v-for="question in questions" :key="question.answers">
      <li>{{ question.answers.answer }}</li>

How can compress file or image in hayageek js file upload plugin

During file upload, I need to compress or reduce the size of a file or image. The maximum allowed file size is specified as 16MB. Therefore, if the file or image size exceeds 16MB even after compression, it should not be uploaded.

Attaching my code block as well.

var upload_id=null;
var uploader = $(" #fileuploader").uploadFile({
    url: "/ezekyc/kyc/upload",
    fileName: "file",
    enctype: "multipart/form-data",
    sequential: true,
    sequentialCount: 1,
    maxFileSize: 16 * 1024 * 1024,
    autoSubmit: false,
    acceptFiles: "jp/*",
    dynamicFormData: function(file, xhr, pd)
    {
         upload_id = $("input[name='upload_id']:checked").val();
        var data = {
            "kycId": ezekyc.kycId,
            "documentType": upload_id,
            "pageNumber": findUploadCount(ezekyc.uploadedDocuments)
        };
        return data;
    },
    onSuccess: function(files, data, xhr, pd) {
        if (data.success) {
            if (ezekyc && data.kyc && data.kyc.uploadedDocuments)
                ezekyc.uploadedDocuments = data.kyc.uploadedDocuments;
            $('.ajax-file-upload-container').find('.ajax-file-upload-statusbar').each(function(index){
                               var name=('.ajax-file-upload-filename',$(this) ).text();
                               if(name && files &&  files[0] && name.search(files[0]) ){
                                      $(this).remove();
                               }
        });
    }
    },
    onError: function(files, status, errMsg, pd) {
        cancel();
        hidecardAggr11(upload_id);
    },
    afterUploadAll:function(obj)
    {
         loadup();
         hidecardAggr11(upload_id);
         console.log("loaded all");
    }
 });

var cancel = function() {
    uploader.stopUpload();
};

$("#extrabutton").click(function() {
    if(uploader.selectedFiles==0){
        toast("Please select files to upload");
    }
    uploader.startUpload();
});

$("#clearButton").click(function() {
    uploader.cancelAll();
});

I tried to use pako plugin with hayageek plugin but it is not working

beforeSend: function(file, xhr, pd) {
    var fileReader = new FileReader();
    fileReader.onload = function(e) {
      var compressedData = pako.gzip(e.target.result);
      xhr.setRequestHeader('Content-Encoding', 'gzip');
      pd.data = compressedData;
      pd.filename = file.name + '.gz';
    };
    fileReader.readAsArrayBuffer(file);
  },

How to create collapsible contents with jQuery, HTML, and CSS using CSS grid layout and solve overlapping card issue?

I’m trying to hide and show elements using jQuery + HTML + CSS to create collapsible contents from clicking on buttons.

To do this, I applied CSS grid for the layout of cards. Then use jQuery to hide other cards. For example, I want to only show project belong to group 2, so project belongs to group 1 and 3 will be hidden when I clicked “Group 2”. My code does hide them, however, the appearing cards do not overlap the hidden cards, which create awkward spaces. Any help/advice would be greatly appreciated! Thank you so much <33

enter image description here
enter image description here

jQuery(function() {
    jQuery(".allbutton").click(function() {
        jQuery(".single").fadeIn(); 
    }); 
    jQuery(".button").click(function() {
        jQuery(".single").css("display", "none"); 
        jQuery(".div" + $(this).attr('target')).fadeIn();
    }); 
}); 

How to Get Geolocation in NodeJS

I’m currently working on a Node.js project where I need to retrieve the user’s location without relying on external packages or APIs. Most of the solutions I’ve found involve using packages or making API requests, which are not suitable for my requirements.

I’m looking for advice from the community on alternative methods or approaches to achieve this. Since I’m unable to use external packages or APIs, I’m seeking insights into any built-in modules or techniques within Node.js itself that can assist in retrieving the user’s location.

I appreciate any insights or suggestions. Thank you in advance!

How to maintain types of values when extracting keys and values from a JavaScript object in Python?

I need to gather the content of js object while maintaining the values’ type.

for example I have a js file with the next content

const rules = {
    force_update_cache: true,
    country: 'gb',
    override_headers: {
      'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
    },
    navigate_opt: {wait_until: ['domcontentloaded'], timeout: 60*SEC},
}

I want to extract the keys and values of rules while maintaining the original type of the values.

I regexed my way to read only the keys and values without the “const rules {, }”.
I tried using ast.literal_eval but it doesn’t work propely.

I expect to get evantually a dictionary with the keys, and values with their original type.

string.
number.
integer.
object.
array.
boolean.
null.

Is there a solution for that?

Expanding children nodes in Echarts sunburst graph to avoid overlapping with circle

I have a sunburst graph in echarts, which looks like this:

enter image description here

I want to try and branch out the children nodes further, so that they are visible and not overlapping with the circle of the sunburst, is there any way i could do this? Instead of being in the circle, I want it to be outside.

I am not very good with javascript, any suggestions or ideas will be greatly appreciated

Doesn’t mousePressedOver() detect touches from mobile too, If doesn’t what function to use instead?

This is the line I’m facing with, I want to detect mouse click when being used in PC(which is working completey fine) and to detect clicks when used in mobile too.

 if (keyDown("left") || mousePressedOver(left)) {
            sofia.velocityX = -1
            sofiavelocityY = 0
        }

Note: I’m using p5.js, p5.play.js & p5.dom.min.js

I tried several other mouse click functions such as mouseOver etc.